func PeopleMutation(x string, mode string) []string {

	var (

		//		y	=	[]string{"","","","",""}
		y []string

		ckl = int(0)
		num = int(0)
	)

	for strings.Contains(x, "  ") {
		x = strings.Replace(x, "  ", " ", -1)
	}

	y = strings.Split(strings.Trim(strings.ToLower(x), " "), " ")

	num = len(y)

	for ckl = 0; ckl < num; ckl++ {
		if mode == "RUS" {
			y[ckl] = fmt.Sprintf("%s%s", strings.ToUpper(y[ckl][:2]), y[ckl][2:])
		} else {
			y[ckl] = fmt.Sprintf("%s%s", strings.ToUpper(y[ckl][:1]), y[ckl][1:])
		}
	}

	return y

}
Beispiel #2
0
func (m *TksManager) GetKillometreExtract(typeExtract string, startIndex int, pageSize int, searched string) (ke *KillometreExtract) {
	// comme il n'y a pas la moindre structure d'index, les recherches, en particulier sur le nom, sont forcément lentes
	ke = new(KillometreExtract)
	ke.SearchedTrollIndex = -1
	m.checkTrollInfosLoaded()
	var source []*TrollInfos
	switch typeExtract {
	case "TrollsByKills":
		source = m.TrollsByKills
	case "TrollsByKillsMonstres":
		source = m.TrollsByKillsMonstres
	case "TrollsByKillsTrolls":
		source = m.TrollsByKillsTrolls
	case "AtkByKillsTrolls":
		source = m.AtkByKillsTrolls
	default:
		ke.Error = "Erreur GetKillometreExtract : type non reconnu : " + typeExtract
		return
	}
	searchedNum, _ := strconv.Atoi(searched)
	if searchedNum > 0 {
		foundIndex := -1
		for i, t := range source {
			if t.Num == searchedNum {
				foundIndex = i
				break
			}
		}
		pageNum := foundIndex / pageSize
		startIndex = pageNum * pageSize
		ke.SearchedTrollIndex = foundIndex - startIndex
	} else if searched != "" {
		upperSearched := strings.ToUpper(searched)
		foundIndex := -1
		for i, t := range source {
			if strings.Index(strings.ToUpper(t.Nom), upperSearched) >= 0 {
				foundIndex = i
				break
			}
		}
		pageNum := foundIndex / pageSize
		startIndex = pageNum * pageSize
		ke.SearchedTrollIndex = foundIndex - startIndex
	} else {
		if startIndex < 0 || startIndex > len(source) {
			ke.Error = fmt.Sprintf("Erreur GetKillometreExtract : index invalide : %d\n", startIndex)
			return
		}
	}
	if pageSize < 0 || pageSize > 100 {
		ke.Error = fmt.Sprintf("Erreur GetKillometreExtract : pageSize invalide : %d\n", pageSize)
		return
	} else if pageSize == 0 {
		pageSize = 20
	}
	//fmt.Printf("startIndex=%d  pageSize=%d\n", startIndex, pageSize)
	ke.Trolls = source[startIndex : pageSize+startIndex]
	ke.StartIndex = startIndex
	return
}
Beispiel #3
0
func main() {
	// 以下读取网卡信息
	Interface, err := net.Interfaces()
	if err != nil {
		panic("未发现网卡地址")
		os.Exit(1)
	}

	handwareAddrs = make(map[string]string, len(Interface))
	for _, inter := range Interface {
		inMAC := strings.ToUpper(inter.HardwareAddr.String())
		handwareAddrs[inMAC] = inMAC
	}

	if len(os.Args) != 2 {
		fmt.Println("为保障安全:请先绑定本机上的网卡地址")
		os.Exit(0)
	}

	addr := os.Args[1]
	h, e := net.ParseMAC(addr)
	if e != nil {
		fmt.Println("为保障安全:请先绑定本机上的网卡地址")
		fmt.Println("方法:client.exe 90-4C-E5-58-7E-FE")
		os.Exit(2)
	}
	inputMAC := strings.ToUpper(h.String())
	if inputMAC != handwareAddrs[inputMAC] {
		fmt.Println("网卡地址不匹配")
		os.Exit(0)
	}
}
Beispiel #4
0
// TsigVerify verifies the TSIG on a message.
// If the signature does not validate err contains the
// error, otherwise it is nil.
func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error {
	rawsecret, err := packBase64([]byte(secret))
	if err != nil {
		return err
	}
	// Srtip the TSIG from the incoming msg
	stripped, tsig, err := stripTsig(msg)
	if err != nil {
		return err
	}

	buf := tsigBuffer(stripped, tsig, requestMAC, timersOnly)

	ti := uint64(time.Now().Unix()) - tsig.TimeSigned
	if uint64(tsig.Fudge) < ti {
		return ErrTime
	}

	var h hash.Hash
	switch tsig.Algorithm {
	case HmacMD5:
		h = hmac.New(md5.New, []byte(rawsecret))
	case HmacSHA1:
		h = hmac.New(sha1.New, []byte(rawsecret))
	case HmacSHA256:
		h = hmac.New(sha256.New, []byte(rawsecret))
	default:
		return ErrKeyAlg
	}
	io.WriteString(h, string(buf))
	if strings.ToUpper(hex.EncodeToString(h.Sum(nil))) != strings.ToUpper(tsig.MAC) {
		return ErrSig
	}
	return nil
}
Beispiel #5
0
func (cl cmdLine) Verb() string {
	s := string(cl)
	if idx := strings.Index(s, " "); idx != -1 {
		return strings.ToUpper(s[:idx])
	}
	return strings.ToUpper(s[:len(s)-2])
}
Beispiel #6
0
func (l *Link) ToEnv() []string {
	env := []string{}
	alias := strings.ToUpper(l.Alias())

	if p := l.getDefaultPort(); p != nil {
		env = append(env, fmt.Sprintf("%s_PORT=%s://%s:%s", alias, p.Proto(), l.ChildIP, p.Port()))
	}

	// Load exposed ports into the environment
	for _, p := range l.Ports {
		env = append(env, fmt.Sprintf("%s_PORT_%s_%s=%s://%s:%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Proto(), l.ChildIP, p.Port()))
		env = append(env, fmt.Sprintf("%s_PORT_%s_%s_ADDR=%s", alias, p.Port(), strings.ToUpper(p.Proto()), l.ChildIP))
		env = append(env, fmt.Sprintf("%s_PORT_%s_%s_PORT=%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Port()))
		env = append(env, fmt.Sprintf("%s_PORT_%s_%s_PROTO=%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Proto()))
	}

	// Load the linked container's name into the environment
	env = append(env, fmt.Sprintf("%s_NAME=%s", alias, l.Name))

	if l.ChildEnvironment != nil {
		for _, v := range l.ChildEnvironment {
			parts := strings.Split(v, "=")
			if len(parts) != 2 {
				continue
			}
			// Ignore a few variables that are added during docker build
			if parts[0] == "HOME" || parts[0] == "PATH" {
				continue
			}
			env = append(env, fmt.Sprintf("%s_ENV_%s=%s", alias, parts[0], parts[1]))
		}
	}
	return env
}
Beispiel #7
0
func newListNodesFilters(filter filters.Args) (*swarmapi.ListNodesRequest_Filters, error) {
	accepted := map[string]bool{
		"name":       true,
		"id":         true,
		"label":      true,
		"role":       true,
		"membership": true,
	}
	if err := filter.Validate(accepted); err != nil {
		return nil, err
	}
	f := &swarmapi.ListNodesRequest_Filters{
		Names:      filter.Get("name"),
		IDPrefixes: filter.Get("id"),
		Labels:     runconfigopts.ConvertKVStringsToMap(filter.Get("label")),
	}

	for _, r := range filter.Get("role") {
		if role, ok := swarmapi.NodeRole_value[strings.ToUpper(r)]; ok {
			f.Roles = append(f.Roles, swarmapi.NodeRole(role))
		} else if r != "" {
			return nil, fmt.Errorf("Invalid role filter: '%s'", r)
		}
	}

	for _, a := range filter.Get("membership") {
		if membership, ok := swarmapi.NodeSpec_Membership_value[strings.ToUpper(a)]; ok {
			f.Memberships = append(f.Memberships, swarmapi.NodeSpec_Membership(membership))
		} else if a != "" {
			return nil, fmt.Errorf("Invalid membership filter: '%s'", a)
		}
	}

	return f, nil
}
Beispiel #8
0
Datei: sc.go Projekt: kpmy/lomo
func (s *sc) ident() (sym Sym) {
	assert.For(unicode.IsLetter(s.ch), 20, "character expected")
	var buf []rune
	for {
		buf = append(buf, s.ch)
		s.next()
		if s.err != nil || !(unicode.IsLetter(s.ch) || unicode.IsDigit(s.ch)) {
			break
		}
	}
	if s.err == nil {
		sym.Str = string(buf)
		key := sym.Str
		if s.evil == nil {
			x := true
			s.evil = &x
			if keyTab[key] == None && keyTab[strings.ToUpper(key)] == s.useTab[0] {
				*s.evil = true
			} else if keyTab[key] == s.useTab[0] {
				*s.evil = false
			}
		}
		set := func() {
			if sym.Code = keyTab[key]; sym.Code == None {
				sym.Code = Ident
				sym.User = s.foreignTab[key]
			} else if sym.Code != None {
				ok := false
				for _, u := range s.useTab {
					if u == sym.Code {
						ok = true
						break
					}
				}
				if !ok {
					sym.Code = Ident
					sym.User = s.foreignTab[key]
				}
			}
		}
		if s.evil != nil {
			if *s.evil {
				key = strings.ToUpper(sym.Str)
				if key != sym.Str {
					set()
				} else {
					sym.Code = Ident
				}
			} else {
				set()
			}

		} else {
			sym.Code = Ident
		}
	} else {
		s.mark("error while ident read")
	}
	return
}
Beispiel #9
0
func format(lines []string) {
	var indexes []int
	for i, line := range lines {
		// --- First letter of comments in capital
		if indexes = re_comment_caps.FindStringSubmatchIndex(line); indexes != nil && indexes[2] == -1 {
			// => the first capture group didn't return anything, which is what we want (nb: No negative lookahead for regexp in Go)
			// Capitalisation of the first letter
			line = line[:indexes[4]] + strings.ToUpper(line[indexes[4]:indexes[5]]) + line[indexes[5]:]
		}
		// --- Replace "@" by "\" in doxygen comment blocks
		if indexes = re_dox_backslash.FindStringSubmatchIndex(line); indexes != nil {
			line = line[:indexes[3]] + "\\" + line[indexes[4]:]
		}
		//  --- Capitalisation of first letter after brief/return in doxygen comment blocks
		if indexes = re_dox_caps.FindStringSubmatchIndex(line); indexes != nil && indexes[6] == -1 {
			// the third capture group didn't return anything, which is what we want (nb: No negative lookahead for regexp in Go)
			line = line[:indexes[3]] + " " + strings.ToUpper(line[indexes[4]:indexes[5]]) + line[indexes[5]:]
		}
		//  --- Add colon after parameter name and capitalise the first letter of the parameter detail in doxygen comment blocks
		if indexes = re_dox_colon.FindStringSubmatchIndex(line); indexes != nil {
			line = line[:indexes[3]] + ": " + strings.ToUpper(line[indexes[4]:indexes[4]+1]) + line[indexes[4]+1:]
		}
		// If the line used in the loop is modified we replace it in the slice
		if line != lines[i] {
			lines[i] = line
		}
	}
}
/**
 * Takes a character and returns the escaped string for that character. For
 * example escapeChar(String.fromCharCode(15)) -> "\\x0E".
 * @param {string} c The character to escape.
 * @return {string} An escaped string representing {@code c}.
 */
func EscapeChar(c string) string {
	if v, ok := _EscapeCharJs[c]; ok {
		return v
	}
	var rv string
	var cc rune
	for _, cc = range rv {
		switch {
		case cc > 31 && cc < 127:
			rv = c
		case cc < 16:
			// tab is 9 but handled above
			rv = "\\x0" + strings.ToUpper(string(cc))
		case cc < 256:
			rv = "\\x" + strings.ToUpper(string(cc))
		case cc < 4096:
			rv = "\\u0" + strings.ToUpper(string(cc))
		case cc >= 4096:
			rv = "\\u" + strings.ToUpper(string(cc))
		default:
			rv = c
		}
		break
	}
	_EscapeCharJs[c] = rv
	return rv
}
Beispiel #11
0
// ToRuleCreateMap builds the create rule options into a serializable format.
func (opts CreateRuleOpts) ToRuleCreateMap() (map[string]interface{}, error) {
	rule := make(map[string]interface{})

	if opts.ParentGroupID == "" {
		return rule, errors.New("A ParentGroupID must be set")
	}
	if opts.FromPort == 0 && strings.ToUpper(opts.IPProtocol) != "ICMP" {
		return rule, errors.New("A FromPort must be set")
	}
	if opts.ToPort == 0 && strings.ToUpper(opts.IPProtocol) != "ICMP" {
		return rule, errors.New("A ToPort must be set")
	}
	if opts.IPProtocol == "" {
		return rule, errors.New("A IPProtocol must be set")
	}
	if opts.CIDR == "" && opts.FromGroupID == "" {
		return rule, errors.New("A CIDR or FromGroupID must be set")
	}

	rule["parent_group_id"] = opts.ParentGroupID
	rule["from_port"] = opts.FromPort
	rule["to_port"] = opts.ToPort
	rule["ip_protocol"] = opts.IPProtocol

	if opts.CIDR != "" {
		rule["cidr"] = opts.CIDR
	}
	if opts.FromGroupID != "" {
		rule["group_id"] = opts.FromGroupID
	}

	return map[string]interface{}{"security_group_rule": rule}, nil
}
Beispiel #12
0
// stringFormat formats a string.
func stringFormat(format string, text string) string {
	if format == "uppercase" {
		return strings.ToUpper(text)
	} else if format == "lowercase" {
		return strings.ToLower(text)
	} else if format == "sentence" {
		if len(text) > 1 {
			return strings.ToUpper(text[0:1]) + strings.ToLower(text[1:])
		} else {
			return strings.ToUpper(text)
		}
	} else if format == "formal" {
		words := strings.Split(text, " ")
		result := []string{}
		for _, word := range words {
			if len(word) > 1 {
				result = append(result, strings.ToUpper(word[0:1])+strings.ToLower(word[1:]))
			} else {
				result = append(result, strings.ToUpper(word))
			}
		}
		return strings.Join(result, " ")
	}
	return text
}
Beispiel #13
0
func strGetSetFunction(c []Column, tblName string) string {
	var ret string
	var letter string = strings.ToLower(tblName[:1])
	ret = "func (" + letter + " *" + tblName + ") Set(key string, value interface{}) error {\n"
	if hasIntColumns(c) {
		ret += "\tvar err error\n"
	}
	ret += "\tif  value == nil {\n"
	ret += "\t\treturn errors.New(\"value for \" + key + \" is nil\")\n"
	ret += "\t}\n"
	ret += "\tswitch key {\n"
	for _, col := range c {
		ret += "\tcase \"" + col.Field + "\":\n" //TODO: capitalize fields
		if getType(col.Type) == "int" {
			ret += "\t\t" + letter + "."
			ret += strings.ToUpper(col.Field[:1]) + col.Field[1:]
			ret += ", err = strconv.Atoi(value.(string))\n"
			ret += "\t\tif err != nil && value != \"NULL\" {\n"
			ret += "\t\t\treturn err\n"
			ret += "\t\t}\n"
		} else {
			ret += "\t\t" + letter + "." + strings.ToUpper(col.Field[:1]) + col.Field[1:] + " = value.(string)\n"
		}
		ret += "\t\treturn nil\n"
	}
	ret += "\tdefault:\n"
	ret += "\t\treturn errors.New(\"Key not found:\" + key)\n"
	ret += "\t}\n"
	ret += "}\n\n"
	return ret
}
Beispiel #14
0
func (s *ProxyUpdaterSuite) TestEnvironmentVariables(c *gc.C) {
	setenv := func(proxy, value string) {
		os.Setenv(proxy, value)
		os.Setenv(strings.ToUpper(proxy), value)
	}
	setenv("http_proxy", "foo")
	setenv("https_proxy", "foo")
	setenv("ftp_proxy", "foo")
	setenv("no_proxy", "foo")

	proxySettings, _ := s.updateConfig(c)
	updater, err := proxyupdater.NewWorker(s.config)
	c.Assert(err, jc.ErrorIsNil)
	defer worker.Stop(updater)
	s.waitProxySettings(c, proxySettings)

	assertEnv := func(proxy, value string) {
		c.Assert(os.Getenv(proxy), gc.Equals, value)
		c.Assert(os.Getenv(strings.ToUpper(proxy)), gc.Equals, value)
	}
	assertEnv("http_proxy", proxySettings.Http)
	assertEnv("https_proxy", proxySettings.Https)
	assertEnv("ftp_proxy", proxySettings.Ftp)
	assertEnv("no_proxy", proxySettings.NoProxy)
}
Beispiel #15
0
func (o *TodoListAPI) initHandlerCache() {
	if o.context == nil {
		o.context = middleware.NewRoutableContext(o.spec, o, nil)
	}

	if o.handlers == nil {
		o.handlers = make(map[string]map[string]http.Handler)
	}

	if o.handlers["POST"] == nil {
		o.handlers[strings.ToUpper("POST")] = make(map[string]http.Handler)
	}
	o.handlers["POST"]["/"] = todos.NewAddOne(o.context, o.TodosAddOneHandler)

	if o.handlers["DELETE"] == nil {
		o.handlers[strings.ToUpper("DELETE")] = make(map[string]http.Handler)
	}
	o.handlers["DELETE"]["/{id}"] = todos.NewDestroyOne(o.context, o.TodosDestroyOneHandler)

	if o.handlers["GET"] == nil {
		o.handlers[strings.ToUpper("GET")] = make(map[string]http.Handler)
	}
	o.handlers["GET"]["/"] = todos.NewFindTodos(o.context, o.TodosFindTodosHandler)

	if o.handlers["PUT"] == nil {
		o.handlers[strings.ToUpper("PUT")] = make(map[string]http.Handler)
	}
	o.handlers["PUT"]["/{id}"] = todos.NewUpdateOne(o.context, o.TodosUpdateOneHandler)

}
Beispiel #16
0
/**
 * Return canonical form.
 * @return String
 */
func (this *Protocol) String() string {
	return strings.ToUpper(this.protocolName) +
		core.SIPSeparatorNames_SLASH +
		this.protocolVersion +
		core.SIPSeparatorNames_SLASH +
		strings.ToUpper(this.transport)
}
Beispiel #17
0
func Color(color string) string {
	if len(color) < 2 {
		panic(color + ": length of Color < 2 ")

	}
	colorm := ColorMap[strings.ToUpper(color[0:1])+color[1:]]
	//if not found on Map, use as-is. ("FF0000" etc)
	if colorm == "" {
		if len(color) != 6 {
			panic(color + ": not defined ")
		}
		for i := 0; i < 6; i++ {
			cx := color[i : i+1]
			switch cx {
			case "0", "1", "2", "3", "4", "5",
				"6", "7", "8", "9",
				"A", "B", "C", "D", "E", "F":
			default:
				panic(color + ": not defined ")
			}
		}
		return color
	}
	colorx := colornames.Map[colorm]
	cs := hex.EncodeToString([]byte{colorx.R, colorx.G, colorx.B})
	return strings.ToUpper(cs)
}
Beispiel #18
0
// PostFindHandle implements the handle for the find document (POST).
func PostFindHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
	var userData map[string]string
	userData = rawhttp.GetFieldsFromPost(httpPayload)
	var replyBuffer []byte
	if _, posted := userData["user"]; !posted {
		replyBuffer = rawhttp.MakeReplyBuffer(html.GetBadAssErrorData(), 404, true)
	} else {
		var result string
		result = preprocessor.ExpandData(roomName, rooms.GetFindResultsHeadTemplate(roomName))
		listing := rooms.GetFindResultsBodyTemplate(roomName)
		availRooms := rooms.GetRooms()
		user := strings.ToUpper(userData["user"])
		if len(user) > 0 {
			for _, r := range availRooms {
				users := rooms.GetRoomUsers(r)
				preprocessor.SetDataValue("{{.find-result-users-total}}", rooms.GetUsersTotal(r))
				preprocessor.SetDataValue("{{.find-result-room-name}}", r)
				for _, u := range users {
					if strings.HasPrefix(strings.ToUpper(u), user) {
						preprocessor.SetDataValue("{{.find-result-user}}", u)
						result += preprocessor.ExpandData(roomName, listing)
					}
				}
			}
		}
		result += preprocessor.ExpandData(roomName, rooms.GetFindResultsTailTemplate(roomName))
		replyBuffer = rawhttp.MakeReplyBuffer(result, 200, true)
	}
	newConn.Write(replyBuffer)
	newConn.Close()
}
Beispiel #19
0
// Prepares the route to be used in matching.
func NewRoute(method, path, action, fixedArgs, routesPath string, line int) (r *Route) {
	// Handle fixed arguments
	argsReader := strings.NewReader(fixedArgs)
	csv := csv.NewReader(argsReader)
	fargs, err := csv.Read()
	if err != nil && err != io.EOF {
		ERROR.Printf("Invalid fixed parameters (%v): for string '%v'", err.Error(), fixedArgs)
	}

	r = &Route{
		Method:      strings.ToUpper(method),
		Path:        path,
		Action:      action,
		FixedParams: fargs,
		TreePath:    treePath(strings.ToUpper(method), path),
		routesPath:  routesPath,
		line:        line,
	}

	// URL pattern
	if !strings.HasPrefix(r.Path, "/") {
		ERROR.Print("Absolute URL required.")
		return
	}

	actionSplit := strings.Split(action, ".")
	if len(actionSplit) == 2 {
		r.ControllerName = actionSplit[0]
		r.MethodName = actionSplit[1]
	}

	return
}
Beispiel #20
0
// splitName splits name into a slice of strings split by capitalization.
func splitName(name string) []string {
	out, buf := []string{}, ""

	for i, r := range name {
		l := string(r)

		// special check for EC2, MD5, DBi
		lower := strings.ToLower(buf)
		if _, err := strconv.Atoi(l); err == nil &&
			(lower == "ec" || lower == "md" || lower == "db") {
			buf += l
			continue
		}

		lastUpper := i-1 >= 0 && strings.ToUpper(name[i-1:i]) == name[i-1:i]
		curUpper := l == strings.ToUpper(l)
		nextUpper := i+2 > len(name) || strings.ToUpper(name[i+1:i+2]) == name[i+1:i+2]

		if (lastUpper != curUpper) || (nextUpper != curUpper && !nextUpper) {
			if len(buf) > 1 || curUpper {
				out = append(out, buf)
				buf = ""
			}
			buf += l
		} else {
			buf += l
		}
	}
	if len(buf) > 0 {
		out = append(out, buf)
	}
	return out
}
Beispiel #21
0
func (b *buildFile) Build(context io.Reader) (string, error) {
	// FIXME: @creack "name" is a terrible variable name
	name, err := ioutil.TempDir("", "docker-build")
	if err != nil {
		return "", err
	}
	if err := Untar(context, name); err != nil {
		return "", err
	}
	defer os.RemoveAll(name)
	b.context = name
	filename := path.Join(name, "Dockerfile")
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return "", fmt.Errorf("Can't build a directory with no Dockerfile")
	}
	fileBytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return "", err
	}
	dockerfile := string(fileBytes)
	dockerfile = lineContinuation.ReplaceAllString(dockerfile, "")
	stepN := 0
	for _, line := range strings.Split(dockerfile, "\n") {
		line = strings.Trim(strings.Replace(line, "\t", " ", -1), " \t\r\n")
		// Skip comments and empty line
		if len(line) == 0 || line[0] == '#' {
			continue
		}
		tmp := strings.SplitN(line, " ", 2)
		if len(tmp) != 2 {
			return "", fmt.Errorf("Invalid Dockerfile format")
		}
		instruction := strings.ToLower(strings.Trim(tmp[0], " "))
		arguments := strings.Trim(tmp[1], " ")

		method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:]))
		if !exists {
			fmt.Fprintf(b.out, "# Skipping unknown instruction %s\n", strings.ToUpper(instruction))
			continue
		}

		stepN += 1
		fmt.Fprintf(b.out, "Step %d : %s %s\n", stepN, strings.ToUpper(instruction), arguments)

		ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface()
		if ret != nil {
			return "", ret.(error)
		}

		fmt.Fprintf(b.out, " ---> %v\n", utils.TruncateID(b.image))
	}
	if b.image != "" {
		fmt.Fprintf(b.out, "Successfully built %s\n", utils.TruncateID(b.image))
		if b.rm {
			b.clearTmp(b.tmpContainers)
		}
		return b.image, nil
	}
	return "", fmt.Errorf("An error occurred during the build\n")
}
Beispiel #22
0
// environ merges os.Environ and the given "key=value" pairs.
// If a key is in both os.Environ and kv, kv takes precedence.
func environ(kv []string) []string {
	cur := os.Environ()
	new := make([]string, 0, len(cur)+len(kv))

	envs := make(map[string]string, len(cur))
	for _, ev := range cur {
		elem := strings.SplitN(ev, "=", 2)
		if len(elem) != 2 || elem[0] == "" {
			// pass the env var of unusual form untouched.
			// e.g. Windows may have env var names starting with "=".
			new = append(new, ev)
			continue
		}
		if goos == "windows" {
			elem[0] = strings.ToUpper(elem[0])
		}
		envs[elem[0]] = elem[1]
	}
	for _, ev := range kv {
		elem := strings.SplitN(ev, "=", 2)
		if len(elem) != 2 || elem[0] == "" {
			panic(fmt.Sprintf("malformed env var %q from input", ev))
		}
		if goos == "windows" {
			elem[0] = strings.ToUpper(elem[0])
		}
		envs[elem[0]] = elem[1]
	}
	for k, v := range envs {
		new = append(new, k+"="+v)
	}
	return new
}
Beispiel #23
0
func (r Resolver) outputResults(w *bufio.Writer, results gresults) {
	var zip, city, state, stateName, county, country, countryName string
	var latitude, longitude float32

	var comp addressComponent
	var err error
	for _, res := range results.Results {
		if comp, err = res.findAddressComponent(zipType); err == nil {
			zip = comp.LongName
		}
		if comp, err = res.findAddressComponent(cityType); err == nil {
			city = comp.LongName
		}
		if comp, err = res.findAddressComponent(countyType); err == nil {
			county = comp.LongName
		}
		if comp, err = res.findAddressComponent(stateType); err == nil {
			state = strings.ToUpper(comp.ShortName)
			stateName = comp.LongName
		}
		if comp, err = res.findAddressComponent(countryType); err == nil {
			country = strings.ToUpper(comp.ShortName)
			countryName = comp.LongName
		}
		latitude = res.Geometry.Location.Lat
		longitude = res.Geometry.Location.Lng
	}
	w.WriteString(fmt.Sprintf("%v,\"%v\",\"%v\",\"%v\",\"%v\",\"%v\",\"%v\",%v,%v\n", country, zip, city, state, stateName, county, countryName, latitude, longitude))
	w.Flush()
}
Beispiel #24
0
// add http method router
// usage:
//    AddMethod("get","/api/:id", func(ctx *context.Context){
//          ctx.Output.Body("hello world")
//    })
func (p *ControllerRegistor) AddMethod(method, pattern string, f FilterFunc) {
	if _, ok := HTTPMETHOD[strings.ToUpper(method)]; method != "*" && !ok {
		panic("not support http method: " + method)
	}
	route := &controllerInfo{}
	route.pattern = pattern
	route.routerType = routerTypeRESTFul
	route.runfunction = f
	methods := make(map[string]string)
	if method == "*" {
		for _, val := range HTTPMETHOD {
			methods[val] = val
		}
	} else {
		methods[strings.ToUpper(method)] = strings.ToUpper(method)
	}
	route.methods = methods
	for k := range methods {
		if k == "*" {
			for _, m := range HTTPMETHOD {
				p.addToRouter(m, pattern, route)
			}
		} else {
			p.addToRouter(k, pattern, route)
		}
	}
}
Beispiel #25
0
func (v *Viper) mergeWithEnvPrefix(in string) string {
	if v.envPrefix != "" {
		return strings.ToUpper(v.envPrefix + "_" + in)
	}

	return strings.ToUpper(in)
}
Beispiel #26
0
func applyEnvVariableOverrides() {
	appliedEnvOverrides = make([]string, 0)
	for _, section := range Cfg.Sections() {
		for _, key := range section.Keys() {
			sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
			keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
			envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
			envValue := os.Getenv(envKey)

			if len(envValue) > 0 {
				key.SetValue(envValue)
				if shouldRedactKey(envKey) {
					envValue = "*********"
				}
				if shouldRedactURLKey(envKey) {
					u, _ := url.Parse(envValue)
					ui := u.User
					if ui != nil {
						_, exists := ui.Password()
						if exists {
							u.User = url.UserPassword(ui.Username(), "-redacted-")
							envValue = u.String()
						}
					}
				}
				appliedEnvOverrides = append(appliedEnvOverrides, fmt.Sprintf("%s=%s", envKey, envValue))
			}
		}
	}
}
Beispiel #27
0
func UpperName(name string) string {
	// myapp -> Myapp; my-app -> MyApp
	us := strings.ToUpper(name[0:1]) + name[1:]

	for {
		i := strings.Index(us, "-")

		if i == -1 {
			break
		}

		s := us[0:i]

		if len(us) > i+1 {
			s += strings.ToUpper(us[i+1 : i+2])
		}

		if len(us) > i+2 {
			s += us[i+2:]
		}

		us = s
	}

	return us
}
Beispiel #28
0
func (a CaseACK) MarshalJSON() ([]byte, error) {
	var results interface{}
	messageType := a.Type().String()
	packet := a.Request.(client.ClientACK)
	switch a.CaseTestType {
	case ValueTypeUpper:
		results = struct {
			MessageType string          `json:"messageType"`
			Updates     []client.Update `json:"updates"`
		}{strings.ToUpper(messageType), packet.Updates}

	case ValueTypeCap:
		results = struct {
			MessageType string          `json:"messageType"`
			Updates     []client.Update `json:"updates"`
		}{strings.ToUpper(messageType[:1]) + strings.ToLower(messageType[1:]), packet.Updates}

	case ValueTypeEmpty:
		results = struct {
			MessageType string          `json:"messageType"`
			Updates     []client.Update `json:"updates"`
		}{"", packet.Updates}

	default:
		return nil, ErrInvalidCaseTest
	}
	return json.Marshal(results)
}
// domainConstant converts the domain name |s| into a string of the form
// "DOMAIN_" + uppercase last two labels.
func domainConstant(s string) string {
	labels := strings.Split(s, ".")
	gtld := strings.ToUpper(labels[len(labels)-1])
	domain := strings.Replace(strings.ToUpper(labels[len(labels)-2]), "-", "_", -1)

	return fmt.Sprintf("DOMAIN_%s_%s", domain, gtld)
}
Beispiel #30
0
// WriteEnvConfig writes the given configuration to out. The format of the
// output is a list of environment variables settings suitable to be sourced
// by a Bourne-like shell.
func WriteEnvConfig(cfg *Config, out io.Writer) {
	cfgMap := map[string]interface{}{}
	cfgElem := reflect.ValueOf(cfg).Elem()

	for _, def := range defs {
		if !def.HasField {
			continue
		}

		field := cfgElem.FieldByName(def.FieldName)
		cfgMap[def.Name] = field.Interface()
	}

	sortedCfgMapKeys := []string{}

	for key := range cfgMap {
		sortedCfgMapKeys = append(sortedCfgMapKeys, key)
	}

	sort.Strings(sortedCfgMapKeys)

	fmt.Fprintf(out, "# travis-worker env config generated %s\n", time.Now().UTC())
	for _, key := range sortedCfgMapKeys {
		envKey := fmt.Sprintf("TRAVIS_WORKER_%s", strings.ToUpper(strings.Replace(key, "-", "_", -1)))
		fmt.Fprintf(out, "export %s=%q\n", envKey, fmt.Sprintf("%v", cfgMap[key]))
	}
	fmt.Fprintf(out, "\n# travis-worker provider config:\n")
	cfg.ProviderConfig.Each(func(key, value string) {
		envKey := strings.ToUpper(fmt.Sprintf("TRAVIS_WORKER_%s_%s", cfg.ProviderName, strings.Replace(key, "-", "_", -1)))
		fmt.Fprintf(out, "export %s=%q\n", envKey, value)
	})
	fmt.Fprintf(out, "# end travis-worker env config\n")
}