// tagURLForParser implements a {% urlfor %} tag.
//
// urlfor takes one argument for the controller, as well as any number of key/value pairs for additional URL data.
// Example: {% urlfor "UserController.View" ":slug" "oal" %}
776463
func tagAppendParser(doc *p2.Parser, start *p2.Token, arguments *p2.Parser) (p2.INodeTag, *p2.Error) {
	var name string
	var isPublic bool
	// Parse variable name
	typeToken := arguments.MatchType(p2.TokenIdentifier)
	if typeToken != nil {
		name = typeToken.Val
	} else if sToken := arguments.MatchType(p2.TokenString); nil != sToken {
		name = sToken.Val
	} else {
		return nil, arguments.Error("Expected an identifier or string.", nil)
	}

	evals := []p2.IEvaluator{}
	for arguments.Remaining() > 0 {
		expr, err := arguments.ParseExpression()
		if err != nil {
			return nil, err
		}
		evals = append(evals, expr)
	}

	return &INodeImplied{Exec: func(ctx *p2.ExecutionContext, w p2.TemplateWriter) *p2.Error {

		node := &tagAppendNode{isPublic, name, evals}
		return node.Execute(ctx, w)
	}}, nil

}
1361942
func (repo *Repository) GetTagsAfter(after string, limit int) (*TagsResult, error) {
	allTags, err := repo.GetTags()
	if err != nil {
		return nil, fmt.Errorf("GetTags: %v", err)
	}

	if limit < 0 {
		limit = 0
	}

	numAllTags := len(allTags)
	if len(after) == 0 && limit == 0 {
		return &TagsResult{
			HasLatest: true,
			ReachEnd:  true,
			Tags:      allTags,
		}, nil
	} else if len(after) == 0 && limit > 0 {
		endIdx := limit
		if limit >= numAllTags {
			endIdx = numAllTags
		}
		return &TagsResult{
			HasLatest: true,
			ReachEnd:  limit >= numAllTags,
			Tags:      allTags[:endIdx],
		}, nil
	}

	previousAfter := ""
	hasMatch := false
	tags := make([]string, 0, len(allTags))
	for i := range allTags {
		if hasMatch {
			tags = allTags[i:]
			break
		}
		if allTags[i] == after {
			hasMatch = true
			if limit > 0 && i-limit >= 0 {
				previousAfter = allTags[i-limit]
			}
			continue
		}
	}

	if !hasMatch {
		tags = allTags
	}

	// If all tags after match is equal to the limit, it reaches the oldest tag as well.
	if limit == 0 || len(tags) <= limit {
		return &TagsResult{
			HasLatest:     !hasMatch,
			PreviousAfter: previousAfter,
			ReachEnd:      true,
			Tags:          tags,
		}, nil
	}
	return &TagsResult{
		HasLatest:     !hasMatch,
		PreviousAfter: previousAfter,
		Tags:          tags[:limit],
	}, nil
}
1044027
func URLFunc(v string) (interface{}, error) {
	u, err := url.Parse(v)
	if err != nil {
		return nil, fmt.Errorf("unable parse URL: %v", err)
	}
	return *u, nil
}
168995
func DefaultTagHandler(ctx *tagContext) error {
	if len(ctx.params) > 0 {
		ctx.col.Default = ctx.params[0]
	} else {
		ctx.col.Default = ctx.nextTag
		ctx.ignoreNext = true
	}
	return nil
}
588412
func (l *LogParserPlugin) parser() {
	defer l.wg.Done()

	var m telegraf.Metric
	var err error
	var entry logEntry
	for {
		select {
		case <-l.done:
			return
		case entry = <-l.lines:
			if entry.line == "" || entry.line == "\n" {
				continue
			}
		}
		m, err = l.GrokParser.ParseLine(entry.line)
		if err == nil {
			if m != nil {
				tags := m.Tags()
				tags["path"] = entry.path
				l.acc.AddFields(m.Name(), m.Fields(), tags, m.Time())
			}
		} else {
			log.Println("E! Error parsing log line: " + err.Error())
		}

	}
}
1054431
func (p *Parser) parseFilter() (*filterCall, *Error) {
	identToken := p.MatchType(TokenIdentifier)

	// Check filter ident
	if identToken == nil {
		return nil, p.Error("Filter name must be an identifier.", nil)
	}

	filter := &filterCall{
		token: identToken,
		name:  identToken.Val,
	}

	// Get the appropriate filter function and bind it
	filterFn, exists := filters[identToken.Val]
	if !exists {
		return nil, p.Error(fmt.Sprintf("Filter '%s' does not exist.", identToken.Val), identToken)
	}

	filter.filterFunc = filterFn

	// Check for filter-argument (2 tokens needed: ':' ARG)
	if p.Match(TokenSymbol, ":") != nil {
		if p.Peek(TokenSymbol, "}}") != nil {
			return nil, p.Error("Filter parameter required after ':'.", nil)
		}

		// Get filter argument expression
		v, err := p.parseVariableOrLiteral()
		if err != nil {
			return nil, err
		}
		filter.parameter = v
	}

	return filter, nil
}
1424
func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) {
	if z.nAttrReturned < len(z.attr) {
		switch z.tt {
		case StartTagToken, SelfClosingTagToken:
			x := z.attr[z.nAttrReturned]
			z.nAttrReturned++
			key = z.buf[x[0].start:x[0].end]
			val = z.buf[x[1].start:x[1].end]
			return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr)
		}
	}
	return nil, nil, false
}
646478
func parseTag(tag string) (string, tagOptions) {
	s := strings.Split(tag, ",")
	return s[0], s[1:]
}
118566
func (c *Context) HTMLParser() (*goquery.Document, error) {
	res := c.Response()
	defer res.Body.Close()
	return goquery.NewDocumentFromReader(res.Body)
}
671767
func (t *Tag) GetURL() string {
	if t == nil || t.URL == nil {
		return ""
	}
	return *t.URL
}
1001163
func parseFor(t *Tree, start Pos) (*ForNode, error) {
	var kn, vn string
	nam, err := t.parseInnerExpr()
	if err != nil {
		return nil, err
	}
	if nam, ok := nam.(*NameExpr); ok {
		vn = nam.Name
	} else {
		return nil, errors.New("parse error: a parse error occured, expected name")
	}
	nxt := t.peekNonSpace()
	if nxt.tokenType == tokenPunctuation && nxt.value == "," {
		t.next()
		kn = vn
		nam, err = t.parseInnerExpr()
		if err != nil {
			return nil, err
		}
		if nam, ok := nam.(*NameExpr); ok {
			vn = nam.Name
		} else {
			return nil, errors.New("parse error: a parse error occured, expected name")
		}
	}
	tok := t.nextNonSpace()
	if tok.tokenType != tokenName && tok.value != "in" {
		return nil, newUnexpectedTokenError(tok)
	}
	expr, err := t.parseExpr()
	if err != nil {
		return nil, err
	}
	tok, err = t.expect(tokenTagClose, tokenName)
	if err != nil {
		return nil, err
	}
	var ifCond Expr
	if tok.tokenType == tokenName {
		if tok.value != "if" {
			return nil, errors.New("parse error: a parse error occured")
		}
		ifCond, err = t.parseExpr()
		if err != nil {
			return nil, err
		}
		tok, err = t.expect(tokenTagClose)
		if err != nil {
			return nil, err
		}
	}
	var body Node
	body, err = t.parseUntilTag(tok.Pos, "endfor", "else")
	if err != nil {
		return nil, err
	}
	if ifCond != nil {
		body = NewIfNode(ifCond, body, nil, tok.Pos)
	}
	t.backup()
	tok = t.next()
	var elseBody Node = NewBodyNode(tok.Pos)
	if tok.value == "else" {
		_, err = t.expect(tokenTagClose)
		if err != nil {
			return nil, err
		}
		elseBody, err = t.parseUntilTag(tok.Pos, "endfor")
		if err != nil {
			return nil, err
		}
	}
	_, err = t.expect(tokenTagClose)
	if err != nil {
		return nil, err
	}
	return NewForNode(kn, vn, expr, body, elseBody, start), nil
}
1167575
func (a *Wrapper) RouteTags() {
	if _, y := a.Controller.(Initer); !y {
		a.Module.Core.Logger().Infof(`%T is no method Init(echo.Context)error, skiped.`, a.Controller)
		return
	}
	t := reflect.TypeOf(a.Controller)
	e := t.Elem()
	v := reflect.ValueOf(a.Controller)
	ctlPath := e.PkgPath() + `.(*` + e.Name() + `).`
	//github.com/webx-top/{Project}/app/{Module}/controller.(*Index).

	var ctl string
	if a.Module.URLConvert != nil {
		ctl = a.Module.URLConvert(e.Name())
	} else {
		ctl = e.Name()
	}
	a.ControllerName = ctl
	for i := 0; i < e.NumField(); i++ {
		f := e.Field(i)
		if !a.Module.Application.MapperCheck(f.Type) {
			continue
		}
		name := strings.Title(f.Name)
		m := v.MethodByName(name)
		if !m.IsValid() && !a.hasMain {
			m = v.MethodByName(`Main`)
			if !m.IsValid() {
				continue
			}
			a.hasMain = true
		}
		/*
			支持的tag:
			1. webx - 路由规则
			2. memo - 注释说明
			webx标签内容支持以下格式：
			1、只指定http请求方式，如`webx:"POST|GET"`
			2、只指定路由规则，如`webx:"index"`
			3、只指定扩展名规则，如`webx:".JSON|XML"`
			4、指定以上全部规则，如`webx:"GET|POST.JSON|XML index"`
			注: 当路径规则以波浪线"~"开头时，表示该规则加在app下，否则加在controller下
		*/
		tag := e.Field(i).Tag
		tagv := tag.Get(a.Module.RouteTagName)
		var methods, extends []string
		var p, w string
		if len(tagv) > 0 {
			tags := strings.Split(tagv, ` `)
			length := len(tags)
			if length >= 2 { //`webx:"GET|POST /index"`
				w = tags[0]
				p = tags[1]
			} else if length == 1 {
				if !routeTagRegex.MatchString(tags[0]) {
					//非全大写字母时，判断为网址规则
					p = tags[0]
				} else { //`webx:"GET|POST"`
					w = tags[0]
				}
			}
		}
		if len(p) == 0 {
			if a.Module.URLConvert != nil {
				p = `/` + a.Module.URLConvert(name)
			} else {
				p = `/` + name
			}
		}
		var ppath string
		if p[0] == '~' {
			p = p[1:]
			if p[0] != '/' {
				p = `/` + p
			}
			ppath = p
		} else {
			if p[0] != '/' {
				p = `/` + p
			}
			ppath = `/` + ctl + p
		}
		var met, ext string
		if len(w) > 0 {
			me := strings.Split(w, `.`)
			met = me[0]
			if len(me) > 1 {
				ext = me[1]
			}
		}
		if len(met) > 0 {
			methods = strings.Split(met, `|`)
		}
		if len(ext) > 0 {
			ext = strings.ToLower(ext)
			extends = strings.Split(ext, `|`)
		}
		k := ctlPath + name + `-fm`
		u := a.Module.Application.URLBuilder.SetExtensions(k, extends)
		h := NewHandler(func(ctx echo.Context) error {
			return a.execute(ctx, k, e, u, name)
		}, k)
		switch len(methods) {
		case 0:
			methods = append(methods, `GET`)
			methods = append(methods, `POST`)
		case 1:
			if methods[0] == `ANY` {
				a.addRouter(ctl, ppath, h)
				continue
			}
		}
		a.addRouter(ctl, ppath, h, methods...)
	}
}
1278046
func (p *Parser) parseFilter(cur *ListNode) error {
	p.pos += len("[?(")
	p.consumeText()
Loop:
	for {
		switch p.next() {
		case eof, '\n':
			return fmt.Errorf("unterminated filter")
		case ')':
			break Loop
		}
	}
	if p.next() != ']' {
		return fmt.Errorf("unclosed array expect ]")
	}
	reg := regexp.MustCompile(`^([^!<>=]+)([!<>=]+)(.+?)$`)
	text := p.consumeText()
	text = string(text[:len(text)-2])
	value := reg.FindStringSubmatch(text)
	if value == nil {
		parser, err := parseAction("text", text)
		if err != nil {
			return err
		}
		cur.append(newFilter(parser.Root, newList(), "exists"))
	} else {
		leftParser, err := parseAction("left", value[1])
		if err != nil {
			return err
		}
		rightParser, err := parseAction("right", value[3])
		if err != nil {
			return err
		}
		cur.append(newFilter(leftParser.Root, rightParser.Root, value[2]))
	}
	return p.parseInsideAction(cur)
}
68391
func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
	expiresTime := time.Now().UTC().Add(20 * time.Minute) // default expiration
	expires, ok := options["expiry"]
	if ok {
		t, ok := expires.(time.Time)
		if ok {
			expiresTime = t
		}
	}
	blobRef := d.client.GetContainerReference(d.container).GetBlobReference(path)
	return blobRef.GetSASURI(azure.BlobSASOptions{
		BlobServiceSASPermissions: azure.BlobServiceSASPermissions{
			Read: true,
		},
		SASOptions: azure.SASOptions{
			Expiry: expiresTime,
		},
	})
}
1336263
func (i *Image) parseResponseFromURL(u string, result interface{}) error {
	resp, err := i.getResponseFromURL(u)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	if err := dec.Decode(&result); err != nil {
		return err
	}

	return nil
}
1358938
func SpecFromURL(u *url.URL) (*Spec, error) {
	q := u.Query()
	sp := Spec{
		Context:   q.Get("context"),
		Namespace: q.Get("namespace"),
		Pod:       u.Hostname(),
		Container: q.Get("container"),
	}
	if sp.Context != "" && !validKubeIdentifier(sp.Context) {
		return nil, errors.Errorf("unsupported context name: %q", sp.Context)
	}
	if sp.Namespace != "" && !validKubeIdentifier(sp.Namespace) {
		return nil, errors.Errorf("unsupported namespace name: %q", sp.Namespace)
	}
	if sp.Pod == "" {
		return nil, errors.New("url lacks pod name")
	}
	if !validKubeIdentifier(sp.Pod) {
		return nil, errors.Errorf("unsupported pod name: %q", sp.Pod)
	}
	if sp.Container != "" && !validKubeIdentifier(sp.Container) {
		return nil, errors.Errorf("unsupported container name: %q", sp.Container)
	}
	return &sp, nil
}
275177
func (f *Fn) HelperParamList() string {
	return join(f.Params, func(p *Param) string { return p.Name + " " + p.HelperType() }, ", ")
}