Exemple #1
0
func (cmd *cmdBreakfast) Run(title, from, text string) error {
	var err error

	if strings.HasPrefix(text, "!b-") {
		bfText := strings.TrimSpace(strings.TrimPrefix(text, "!b-"))
		if bfText == "" {
			// !b-: Reset list
			err = cmd.listReset(title)
		} else {
			// !b- n: Remove item n
			err = cmd.removeItem(title, bfText)
		}
	} else {
		bfText := strings.TrimSpace(strings.TrimPrefix(text, "!b"))
		if bfText == "" {
			// !b: List
			err = cmd.listItems(title)
		} else {
			// !b item: Add item to the list
			err = cmd.addItem(title, from, bfText)
		}
	}
	if err != nil {
		fmt.Fprintf(cmd.w, "msg %v error: cannot get or add items\n", title)
		return err
	}
	return nil
}
Exemple #2
0
// walk every arg looking for "file:" and calling iomHelper on the suffix.
// Replace the arg with the local file if found.
func iomPreprocessor(c *minicli.Command) (*minicli.Command, error) {
	for k, v := range c.StringArgs {
		if strings.HasPrefix(v, IOM_HELPER_MATCH) {
			file := strings.TrimPrefix(v, IOM_HELPER_MATCH)
			local, err := iomHelper(file)
			if err != nil {
				return nil, err
			}
			log.Debug("iomPreProcessor: %v -> %v", v, local)
			c.StringArgs[k] = local
		}
	}
	for k, v := range c.ListArgs {
		for x, y := range v {
			if strings.HasPrefix(y, IOM_HELPER_MATCH) {
				file := strings.TrimPrefix(y, IOM_HELPER_MATCH)
				local, err := iomHelper(file)
				if err != nil {
					return nil, err
				}
				log.Debug("iomPreProcessor: %v -> %v", y, local)
				c.ListArgs[k][x] = local
			}
		}
	}
	return c, nil
}
Exemple #3
0
// aliasExpand expands aliased (name:/path) to full URL, used by url-parser
func aliasExpand(aliasedURL string, aliases map[string]string) (newURL string, err error) {
	u, err := client.Parse(aliasedURL)
	if err != nil {
		return aliasedURL, iodine.New(errInvalidURL{URL: aliasedURL}, nil)
	}
	// proper URL
	if u.Host != "" {
		return aliasedURL, nil
	}
	for aliasName, expandedURL := range aliases {
		if strings.HasPrefix(aliasedURL, aliasName+":") {
			// Match found. Expand it.
			splits := strings.Split(aliasedURL, ":")
			// if expandedURL is missing, return aliasedURL treat it like fs
			if expandedURL == "" {
				return aliasedURL, nil
			}
			// if more splits found return
			if len(splits) == 2 {
				// remove any prefixed slashes
				trimmedURL := expandedURL + "/" + strings.TrimPrefix(strings.TrimPrefix(splits[1], "/"), "\\")
				u, err := client.Parse(trimmedURL)
				if err != nil {
					return aliasedURL, iodine.New(errInvalidURL{URL: aliasedURL}, nil)
				}
				return u.String(), nil
			}
			return aliasedURL, nil
		}
	}
	return aliasedURL, nil
}
// pathToKey translates etcd key paths into something more suitable for use
// in Golang templates. Turn /prefix/key/subkey into key_subkey.
func pathToKey(key, prefix string) string {
	prefix = strings.TrimPrefix(prefix, "/")
	key = strings.TrimPrefix(key, "/")
	key = strings.TrimPrefix(key, prefix)
	key = strings.TrimPrefix(key, "/")
	return replacer.Replace(key)
}
Exemple #5
0
func lookUpNamespace(type_, currentNs string) string {
	//Embeddeds or extends are often times empty
	if type_ == "" {
		return type_
	}

	var prefix string
	if type_[0:1] == "*" {
		prefix = "*"
		type_ = type_[1:]
	} else if type_[0:3] == "[]*" {
		prefix = "[]*"
		type_ = type_[3:]
	} else if type_[0:2] == "[]" {
		prefix = "[]"
		type_ = type_[2:]
	}

	//strips out package name if it has it
	type_ = strings.TrimPrefix(type_, "mo.")
	type_ = strings.TrimPrefix(type_, "do.")
	type_ = strings.TrimPrefix(type_, "fault.")
	type_ = strings.TrimPrefix(type_, "enum.")

	targetNs := objnsmap[type_]
	if targetNs == "" || targetNs != "enum" || targetNs == currentNs {
		return prefix + type_
	}

	return prefix + targetNs + "." + type_
}
Exemple #6
0
// NewRequest creates a new raw request object to query the Vault server
// configured for this client. This is an advanced method and generally
// doesn't need to be called externally.
func (c *Client) NewRequest(method, path string) *Request {
	req := &Request{
		Method: method,
		URL: &url.URL{
			Scheme: c.addr.Scheme,
			Host:   c.addr.Host,
			Path:   path,
		},
		ClientToken: c.token,
		Params:      make(map[string][]string),
	}

	var lookupPath string
	switch {
	case strings.HasPrefix(path, "/v1/"):
		lookupPath = strings.TrimPrefix(path, "/v1/")
	case strings.HasPrefix(path, "v1/"):
		lookupPath = strings.TrimPrefix(path, "v1/")
	default:
		lookupPath = path
	}
	if c.wrappingLookupFunc != nil {
		req.WrapTTL = c.wrappingLookupFunc(method, lookupPath)
	} else {
		req.WrapTTL = DefaultWrappingLookupFunc(method, lookupPath)
	}

	return req
}
Exemple #7
0
// based off of https://github.com/dotcloud/docker/blob/2a711d16e05b69328f2636f88f8eac035477f7e4/utils/utils.go
func parseHost(addr string) (string, string, error) {

	var (
		proto string
		host  string
		port  int
	)
	addr = strings.TrimSpace(addr)
	switch {
	case addr == "tcp://":
		return "", "", fmt.Errorf("Invalid bind address format: %s", addr)
	case strings.HasPrefix(addr, "unix://"):
		proto = "unix"
		addr = strings.TrimPrefix(addr, "unix://")
		if addr == "" {
			addr = "/var/run/docker.sock"
		}
	case strings.HasPrefix(addr, "tcp://"):
		proto = "tcp"
		addr = strings.TrimPrefix(addr, "tcp://")
	case strings.HasPrefix(addr, "fd://"):
		return "fd", addr, nil
	case addr == "":
		proto = "unix"
		addr = "/var/run/docker.sock"
	default:
		if strings.Contains(addr, "://") {
			return "", "", fmt.Errorf("Invalid bind address protocol: %s", addr)
		}
		proto = "tcp"
	}

	if proto != "unix" && strings.Contains(addr, ":") {
		hostParts := strings.Split(addr, ":")
		if len(hostParts) != 2 {
			return "", "", fmt.Errorf("Invalid bind address format: %s", addr)
		}
		if hostParts[0] != "" {
			host = hostParts[0]
		} else {
			host = "127.0.0.1"
		}

		if p, err := strconv.Atoi(hostParts[1]); err == nil && p != 0 {
			port = p
		} else {
			return "", "", fmt.Errorf("Invalid bind address format: %s", addr)
		}

	} else if proto == "tcp" && !strings.Contains(addr, ":") {
		return "", "", fmt.Errorf("Invalid bind address format: %s", addr)
	} else {
		host = addr
	}
	if proto == "unix" {
		return proto, host, nil

	}
	return proto, fmt.Sprintf("%s:%d", host, port), nil
}
Exemple #8
0
// Add adds a pattern and associated value to the matcher.
func (m *Matcher) Add(pattern string, v interface{}) error {
	if strings.HasPrefix(pattern, ExactPrefix) {
		s := strings.TrimPrefix(pattern, ExactPrefix)
		m.exact[s] = v
		return nil
	}
	if strings.HasPrefix(pattern, RegexPrefix) {
		s := strings.TrimPrefix(pattern, RegexPrefix)
		re, err := regexp.Compile(s)
		if err != nil {
			return err
		}
		m.regex = append(m.regex, struct {
			re *regexp.Regexp
			v  interface{}
		}{
			re: re,
			v:  v,
		})
		return nil
	}
	if strings.HasPrefix(pattern, SkipPrefix) {
		s := strings.TrimPrefix(pattern, SkipPrefix)
		m.trie.Add(s, &skipMatcher{
			pattern: pattern,
			v:       v,
		})
		return nil
	}
	m.trie.Add(pattern, v)
	return nil
}
Exemple #9
0
// Strip ...
func Strip(str string) string {
	dirty := true
	strippedStr := str
	for dirty {
		hasWhiteSpacePrefix := false
		if strings.HasPrefix(strippedStr, " ") {
			hasWhiteSpacePrefix = true
			strippedStr = strings.TrimPrefix(strippedStr, " ")
		}

		hasWhiteSpaceSuffix := false
		if strings.HasSuffix(strippedStr, " ") {
			hasWhiteSpaceSuffix = true
			strippedStr = strings.TrimSuffix(strippedStr, " ")
		}

		hasNewlinePrefix := false
		if strings.HasPrefix(strippedStr, "\n") {
			hasNewlinePrefix = true
			strippedStr = strings.TrimPrefix(strippedStr, "\n")
		}

		hasNewlineSuffix := false
		if strings.HasSuffix(strippedStr, "\n") {
			hasNewlinePrefix = true
			strippedStr = strings.TrimSuffix(strippedStr, "\n")
		}

		if !hasWhiteSpacePrefix && !hasWhiteSpaceSuffix && !hasNewlinePrefix && !hasNewlineSuffix {
			dirty = false
		}
	}
	return strippedStr
}
Exemple #10
0
func usrParse(usrStr string) (err error) {
	switch {
	default:
		err = client.Call("Receiver.SendMsg", Args{Token, usrStr}, nil)
	case strings.HasPrefix(usrStr, COMM_CREATEROOM):
		cName := strings.TrimSuffix(strings.TrimPrefix(usrStr, COMM_CREATEROOM+" "), "\n")
		err = client.Call("Receiver.CreateCRoom", Args{Token, cName}, nil)
	case strings.HasPrefix(usrStr, COMM_ENTERROOM):
		cName := strings.TrimSuffix(strings.TrimPrefix(usrStr, COMM_ENTERROOM+" "), "\n")
		err = client.Call("Receiver.JoinCRoom", Args{Token, cName}, nil)
	case strings.HasPrefix(usrStr, COMM_LEAVEROOM):
		err = client.Call("Receiver.LeaveCRoom", &Token, nil)
	case strings.HasPrefix(usrStr, COMM_LISTROOMS):
		err = client.Call("Receiver.ListCRooms", &Token, nil)
	case strings.HasPrefix(usrStr, COMM_HELPCHAT):
		fmt.Print(MESS_HELP)
	case strings.HasPrefix(usrStr, COMM_CHANGENAME):
		cName := strings.TrimSuffix(strings.TrimPrefix(usrStr, COMM_CHANGENAME+" "), "\n")
		err = client.Call("Receiver.ChangeName", Args{Token, cName}, nil)
	case strings.HasPrefix(usrStr, COMM_QUITCHAT):
		err = client.Call("Receiver.Quit", &Token, nil)
		waitG.Done()
	}
	//fmt.Print(err)
	return err
}
Exemple #11
0
func TestCacheKeyFields(t *testing.T) {
	keyJSON, err := cacheKey(kapi.NewContext(), &authorizer.DefaultAuthorizationAttributes{})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	keyMap := map[string]interface{}{}
	if err := json.Unmarshal([]byte(keyJSON), &keyMap); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	keys := sets.NewString()
	for k := range keyMap {
		keys.Insert(strings.ToLower(k))
	}

	// These are results we don't expect to be in the cache key
	expectedMissingKeys := sets.NewString("requestattributes")

	attrType := reflect.TypeOf((*authorizer.AuthorizationAttributes)(nil)).Elem()
	for i := 0; i < attrType.NumMethod(); i++ {
		name := attrType.Method(i).Name
		name = strings.TrimPrefix(name, "Get")
		name = strings.TrimPrefix(name, "Is")
		name = strings.ToLower(name)
		if !keys.Has(name) && !expectedMissingKeys.Has(name) {
			t.Errorf("computed cache is missing an entry for %s", attrType.Method(i).Name)
		}
	}
}
Exemple #12
0
// GetHostFromUrl extracts the host from an URL.
// Local file urls starting with 'file://' are skipped.
func GetHostFromUrl(url string) string {
	url = strings.TrimSpace(url)

	// Skip if this is a local file url.
	if strings.HasPrefix(url, "file://") {
		return url
	}

	if strings.HasPrefix(url, "http://") {
		url = strings.TrimPrefix(url, "http://")
	} else if strings.HasPrefix(url, "https://") {
		url = strings.TrimPrefix(url, "https://")
	} else if strings.HasPrefix(url, "git@") {
		url = strings.TrimPrefix(url, "git@")
	}

	// Remove everything after the first slash.
	pos := strings.Index(url, "/")
	if pos >= 0 {
		url = url[:pos]
	}

	// Remove everything after the ':'.
	// This is important for git urls.
	pos = strings.Index(url, ":")
	if pos >= 0 {
		url = url[:pos]
	}

	return url
}
Exemple #13
0
func getFileSummary(filename, dir, cmd, out string) (FileSummary, error) {
	filename = strings.TrimPrefix(filename, "repos/src")
	githubLink := strings.TrimPrefix(dir, "repos/src")
	fileURL := "https://" + strings.TrimPrefix(dir, "repos/src/") + "/blob/master" + strings.TrimPrefix(filename, githubLink)
	fs := FileSummary{
		Filename: filename,
		FileURL:  fileURL,
	}
	split := strings.Split(string(out), "\n")
	for _, sp := range split[0 : len(split)-1] {
		parts := strings.Split(sp, ":")
		msg := sp
		if cmd != "gocyclo" {
			msg = parts[len(parts)-1]
		}
		e := Error{ErrorString: msg}
		switch cmd {
		case "golint", "gocyclo", "vet":
			ln, err := strconv.Atoi(strings.Split(sp, ":")[1])
			if err != nil {
				return fs, err
			}
			e.LineNumber = ln
		}

		fs.Errors = append(fs.Errors, e)
	}

	return fs, nil
}
Exemple #14
0
func uri(workdir, fn string) string {
	u := fn
	u = strings.TrimPrefix(u, path.Join(workdir, "markdowns"))
	u = strings.TrimPrefix(u, path.Join(workdir, "templates"))
	u = strings.TrimPrefix(u, path.Join(workdir, "statics"))
	return u
}
Exemple #15
0
func simpleImporter(imports map[string]*ast.Object, path string) (*ast.Object, error) {
	pkg := imports[path]
	if pkg == nil {
		// Guess the package name without importing it. Start with the last
		// element of the path.
		name := path[strings.LastIndex(path, "/")+1:]

		// Trim commonly used prefixes and suffixes containing illegal name
		// runes.
		name = strings.TrimSuffix(name, ".go")
		name = strings.TrimSuffix(name, "-go")
		name = strings.TrimPrefix(name, "go.")
		name = strings.TrimPrefix(name, "go-")
		name = strings.TrimPrefix(name, "biogo.")

		// It's also common for the last element of the path to contain an
		// extra "go" prefix, but not always. TODO: examine unresolved ids to
		// detect when trimming the "go" prefix is appropriate.

		pkg = ast.NewObj(ast.Pkg, name)
		pkg.Data = ast.NewScope(nil)
		imports[path] = pkg
	}
	return pkg, nil
}
Exemple #16
0
// Read an input configuration file, parsing it (as YAML or JSON)
// into the input 'interface{}', v
func Read(path string, v interface{}, schema string) []serror.SnapError {
	// read bytes from file
	b, err := cfgReader.ReadFile(path)
	if err != nil {
		return []serror.SnapError{serror.New(err)}
	}
	// convert from YAML to JSON (remember, JSON is actually valid YAML)
	jb, err := yaml.YAMLToJSON(b)
	if err != nil {
		return []serror.SnapError{serror.New(fmt.Errorf("error converting YAML to JSON: %v", err))}
	}
	// validate the resulting JSON against the input the schema
	if errors := cfgValidator.validateSchema(schema, string(jb)); errors != nil {
		// if invalid, construct (and return?) a SnapError from the errors identified
		// during schema validation
		return errors
	}
	// if valid, parse the JSON byte-stream (above)
	if parseErr := json.Unmarshal(jb, v); parseErr != nil {
		// remove any YAML-specific prefix that might have been added by then
		// yaml.Unmarshal() method or JSON-specific prefix that might have been
		// added if the resulting JSON string could not be marshalled into our
		// input interface correctly (note, if there is no match to either of
		// these prefixes then the error message will be passed through unchanged)
		tmpErr := strings.TrimPrefix(parseErr.Error(), "error converting YAML to JSON: yaml: ")
		errRet := strings.TrimPrefix(tmpErr, "error unmarshaling JSON: json: ")
		return []serror.SnapError{serror.New(fmt.Errorf("Error while parsing configuration file: %v", errRet))}
	}
	return nil
}
Exemple #17
0
func (t *LibCTarget) GetOutputFile() *actions.File {
	if file_list == nil {
		file_list = make(map[string]*actions.File)
	}

	outfile_name := strings.TrimPrefix(t.Name, "//") + ".a"

	f, ok := file_list[outfile_name]
	if ok {
		return f
	}

	inputs := actions.MakeCObjects(t.Name, t.Sources, t.Resources, file_list)
	ar_action := actions.Action{
		Name:    strings.TrimPrefix(t.Name, "//"),
		Infiles: inputs,
		Method:  "Task.ArLink",
	}
	outfile := actions.File{
		Filename: outfile_name,
		Action:   &ar_action,
		Sem:      make(chan int, 1),
	}

	file_list[outfile_name] = &outfile
	return &outfile
}
Exemple #18
0
// cleanWindowsName will clean invalid Windows characters
func cleanWindowsName(f *Fs, name string) string {
	original := name
	var name2 string
	if strings.HasPrefix(name, `\\?\`) {
		name2 = `\\?\`
		name = strings.TrimPrefix(name, `\\?\`)
	}
	if strings.HasPrefix(name, `//?/`) {
		name2 = `//?/`
		name = strings.TrimPrefix(name, `//?/`)
	}
	// Colon is allowed as part of a drive name X:\
	colonAt := strings.Index(name, ":")
	if colonAt > 0 && colonAt < 3 && len(name) > colonAt+1 {
		// Copy to name2, which is unfiltered
		name2 += name[0 : colonAt+1]
		name = name[colonAt+1:]
	}

	name2 += strings.Map(func(r rune) rune {
		switch r {
		case '<', '>', '"', '|', '?', '*', ':':
			return '_'
		}
		return r
	}, name)

	if name2 != original && f != nil {
		if _, ok := f.warned[name]; !ok {
			fs.Debug(f, "Replacing invalid characters in %q to %q", name, name2)
			f.warned[name] = struct{}{}
		}
	}
	return name2
}
Exemple #19
0
// ParseTCPAddr parses and validates that the specified address is a valid TCP
// address. It returns a formatted TCP address, either using the address parsed
// from tryAddr, or the contents of defaultAddr if tryAddr is a blank string.
// tryAddr is expected to have already been Trim()'d
// defaultAddr must be in the full `tcp://host:port` form
func ParseTCPAddr(tryAddr string, defaultAddr string) (string, error) {
	if tryAddr == "" || tryAddr == "tcp://" {
		return defaultAddr, nil
	}
	addr := strings.TrimPrefix(tryAddr, "tcp://")
	if strings.Contains(addr, "://") || addr == "" {
		return "", fmt.Errorf("Invalid proto, expected tcp: %s", tryAddr)
	}

	u, err := url.Parse("tcp://" + addr)
	if err != nil {
		return "", err
	}
	hostParts := strings.Split(u.Host, ":")
	if len(hostParts) != 2 {
		return "", fmt.Errorf("Invalid bind address format: %s", tryAddr)
	}
	defaults := strings.Split(defaultAddr, ":")
	if len(defaults) != 3 {
		return "", fmt.Errorf("Invalid defaults address format: %s", defaultAddr)
	}

	host := hostParts[0]
	if host == "" {
		host = strings.TrimPrefix(defaults[1], "//")
	}
	if hostParts[1] == "" {
		hostParts[1] = defaults[2]
	}
	p, err := strconv.Atoi(hostParts[1])
	if err != nil && p == 0 {
		return "", fmt.Errorf("Invalid bind address format: %s", tryAddr)
	}
	return fmt.Sprintf("tcp://%s:%d%s", host, p, u.Path), nil
}
Exemple #20
0
// input makes a dataset available for computations in the container.
func (p *pipeline) input(name string) error {
	var trimmed string
	switch {
	case strings.HasPrefix(name, "s3://"):
		trimmed = strings.TrimPrefix(name, "s3://")
		if err := WaitPipeline(p.pipelineDir, trimmed, p.commit); err != nil {
			return err
		}
		if err := p.bind(path.Join(p.pipelineDir, trimmed), "", path.Join("/in", trimmed)); err != nil {
			return err
		}
	case strings.HasPrefix(name, "pps://"):
		trimmed = strings.TrimPrefix(name, "pps://")
		if err := WaitPipeline(p.pipelineDir, trimmed, p.commit); err != nil {
			return err
		}
		if err := p.bind(path.Join(p.pipelineDir, trimmed), "", path.Join("/in", trimmed)); err != nil {
			return err
		}
	case strings.HasPrefix(name, "pfs://"):
		fallthrough
	default:
		if err := p.bind(p.inRepo, name, path.Join("/in", name)); err != nil {
			return err
		}
	}
	return nil
}
Exemple #21
0
// ListKeys returns a map of unique PublicKeys present on the KeyFileStore and
// their corresponding aliases.
func listKeys(s LimitedFileStore) map[string]string {
	keyIDMap := make(map[string]string)

	for _, f := range s.ListFiles() {
		// Remove the prefix of the directory from the filename
		if f[:len(rootKeysSubdir)] == rootKeysSubdir {
			f = strings.TrimPrefix(f, rootKeysSubdir+"/")
		} else {
			f = strings.TrimPrefix(f, nonRootKeysSubdir+"/")
		}

		// Remove the extension from the full filename
		// abcde_root.key becomes abcde_root
		keyIDFull := strings.TrimSpace(strings.TrimSuffix(f, filepath.Ext(f)))

		// If the key does not have a _, it is malformed
		underscoreIndex := strings.LastIndex(keyIDFull, "_")
		if underscoreIndex == -1 {
			continue
		}

		// The keyID is the first part of the keyname
		// The KeyAlias is the second part of the keyname
		// in a key named abcde_root, abcde is the keyID and root is the KeyAlias
		keyID := keyIDFull[:underscoreIndex]
		keyAlias := keyIDFull[underscoreIndex+1:]
		keyIDMap[keyID] = keyAlias
	}
	return keyIDMap
}
Exemple #22
0
func c_hbase_replication() (opentsdb.MultiDataPoint, error) {
	var j jmx
	if err := getBeans(hbRepURL, &j); err != nil {
		return nil, err
	}
	excludeReg, err := regexp.Compile("source.\\d")
	if err != nil {
		return nil, err
	}
	var md opentsdb.MultiDataPoint
	for _, section := range j.Beans {
		for k, v := range section {
			// source.[0-9] entries are for other hosts in the cluster
			if excludeReg.MatchString(k) {
				continue
			}
			// Strip "source." and "sink." from the metric names.
			shortName := strings.TrimPrefix(k, "source.")
			shortName = strings.TrimPrefix(shortName, "sink.")
			metric := "hbase.region." + shortName
			if _, ok := v.(float64); ok {
				Add(&md, metric, v, nil, metadata.Unknown, metadata.None, "")
			}
		}
	}
	return md, nil
}
func TestSnmpServer(t *testing.T) {
	srv, e := NewUdpServerFromString("a", "127.0.0.1:0", mib_string, false)
	if nil != e {
		t.Error(e)
		return
	}
	defer srv.Close()

	for idx, test := range oid_and_value {
		oid := strings.TrimPrefix(test.oid, "[oid]")
		v, e := ReadSnmpValue("127.0.0.1:"+srv.GetPort(), oid, SNMP_PDU_GET)
		if nil != e {
			t.Error("test[", idx, "]", test.oid, e)
			continue
		}

		if v.String() != test.value {
			t.Error("test[", idx, "]", v.String(), "of", test.oid, "is not equals", test.value)
		}
	}

	for idx, test := range next_oid_and_value {
		oid := strings.TrimPrefix(test.oid, "[oid]")
		v, e := ReadSnmpValue("127.0.0.1:"+srv.GetPort(), oid, SNMP_PDU_GETNEXT)
		if nil != e {
			t.Error("testNext[", idx, "]", test.oid, e)
			continue
		}

		if v.String() != test.value {
			t.Error("testNext[", idx, "]", v.String(), "of", test.oid, "is not equals", test.value)
		}
	}
}
Exemple #24
0
func (ta *Table) AddColumn(name string, columnType string, extra string) {
	index := len(ta.Columns)
	ta.Columns = append(ta.Columns, TableColumn{Name: name})

	if strings.Contains(columnType, "int") || strings.HasPrefix(columnType, "year") {
		ta.Columns[index].Type = TYPE_NUMBER
	} else if columnType == "float" || columnType == "double" {
		ta.Columns[index].Type = TYPE_FLOAT
	} else if strings.HasPrefix(columnType, "enum") {
		ta.Columns[index].Type = TYPE_ENUM
		ta.Columns[index].EnumValues = strings.Split(strings.Replace(
			strings.TrimSuffix(
				strings.TrimPrefix(
					columnType, "enum("),
				")"),
			"'", "", -1),
			",")
	} else if strings.HasPrefix(columnType, "set") {
		ta.Columns[index].Type = TYPE_SET
		ta.Columns[index].SetValues = strings.Split(strings.Replace(
			strings.TrimSuffix(
				strings.TrimPrefix(
					columnType, "set("),
				")"),
			"'", "", -1),
			",")
	} else {
		ta.Columns[index].Type = TYPE_STRING
	}

	if extra == "auto_increment" {
		ta.Columns[index].IsAuto = true
	}
}
Exemple #25
0
func (config TaskConfig) validateDotPath() []string {
	messages := []string{}

	pathCount := 0
	dotPath := false

	for _, input := range config.Inputs {
		path := strings.TrimPrefix(input.resolvePath(), "./")

		if path == "." {
			dotPath = true
		}

		pathCount++
	}

	for _, output := range config.Outputs {
		path := strings.TrimPrefix(output.resolvePath(), "./")

		if path == "." {
			dotPath = true
		}

		pathCount++
	}

	if pathCount > 1 && dotPath {
		messages = append(messages, "  you may not have more than one input or output when one of them has a path of '.'")
	}

	return messages
}
Exemple #26
0
func (s *ServiceRuntime) stopContainer(container *docker.Container) error {
	if _, ok := blacklistedContainerId[container.ID]; ok {
		log.Printf("Container %s blacklisted. Won't try to stop.\n", container.ID)
		return nil
	}

	log.Printf("Stopping %s container %s\n", strings.TrimPrefix(container.Name, "/"), container.ID[0:12])

	c := make(chan error, 1)
	go func() { c <- s.dockerClient.StopContainer(container.ID, 10) }()
	select {
	case err := <-c:
		if err != nil {
			log.Printf("ERROR: Unable to stop container: %s\n", container.ID)
			return err
		}
	case <-time.After(20 * time.Second):
		blacklistedContainerId[container.ID] = true
		log.Printf("ERROR: Timed out trying to stop container. Zombie?. Blacklisting: %s\n", container.ID)
		return nil
	}
	log.Printf("Stopped %s container %s\n", strings.TrimPrefix(container.Name, "/"), container.ID[0:12])

	return nil
	// TODO: why is this commented out?
	//       Should we verify that containers are actually removed somehow?
	/*	return s.dockerClient.RemoveContainer(docker.RemoveContainerOptions{
		ID:            container.ID,
		RemoveVolumes: true,
	})*/
}
Exemple #27
0
// Return the text of the comment with // or /* and */ stripped
func (c Comment) Text() string {
	l := 0
	for _, comment := range c.Comment {
		l += len(comment) + 1
	}
	buf := make([]byte, 0, l)

	blockComment := false
	if strings.HasPrefix(c.Comment[0], "/*") {
		blockComment = true
	}

	for i, comment := range c.Comment {
		if blockComment {
			if i == 0 {
				comment = strings.TrimPrefix(comment, "/*")
			}
			if i == len(c.Comment)-1 {
				comment = strings.TrimSuffix(comment, "*/")
			}
		} else {
			comment = strings.TrimPrefix(comment, "//")
		}
		buf = append(buf, comment...)
		buf = append(buf, '\n')
	}

	return string(buf)
}
Exemple #28
0
func (me *LoadTestProvider) ChannelsCommand(c *Context, channelId string, message string) *model.CommandResponse {
	cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels"))

	doFuzz := false
	if strings.Index(cmd, "fuzz") == 0 {
		doFuzz = true
		cmd = strings.TrimSpace(strings.TrimPrefix(cmd, "fuzz"))
	}

	channelsr, err := parseRange(cmd, "")
	if err == false {
		channelsr = utils.Range{2, 5}
	}

	var team *model.Team
	if tr := <-Srv.Store.Team().Get(c.TeamId); tr.Err != nil {
		return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
	} else {
		team = tr.Data.(*model.Team)
	}

	client := model.NewClient(c.GetSiteURL())
	client.SetTeamId(team.Id)
	client.MockSession(c.Session.Token)
	channelCreator := NewAutoChannelCreator(client, team)
	channelCreator.Fuzzy = doFuzz
	channelCreator.CreateTestChannels(channelsr)

	return &model.CommandResponse{Text: "Added channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
}
Exemple #29
0
// Lexes a string in single quotes, whitespaces in the string are permitted.
// Example: 'foo bar is great'
func lexQuotedString(l *lexer) stateFn {
	// the string only consists of the current fild
	if strings.HasPrefix(l.input[l.start], "'") && strings.HasSuffix(l.input[l.start], "'") {
		out := strings.TrimPrefix(l.input[l.start], "'")
		out = strings.TrimRight(out, "'")
		l.emit(STRING, out)
		return lexAttributes
	}

	// the string consists of multiple fields
	out := make([]string, 0)
	out = append(out, strings.TrimPrefix(l.input[l.start], "'"))
	l.pos++
	for {
		if l.pos == len(l.input) {
			l.eof("QuotedString")
		}

		if strings.HasSuffix(l.input[l.pos], "'") {
			out = append(out, strings.TrimRight(l.input[l.pos], "'"))
			l.emit(STRING, strings.Join(out, " "))
			return lexAttributes
		}

		out = append(out, l.input[l.pos])

		l.pos++
	}
}
Exemple #30
0
// NewStorageError - return new Error type.
func traceError(e error, errs ...error) error {
	if e == nil {
		return nil
	}
	err := &Error{}
	err.e = e
	err.errs = errs

	stack := make([]uintptr, 40)
	length := runtime.Callers(2, stack)
	if length > len(stack) {
		length = len(stack)
	}
	stack = stack[:length]

	for _, pc := range stack {
		pc = pc - 1
		fn := runtime.FuncForPC(pc)
		file, line := fn.FileLine(pc)
		name := fn.Name()
		if strings.HasSuffix(name, "ServeHTTP") {
			break
		}
		if strings.HasSuffix(name, "runtime.") {
			break
		}

		file = strings.TrimPrefix(file, rootPath+string(os.PathSeparator))
		name = strings.TrimPrefix(name, "github.com/minio/minio/cmd.")
		err.trace = append(err.trace, traceInfo{file, line, name})
	}

	return err
}