Exemplo n.º 1
0
// Ensure that there are either loggers or placeholders all the way
// from the specified logger to the root of the logger hierarchy.
func (m *manager) fixupParents(l *Logger) {

	var parent *Logger
	name := l.name
	i := strings.LastIndexByte(name, '/')

	for i > 0 && parent == nil {
		name = name[:i]
		if node, ok := m.registry[name]; ok {
			if p, ok := node.(*placeholder); ok {
				// The logger will be child of this placeholder
				// if anybody asks later.
				p.append(l)
			} else { // it' s a *Logger
				if n, ok := node.(*Logger); ok {
					parent = n
				} else {
					panic("Bad logger in registry")
				}
			}
		} else {
			m.registry[name] = newPlaceholder(l)
		}
		i = strings.LastIndexByte(name, '/')
	}
	if parent == nil {
		parent = m.root
	}
	l.h.SwapParent(parent)
}
Exemplo n.º 2
0
// LastIndexByte returns the index of the last instance of c in s
// or -f if c is not present in s
func LastIndexByte(s string, c byte) int {
	fmt.Println(strings.LastIndexByte("gogopher", 'o')) // 3
	fmt.Println(strings.LastIndexByte("gogopher", 111)) // 3
	fmt.Println(strings.LastIndexByte("gogopher", 112)) // 4
	fmt.Println(strings.LastIndexByte("gogopher", 113)) // -1
	return strings.LastIndexByte(s, c)
}
Exemplo n.º 3
0
// Ensure that there are either loggers or placeholders all the way
// from the specified logger to the root of the logger hierarchy.
func (m *manager) fixupParents(l *Logger) {

	var parent *Logger
	name := l.name
	i := strings.LastIndexByte(name, '/')

	for i > 0 && parent == nil {
		name = name[:i]
		if node, ok := m.registry[name]; ok {
			if p, ok := node.(*placeholder); ok {
				// The logger will be child of this placeholder,
				// somewhere in the subtree.
				// if anybody asks later.
				p.append(l)
			} else { // it' s a *Logger, make it the parent
				if n, ok := node.(*Logger); ok {
					parent = n
				} else {
					// unreachable
					panic("Bad logger in registry")
				}
			}
		} else {
			m.registry[name] = newPlaceholder(l)
		}
		i = strings.LastIndexByte(name, '/')
	}
	if parent == nil {
		// If the logger inherited the root as parent from a child which previous had
		// the root as parent, this will just set it again
		parent = m.root
	}
	l.h.SwapParent(parent)
}
Exemplo n.º 4
0
// GetPackage finds a package by a given name.
// If package doesn't exist in database, then downloads and saves information about new package.
func GetPackage(name string) *MCPMPackage {
	if !db.o {
		open(db.fn)
	}
	if pkg, ok := db.r[name]; ok {
		return pkg
	}
	ht, hte := get(util.DirPathJoin("http://minecraft.curseforge.com/projects", name))
	if hte != nil {
		return nil
	}
	url := ht.Request.URL
	pn := url.Path[strings.LastIndexByte(url.Path, '/')+1:]
	doc, doce := goquery.NewDocumentFromResponse(ht)
	if doce != nil {
		return nil
	}
	tit := doc.Find("h1.project-title a .overflow-tip").Text()
	oa := doc.Find(".RootGameCategory a").Eq(0)
	ida := doc.Find(".view-on-curse a").Eq(0)
	cat := oa.AttrOr("href", " ")
	id := ida.AttrOr("href", "")
	idn := id[strings.LastIndexByte(id, '/')+1:]
	nid, ner := strconv.ParseUint(idn, 10, 64)
	if ner != nil {
		return nil
	}
	pkg := &MCPMPackage{nid, pn, tit, cat[1:]}
	db.r[pn] = pkg
	db.r[idn] = pkg
	db.a = append(db.a, pkg)
	return pkg
}
Exemplo n.º 5
0
Arquivo: file.go Projeto: toksea/iris
// GetParentDir returns the parent directory(string) of the passed targetDirectory (string)
func GetParentDir(targetDirectory string) string {
	lastSlashIndex := strings.LastIndexByte(targetDirectory, os.PathSeparator)
	//check if the slash is at the end , if yes then re- check without the last slash, we don't want /path/to/ , we want /path/to in order to get the /path/ which is the parent directory of the /path/to
	if lastSlashIndex == len(targetDirectory)-1 {
		lastSlashIndex = strings.LastIndexByte(targetDirectory[0:lastSlashIndex], os.PathSeparator)
	}

	parentDirectory := targetDirectory[0:lastSlashIndex]
	return parentDirectory
}
Exemplo n.º 6
0
func (l *SiteList) excludeSubDomain(site string) string {
	i := strings.LastIndexByte(site, '.')
	if i < 0 {
		return site
	}
	i2 := strings.LastIndexByte(site[:i], '.')
	if i2 < 0 {
		return site
	}
	return site[i2+1:]
}
Exemplo n.º 7
0
// Get the name of the leftmost account group.
// The account name is assumed to be valid as indicated by Valid().
// Example: "e:food.snacks" -> "snacks", "e:food" -> "food", "e:" -> "expense"
func (name AccountName) Leaf() string {
	lastIndex := strings.LastIndexByte(string(name), '.')
	if lastIndex != -1 {
		return string(name[lastIndex+1:])
	}
	lastIndex = strings.LastIndexByte(string(name), ':')
	if lastIndex != -1 && len(name) > AccountNameTypePrefixLen {
		return string(name[lastIndex+1:])
	}
	return name.Type().String()
}
Exemplo n.º 8
0
func GetPath(url string) string {
	p := strings.LastIndexByte(url, '?')
	if p > 0 {
		url = url[:p]
	}
	p = strings.LastIndexByte(url, '/')
	if p > 0 {
		return url[:p+1]
	}
	return "/"
}
Exemplo n.º 9
0
Arquivo: util.go Projeto: zhsj/elvish
func ParseVariableQName(qname string) (ns, name string) {
	i := strings.LastIndexByte(qname, ':')
	if i == -1 {
		return "", qname
	}
	return qname[:i+1], qname[i+1:]
}
Exemplo n.º 10
0
// unexpected complains about the token and terminates processing.
func (p *parser) unexpected(tok token, expected ...TokenType) {
	const bufSize = 10
	start := tok.pos - bufSize
	if start < 0 {
		start = 0
	}
	// Skip any new lines just show a single line
	if i := strings.LastIndexByte(p.text[start:tok.pos], '\n'); i != -1 {
		start = start + i + 1
	}
	stop := tok.pos + bufSize
	if stop > len(p.text) {
		stop = len(p.text)
	}
	// Skip any new lines just show a single line
	if i := strings.IndexByte(p.text[tok.pos:stop], '\n'); i != -1 {
		stop = tok.pos + i
	}
	line, char := p.lex.lineNumber(tok.pos)
	expectedStrs := make([]string, len(expected))
	for i := range expected {
		expectedStrs[i] = fmt.Sprintf("%q", expected[i])
	}
	expectedStr := strings.Join(expectedStrs, ",")
	tokStr := tok.typ.String()
	if tok.typ == TokenError {
		tokStr = tok.val
	}
	p.errorf("unexpected %s line %d char %d in \"%s\". expected: %s", tokStr, line, char, p.text[start:stop], expectedStr)
}
Exemplo n.º 11
0
func extractConsumerIdFromOwnerInfo(ownerZnodeData string) (consumerId string) {
	// ownerZnodeData:
	//   for java sdk: $consumerId-$threadNum  $consumerId: $group_$hostname-$timestamp-$uuidSignificantBits
	// for golang sdk: $consumerId
	//         others: $consumerId

	consumerId = ownerZnodeData // by default

	if !strings.Contains(ownerZnodeData, "_") {
		// java consumer group always has the "_"
		return
	}

	lastDash := strings.LastIndexByte(ownerZnodeData, '-')
	if lastDash == -1 || lastDash == len(ownerZnodeData)-1 {
		// java consumer group always has the '-' and not ends with '-'
		return
	}

	maybeJavaThreadNum := ownerZnodeData[lastDash+1:]
	if len(maybeJavaThreadNum) > 3 {
		// not a java consumer group because thread num never above 999
		return
	}

	for _, c := range maybeJavaThreadNum {
		if c < '0' || c > '9' {
			// not a java consumer group because threadNum is digit
			return
		}
	}

	// confirmed, it IS java api consumer group: discard the threadNum section
	return ownerZnodeData[:lastDash]
}
Exemplo n.º 12
0
Arquivo: main.go Projeto: Carbyn/iris
func init() {

	// set the current working dir
	if d, err := os.Getwd(); err != nil {
		panic(err)
	} else {
		workingDir = d
	}

	// defaultInstallDir is the default directory which the create will copy and run the package when finish downloading
	// it's just the last path part of the workingDir
	defaultInstallDir := workingDir[strings.LastIndexByte(workingDir, os.PathSeparator)+1:]

	// init the cli app
	app = cli.NewApp("iris", "Command line tool for Iris web framework", Version)
	// version command
	app.Command(cli.Command("version", "\t      prints your iris version").Action(func(cli.Flags) error { app.Printf("%s", iris.Version); return nil }))

	// create command/-/create.go
	createCmd := cli.Command("create", "create a project to a given directory").
		Flag("offline", false, "set to true to disable the packages download on each create command").
		Flag("dir", defaultInstallDir, "$GOPATH/src/$dir the directory to install the sample package").
		Flag("type", "basic", "creates a project based on the -t package. Currently, available types are 'basic' & 'static'").
		Action(create)

	// run command/-/run.go
	runAndWatchCmd := cli.Command("run", "runs and reload on source code changes, example: iris run main.go").Action(runAndWatch)

	// register the commands
	app.Command(createCmd)
	app.Command(runAndWatchCmd)

	// init the logger
	printer = logger.New(config.DefaultLogger())
}
Exemplo n.º 13
0
// Get splits the specified name by the stored delimiter, and attempts to retrieve the nested value
// corresponding to the nested fields.
func (rc *RecordCache) Get(name string) (interface{}, error) {
	if val, ok := rc.db[name]; ok {
		return val, nil
	}

	var err error
	var val interface{}
	var parent interface{} = rc.top
	var parentName, childName string

	if index := strings.LastIndexByte(name, rc.delim); index >= 0 {
		parentName, childName = name[:index], name[index+1:]
		parent, err = rc.Get(parentName)
		if err != nil {
			return nil, err
		}
		rc.db[parentName] = parent
		if _, ok := parent.(*Record); !ok {
			return nil, ErrNotRecord{datum: parent}
		}
		name = childName
	}

	val, err = parent.(*Record).GetQualified(name)
	if err != nil {
		if nerr, ok := err.(ErrNoSuchField); ok {
			nerr.path = parentName
			return nil, nerr
		}
		return nil, err
	}

	rc.db[name] = val
	return val, nil
}
Exemplo n.º 14
0
func Basename(s string) string {
	n := strings.LastIndexByte(s, '.')
	if n > 0 {
		return s[:n]
	}
	return s
}
Exemplo n.º 15
0
func getContext(content []byte, offset int64) (int, string, int) {
	if offset >= int64(len(content)) || offset < 0 {
		return 0, fmt.Sprintf("[error: Offset %d is out of bounds 0..%d]", offset, len(content)), 0
	}

	lineN := strings.Count(string(content[:offset]), "\n") + 1

	start := strings.LastIndexByte(string(content[:offset]), '\n')
	if start == -1 {
		start = 0
	} else {
		start++
	}

	end := strings.IndexByte(string(content[start:]), '\n')
	l := ""
	if end == -1 {
		l = string(content[start:])
	} else {
		end = end + start
		l = string(content[start:end])
	}

	return lineN, l, (int(offset) - start)
}
Exemplo n.º 16
0
func getProviderURLFromAccountName(accountName string) (string, error) {
	idx := strings.LastIndexByte(accountName, '/')
	if idx < 0 || idx != len(accountName)-33 {
		return "", fmt.Errorf("does not appear to be an account name: %#v", accountName)
	}
	return "https://" + accountName[0:idx], nil
}
Exemplo n.º 17
0
func makeFunc(fn interface{}, traits FuncTrait) *Func {
	name := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
	if dot := strings.LastIndexByte(name, '.'); dot >= 0 {
		name = name[dot+1:]
	}
	return makeNamedFunc(fn, name, traits)
}
Exemplo n.º 18
0
Arquivo: set.go Projeto: tg/suffix
// PlusOne returns matching suffix plus one label from the name.
// For example if set containt 'com' and name is 'www.blog.com',
// this function would return 'blog.com'. Returned string is empty if there
// is no matching suffix in the set or an additional label is missing.
func PlusOne(set *Set, name string) string {
	pre, suf := set.Split(name)
	if suf == "" || pre == "" {
		return ""
	}
	return pre[strings.LastIndexByte(pre, '.')+1:] + "." + suf
}
Exemplo n.º 19
0
Arquivo: set.go Projeto: tg/suffix
// Match returns the longest matching suffix.
// If nothing matches empty string is returned.
func (set *Set) Match(name string) string {
	if len(set.names) == 0 || len(name) == 0 {
		return ""
	}

	// Shrink to longest suffix
	dot := len(name)
	for n := set.maxLabels; n > 0 && dot > 0; n-- {
		dot = strings.LastIndexByte(name[:dot], '.')
	}
	s := name[dot+1:]

	// Find matching suffix
	for len(s) > 0 {
		if _, ok := set.names[s]; ok {
			return s
		}
		dot := strings.IndexByte(s, '.')
		if dot < 0 {
			return ""
		}
		s = s[dot+1:]
	}

	return ""
}
Exemplo n.º 20
0
// comma inserts commas in a decimal integer or floating-point string.
func comma(s string) string {
	var buf bytes.Buffer
	var dec string
	n := len(s)
	if s[0] == '-' || s[0] == '+' {
		n--
		buf.WriteByte(s[0])
		s = s[1:]
	}
	if dot := strings.LastIndexByte(s, '.'); dot >= 0 {
		n -= len(s[dot:])
		dec = s[dot:]
		s = s[:dot]
	}
	commaPos := n % 3
	if commaPos == 0 {
		commaPos = 3
	}
	for i := 0; i < n; i++ {
		if i == commaPos {
			buf.WriteByte(',')
			commaPos += 3
		}
		buf.WriteByte(s[i])
	}
	return buf.String() + dec
}
Exemplo n.º 21
0
func stripExtension(filename string) string {
	sep := strings.LastIndexByte(filename, '.')
	if sep == -1 {
		return filename
	}
	return filename[:sep]
}
Exemplo n.º 22
0
// Get the directory name from a path.  path.Dir doesn't
// do what we want in the case where there is no path
// separator:
func parentDir(path string) string {
	slash := strings.LastIndexByte(path, os.PathSeparator)
	dir := ""
	if slash >= 0 {
		dir = path[:slash]
	}
	return dir
}
Exemplo n.º 23
0
Arquivo: cmd.go Projeto: udhos/nexthop
func StripLastToken(path string) (string, string) {
	path = strings.TrimRight(path, " ")
	last := strings.LastIndexByte(path, ' ')
	if last < 0 {
		return "", path
	}
	return path[:last], path[last+1:]
}
Exemplo n.º 24
0
func (h *HTTPServer) director(req *http.Request) error {
	dot := strings.LastIndexByte(req.Host, '.')
	name := req.Host[:dot]

	var err error
	req.URL.Scheme, req.URL.Host, err = h.hostForApp(name)
	return err
}
Exemplo n.º 25
0
func validEntry(ent *objectEntry) bool {
	if ent.FromSHA1 != fileSHA1 {
		return false
	}

	i := strings.LastIndexByte(ent.ToPos, ':')
	if i < 0 {
		return false
	}
	i = strings.LastIndexByte(ent.ToPos[:i], ':')
	if i < 0 {
		return false
	}
	fn := ent.ToPos[:i]

	return fileSHA(fn) == ent.ToSHA1
}
Exemplo n.º 26
0
func (id ID) Resource() string {
	idx := strings.LastIndexByte(string(id), '/')
	if idx < 0 {
		return ""
	}

	return string(id)[idx+1:]
}
Exemplo n.º 27
0
// Applies the currently active module in the fields of the log entry.
// Returns nil if log level is not relevant.
func (self *Logger) applyModule(level logrus.Level) *logrus.Entry {
	if level > self.Level {
		return nil
	}

	var module string
	if self.activeModule != "" {
		module = self.activeModule
	} else {

		// Look three functions upwards in the stack, where the log call
		// comes from, and use that as the module name.
		_, file, _, ok := runtime.Caller(3)
		if !ok {
			return self.WithField("module", "<unknown>")
		}
		extPos := strings.LastIndexByte(file, '.')
		if extPos < 0 {
			extPos = len(file)
		}
		lastSlash := strings.LastIndexByte(file, '/')
		if lastSlash < 0 {
			lastSlash = 0
		} else {
			lastSlash += 1
		}
		module = string(file[lastSlash:extPos])
	}

	// Filter based on modules selected.
	if len(self.moduleFilter) > 0 {
		var found bool = false
		for i := range self.moduleFilter {
			if self.moduleFilter[i] == module {
				found = true
				break
			}
		}
		if !found {
			return nil
		}
	}

	return self.WithField("module", module)
}
Exemplo n.º 28
0
func containsEnder(line string, ender byte, allowFirst bool) bool {
	index := strings.LastIndexByte(line, ender)
	if index > 0 {
		return true
	} else if index == 0 && allowFirst {
		return true
	}
	return false
}
Exemplo n.º 29
0
func GetParent(url string) string {
	if len(url) > 3 {
		p := strings.LastIndexByte(url[:len(url)-1], '/')
		if p > 0 {
			return url[:p+1]
		}
	}
	return "/"
}
Exemplo n.º 30
0
func GetBaseName(path string) (string, bool) {
	index := strings.LastIndexByte(path, os.PathSeparator)

	if index == -1 || index == (len(path)-1) {
		return "", false
	}

	return path[index+1:], true
}