Example #1
0
func (p *Page) getParam(key string, stringToLower bool) interface{} {
	v := p.Params[strings.ToLower(key)]

	if v == nil {
		return nil
	}

	switch v.(type) {
	case bool:
		return cast.ToBool(v)
	case string:
		if stringToLower {
			return strings.ToLower(cast.ToString(v))
		}
		return cast.ToString(v)
	case int64, int32, int16, int8, int:
		return cast.ToInt(v)
	case float64, float32:
		return cast.ToFloat64(v)
	case time.Time:
		return cast.ToTime(v)
	case []string:
		if stringToLower {
			return helpers.SliceToLower(v.([]string))
		}
		return v.([]string)
	case map[string]interface{}: // JSON and TOML
		return v
	case map[interface{}]interface{}: // YAML
		return v
	}

	jww.ERROR.Printf("GetParam(\"%s\"): Unknown type %s\n", key, reflect.TypeOf(v))
	return nil
}
Example #2
0
func toSortedLanguages(l map[string]interface{}) (helpers.Languages, error) {
	langs := make(helpers.Languages, len(l))
	i := 0

	for lang, langConf := range l {
		langsMap, err := cast.ToStringMapE(langConf)

		if err != nil {
			return nil, fmt.Errorf("Language config is not a map: %T", langConf)
		}

		language := helpers.NewLanguage(lang)

		for loki, v := range langsMap {
			switch loki {
			case "title":
				language.Title = cast.ToString(v)
			case "languagename":
				language.LanguageName = cast.ToString(v)
			case "weight":
				language.Weight = cast.ToInt(v)
			}

			// Put all into the Params map
			language.SetParam(loki, v)
		}

		langs[i] = language
		i++
	}

	sort.Sort(langs)

	return langs, nil
}
Example #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
}
Example #4
0
func (rs *SortableRowSet) IsLess(origin *TableRow, than *TableRow) bool {
	for _, val := range rs.cols {
		if val.Orderable && val.Order != ORDER_UNDEFINED {
			if res := strings.Compare(cast.ToString(origin.Data[val.Name]), cast.ToString(than.Data[val.Name])); res != 0 {
				if val.Order == ORDER_DESC {
					return res == -1
				} else {
					return res == 1
				}
			}
		}
	}
	//no ordering provided, base on string pointers
	return strings.Compare(fmt.Sprintf("%p", origin.Data), fmt.Sprintf("%p", than.Data)) == -1
}
Example #5
0
func parseOrdering(formValues map[string]interface{}) map[string]DataTableOrder {
	ordering := map[string]DataTableOrder{}
	if orders, ok := formValues["order"]; ok {
		for _, val := range orders.(map[string]interface{}) {
			mapValue := val.(map[string]interface{})
			column, columnExists := mapValue["column"]
			dir, dirExists := mapValue["dir"]
			if columnExists && dirExists {
				ordering[cast.ToString(column)] = DataTableOrder(cast.ToString(dir))
			}
		}
	}

	return ordering
}
Example #6
0
func (me *MenuEntry) MarshallMap(ime map[string]interface{}) {
	for k, v := range ime {
		loki := strings.ToLower(k)
		switch loki {
		case "url":
			me.Url = cast.ToString(v)
		case "weight":
			me.Weight = cast.ToInt(v)
		case "name":
			me.Name = cast.ToString(v)
		case "parent":
			me.Parent = cast.ToString(v)
		}
	}
}
Example #7
0
// Get returns an interface..
// Must be typecast or used by something that will typecast
func (manager *Config) Get(key string) interface{} {
	jww.TRACE.Println("Looking for", key)

	v := manager.Find(key)

	if v == nil {
		return nil
	}

	jww.TRACE.Println("Found value", v)
	switch v.(type) {
	case bool:
		return cast.ToBool(v)
	case string:
		return cast.ToString(v)
	case int64, int32, int16, int8, int:
		return cast.ToInt(v)
	case float64, float32:
		return cast.ToFloat64(v)
	case time.Time:
		return cast.ToTime(v)
	case []string:
		return v
	}
	return v
}
Example #8
0
func (v *Viper) Get(key string) interface{} {
	key = strings.ToLower(key)
	val := v.find(key)

	if val == nil {
		return nil
	}

	switch val.(type) {
	case bool:
		return cast.ToBool(val)
	case string:
		return cast.ToString(val)
	case int64, int32, int16, int8, int:
		return cast.ToInt(val)
	case float64, float32:
		return cast.ToFloat64(val)
	case time.Time:
		return cast.ToTime(val)
	case time.Duration:
		return cast.ToDuration(val)
	case []string:
		return val
	}
	return val
}
Example #9
0
func (ds *DefaultStore) FilterRow(row *TableRow, filter *SearchDefinition, rowSet RowSet) bool {
	if row == nil || len(row.Data) == 0 {
		return false
	}
	foundGlobally := true
	for name, value := range row.Data {
		strValue := cast.ToString(value)

		if filter.IsApplicable() {
			if filter.IsMatch(strValue) {
				return true
			} else {
				foundGlobally = false
			}
		}

		if col := rowSet.ColumnByName(name); col != nil {
			if col.Searchable && col.Search.IsApplicable() {
				if !col.Search.IsMatch(strValue) {
					return false
				}
			}
		}
	}

	return foundGlobally
}
Example #10
0
func (v *Viper) Get(key string) interface{} {
	lcaseKey := strings.ToLower(key)
	val := v.find(lcaseKey)
	if val == nil {
		return nil
	}

	valType := val
	if v.typeByDefValue {
		// TODO(bep) this branch isn't covered by a single test.
		path := strings.Split(lcaseKey, v.keyDelim)
		defVal := v.searchMap(v.defaults, path)
		if defVal != nil {
			valType = defVal
		}
	}

	switch valType.(type) {
	case bool:
		return cast.ToBool(val)
	case string:
		return cast.ToString(val)
	case int64, int32, int16, int8, int:
		return cast.ToInt(val)
	case float64, float32:
		return cast.ToFloat64(val)
	case time.Time:
		return cast.ToTime(val)
	case time.Duration:
		return cast.ToDuration(val)
	case []string:
		return cast.ToStringSlice(val)
	}
	return val
}
// markdownify renders a given string from Markdown to HTML.
func markdownify(in interface{}) template.HTML {
	text := cast.ToString(in)
	m := helpers.RenderBytes(&helpers.RenderingContext{Content: []byte(text), PageFmt: "markdown"})
	m = bytes.TrimPrefix(m, markdownTrimPrefix)
	m = bytes.TrimSuffix(m, markdownTrimSuffix)
	return template.HTML(m)
}
Example #12
0
func (c *Conf) AutoRepair() {
	fullUriPattern, _ := regexp.Compile("(http[s]{0,1})://([^/:]+):?([0-9]{0,}).*")
	if !fullUriPattern.MatchString(c.EndpointURI) {
		protocol := "https"
		host := getDefaultHostName()
		port := cast.ToString(c.ServerPort)
		hostWithPortPattern, _ := regexp.Compile("([^:/]+):?([0-9]{0,})")
		repaired := false

		if hostWithPortPattern.MatchString(c.EndpointURI) {
			matches := hostWithPortPattern.FindAllStringSubmatch(c.EndpointURI, -1)
			if val := matches[0][1]; val != "" {
				host = val
			}
			if val := matches[0][2]; val != "" {
				port = val
			}
			repaired = true
		}

		if repaired {
			c.EndpointURI = fmt.Sprintf("%s://%s:%s/", protocol, host, port)
			log.Printf("EndpointURI successfully reparied to: %s", c.EndpointURI)
		}
	}
}
Example #13
0
func (c *Config) loadRedirects(seq sequence) {
	// if seq.valForKey("redirects") != "" {
	// 	panic("Configuration error: redirects should be a list of paths and destinations")
	// }
	// TODO: assert right content types (not string val, not value sequence)
	c.redirects = make(map[string]string)
	for _, el := range seq.seqForKey("redirects") {
		path := cast.ToString(el.key)
		dest := cast.ToString(el.value)
		if strings.HasPrefix(path, "/") {
			c.redirects[path[1:]] = dest
		} else {
			c.redirects[path] = dest
		}
	}
}
Example #14
0
func (c *Config) loadS3Bucket(seq sequence) {
	val := cast.ToString(seq.valForKey("s3_bucket"))
	if val == "" {
		panic("Configuration error: s3_bucket is missing")
	}
	c.S3Bucket = val
}
Example #15
0
func (c *Config) loadS3Region(seq sequence) {
	val := cast.ToString(seq.valForKey("s3_region"))
	if val == "" {
		val = s3RegionDefault
	}
	c.S3Region = val
}
Example #16
0
// Get can retrieve any value given the key to use
// Get returns an interface. For a specific value use one of the Get____ methods.
func (c RawConfig) Get(key string) interface{} {
	path := strings.Split(key, keyDelim)

	val := c.find(strings.ToLower(key))

	if val == nil {
		source := c.find(path[0])
		if source == nil {
			return nil
		}

		if reflect.TypeOf(source).Kind() == reflect.Map {
			val = c.searchMap(cast.ToStringMap(source), path[1:])
		}
	}

	switch val.(type) {
	case bool:
		return cast.ToBool(val)
	case string:
		return cast.ToString(val)
	case int64, int32, int16, int8, int:
		return cast.ToInt(val)
	case float64, float32:
		return cast.ToFloat64(val)
	case time.Time:
		return cast.ToTime(val)
	case time.Duration:
		return cast.ToDuration(val)
	case []string:
		return val
	}
	return val
}
Example #17
0
func parseSitemap(input map[string]interface{}) Sitemap {
	sitemap := Sitemap{Priority: -1, Filename: "sitemap.xml"}

	for key, value := range input {
		switch key {
		case "changefreq":
			sitemap.ChangeFreq = cast.ToString(value)
		case "priority":
			sitemap.Priority = cast.ToFloat64(value)
		case "filename":
			sitemap.Filename = cast.ToString(value)
		default:
			jww.WARN.Printf("Unknown Sitemap field: %s\n", key)
		}
	}

	return sitemap
}
Example #18
0
func (c *Config) loadSourceDirectory(rootDir string, seq sequence) {
	value := cast.ToString(seq.valForKey("source_directory"))
	if value == "" {
		panic("Configuration error: source_directory is missing")
	}
	if !strings.HasPrefix(value, "/") {
		value = filepath.Join(filepath.Dir(rootDir), value)
	}
	c.SourceDirectory = value
}
// readDirFromWorkingDir listst the directory content relative to the
// configured WorkingDir.
func readDirFromWorkingDir(i interface{}) ([]os.FileInfo, error) {

	path := cast.ToString(i)

	list, err := afero.ReadDir(hugofs.WorkingDir(), path)

	if err != nil {
		return nil, fmt.Errorf("Failed to read Directory %s with error message %s", path, err)
	}

	return list, nil
}
// findRE returns a list of strings that match the regular expression. By default all matches
// will be included. The number of matches can be limitted with an optional third parameter.
func findRE(expr string, content interface{}, limit ...int) ([]string, error) {
	re, err := reCache.Get(expr)
	if err != nil {
		return nil, err
	}

	conv := cast.ToString(content)
	if len(limit) > 0 {
		return re.FindAllString(conv, limit[0]), nil
	}

	return re.FindAllString(conv, -1), nil
}
Example #21
0
File: viper.go Project: DLag/viper
func (v *Viper) Get(key string) interface{} {
	path := strings.Split(key, v.keyDelim)

	var val interface{}
	lcaseKey := strings.ToLower(key)
	source := v.find(path[0])
	if source != nil {
		if reflect.TypeOf(source).Kind() == reflect.Map {
			val = v.searchMap(cast.ToStringMap(source), path[1:])
		}
	}

	if val == nil {
		val = v.find(lcaseKey)
	}

	if val == nil {
		return nil
	}

	var valType interface{}
	if !v.typeByDefValue {
		valType = val
	} else {
		defVal, defExists := v.defaults[lcaseKey]
		if defExists {
			valType = defVal
		} else {
			valType = val
		}
	}

	switch valType.(type) {
	case bool:
		return cast.ToBool(val)
	case string:
		return cast.ToString(val)
	case int64, int32, int16, int8, int:
		return cast.ToInt(val)
	case float64, float32:
		return cast.ToFloat64(val)
	case time.Time:
		return cast.ToTime(val)
	case time.Duration:
		return cast.ToDuration(val)
	case []string:
		return cast.ToStringSlice(val)
	}
	return val
}
Example #22
0
func TestAutoRepair(t *testing.T) {
	c := newConfig()

	c.EndpointURI = "test-host.localdomain"
	c.AutoRepair()
	assert.Equal(t, "https://test-host.localdomain:"+cast.ToString(c.ServerPort)+"/", c.EndpointURI)

	c.EndpointURI = "test-host.localdomain:8000"
	c.AutoRepair()
	assert.Equal(t, "https://test-host.localdomain:8000/", c.EndpointURI)

	c.EndpointURI = "http://test-host.localdomain:8000/"
	c.AutoRepair()
	assert.Equal(t, "http://test-host.localdomain:8000/", c.EndpointURI)
}
Example #23
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)
		}
	}
}
Example #24
0
//get Config value by key
func (c *Config) Get(key string) interface{} {
	val := c.get(key)

	switch val.(type) {
	case bool:
		return cast.ToBool(val)
	case string:
		return cast.ToString(val)
	case int64, int32, int16, int8, int:
		return cast.ToInt(val)
	case float64, float32:
		return cast.ToFloat64(val)
	case time.Time:
		return cast.ToTime(val)
	case time.Duration:
		return cast.ToDuration(val)
	case []string:
		return val
	}

	return val
}
Example #25
0
File: config.go Project: dyweb/Ayi
// ReadConfigFile read user defined hosts in .ayi.yml
func ReadConfigFile() {
	log.Debug("Read git section in config file")
	hostsMap = make(map[string]Host)
	hostsSlice := cast.ToSlice(viper.Get("git.hosts"))

	for _, h := range hostsSlice {
		m := cast.ToStringMap(h)
		_, exists := m["name"]
		if !exists {
			log.Warn("Skipp host without name")
			continue
		}

		// TODO: more attributes, the following is not working
		// - http port
		// - support ssh
		name := cast.ToString(m["name"])
		https := cast.ToBool(util.GetWithDefault(m, "https", true))
		port := cast.ToInt(util.GetWithDefault(m, "port", DefaultSSHPort))

		h := NewHost(name)
		h.SupportHTTPS = https
		h.SSHPort = port

		hosts = append(hosts, *h)
		// TODO: may add order to host
		hostsMap[name] = *h
	}

	// only merge default hosts that are not configed in config files
	for _, defaultHost := range DefaultHosts {
		_, exists := hostsMap[defaultHost.URL]
		if !exists {
			hosts = append(hosts, defaultHost)
			hostsMap[defaultHost.URL] = defaultHost
		}
	}
}
Example #26
0
func (page *Page) GetParam(key string) interface{} {
	v := page.Params[strings.ToLower(key)]

	if v == nil {
		return nil
	}

	switch v.(type) {
	case bool:
		return cast.ToBool(v)
	case string:
		return strings.ToLower(cast.ToString(v))
	case int64, int32, int16, int8, int:
		return cast.ToInt(v)
	case float64, float32:
		return cast.ToFloat64(v)
	case time.Time:
		return cast.ToTime(v)
	case []string:
		return sliceToLower(v.([]string))
	}
	return nil
}
Example #27
0
File: site.go Project: jaden/hugo
func (s *SiteInfo) GetParam(key string) interface{} {
	v := s.Params[strings.ToLower(key)]

	if v == nil {
		return nil
	}

	switch v.(type) {
	case bool:
		return cast.ToBool(v)
	case string:
		return cast.ToString(v)
	case int64, int32, int16, int8, int:
		return cast.ToInt(v)
	case float64, float32:
		return cast.ToFloat64(v)
	case time.Time:
		return cast.ToTime(v)
	case []string:
		return v
	}
	return nil
}
Example #28
0
// Get returns an interface..
// Must be typecast or used by something that will typecast
func Get(key string) interface{} {
	key = strings.ToLower(key)
	v := find(key)

	if v == nil {
		return nil
	}

	switch v.(type) {
	case bool:
		return cast.ToBool(v)
	case string:
		return cast.ToString(v)
	case int64, int32, int16, int8, int:
		return cast.ToInt(v)
	case float64, float32:
		return cast.ToFloat64(v)
	case time.Time:
		return cast.ToTime(v)
	case []string:
		return v
	}
	return v
}
Example #29
0
func TestExpand(t *testing.T) {
	var v interface{}
	var err error

	m := map[string]interface{}{
		".cat":                 "garfield",
		".dog":                 "odie",
		".friends.[0]":         "John",
		".turtle":              "0",
		".birdColors.cardinal": "red",
		".birdColors.blueJay":  "blue",
		".57":         int64(57),
		".doesItWork": true,
	}

	v, err = Expand(m, ".cat")
	assert.Equal(t, cast.ToString(v), "garfield")
	assert.Equal(t, err, nil)

	r := map[string]interface{}{
		"cat":     "garfield",
		"dog":     "odie",
		"friends": []interface{}{"John"},
		"turtle":  "0",
		"birdColors": map[string]interface{}{
			"cardinal": "red",
			"blueJay":  "blue",
		},
		"57":         int64(57),
		"doesItWork": true,
	}

	v, err = Expand(m, "")
	assert.Equal(t, cast.ToStringMap(v), r)
	assert.Equal(t, err, nil)
}
Example #30
0
func (me *MenuEntry) MarshallMap(ime map[string]interface{}) {
	for k, v := range ime {
		loki := strings.ToLower(k)
		switch loki {
		case "url":
			me.URL = cast.ToString(v)
		case "weight":
			me.Weight = cast.ToInt(v)
		case "name":
			me.Name = cast.ToString(v)
		case "pre":
			me.Pre = template.HTML(cast.ToString(v))
		case "post":
			me.Post = template.HTML(cast.ToString(v))
		case "identifier":
			me.Identifier = cast.ToString(v)
		case "parent":
			me.Parent = cast.ToString(v)
		}
	}
}