// To attempts rewrite. It attempts to rewrite to first valid path
// or the last path if none of the paths are valid.
5230
func To(fs http.FileSystem, r *http.Request, to string, replacer httpserver.Replacer) Result {
	tos := strings.Fields(to)

	// try each rewrite paths
	t := ""
	query := ""
	for _, v := range tos {
		t = replacer.Replace(v)
		tparts := strings.SplitN(t, "?", 2)
		t = path.Clean(tparts[0])

		if len(tparts) > 1 {
			query = tparts[1]
		}

		// add trailing slash for directories, if present
		if strings.HasSuffix(tparts[0], "/") && !strings.HasSuffix(t, "/") {
			t += "/"
		}

		// validate file
		if validFile(fs, t) {
			break
		}
	}

	// validate resulting path
	u, err := url.Parse(t)
	if err != nil {
		// Let the user know we got here. Rewrite is expected but
		// the resulting url is invalid.
		log.Printf("[ERROR] rewrite: resulting path '%v' is invalid. error: %v", t, err)
		return RewriteIgnored
	}

	// perform rewrite
	r.URL.Path = u.Path
	if query != "" {
		// overwrite query string if present
		r.URL.RawQuery = query
	}
	if u.Fragment != "" {
		// overwrite fragment if present
		r.URL.Fragment = u.Fragment
	}

	return RewriteDone
}
1084287
func (e *FwdEdge) Fwd(c context.Context) (*Attempt, *FwdDep) {
	atmpt := &Attempt{ID: *e.From}
	return atmpt, &FwdDep{
		Depender: ds.KeyForObj(c, atmpt),
		Dependee: *e.To,
	}
}
629263
func (c *gitCredentials) WriteTo(w io.Writer) (int64, error) {
	var n int64
	if c.Protocol != "" {
		i, err := io.WriteString(w, "protocol="+c.Protocol+"\n")
		n += int64(i)
		if err != nil {
			return n, err
		}
	}
	if c.Host != "" {
		i, err := io.WriteString(w, "host="+c.Host+"\n")
		n += int64(i)
		if err != nil {
			return n, err
		}
	}
	if c.Path != "" {
		i, err := io.WriteString(w, "path="+c.Path+"\n")
		n += int64(i)
		if err != nil {
			return n, err
		}
	}
	if c.Username != "" {
		i, err := io.WriteString(w, "username="+c.Username+"\n")
		n += int64(i)
		if err != nil {
			return n, err
		}
	}
	if c.Password != "" {
		i, err := io.WriteString(w, "password="+c.Password+"\n")
		n += int64(i)
		if err != nil {
			return n, err
		}
	}
	return n, nil
}
670209
func (expectation *Expectation) To(matcher Matcher, expected ...interface{}) {
	if !expectation.Example.HasFailure {
		values := append([]interface{}{expectation.Actual}, expected...)
		if failureMessage := matcher(values...); failureMessage != "" {
			expectation.Example.Failed(failureMessage)
		}
	}
}
965131
func (like Like) WriteTo(w Writer) error {
	if _, err := fmt.Fprintf(w, "%s LIKE ?", w.Key(like[0])); err != nil {
		return err
	}
	var values []rune
	for _, v := range like[1] {
		switch v {
		case '_', '%':
			values = append(values, '\\')
			fallthrough
		default:
			values = append(values, v)
		}
	}
	w.Append("%" + string(values) + "%")
	return nil
}
1457
func (rg *RouteGroup) To(methods, path string, handlers ...Handler) *Route {
	mm := strings.Split(methods, ",")
	if len(mm) == 1 {
		return rg.add(methods, path, handlers)
	}

	r := rg.newRoute(methods, path)
	for _, method := range mm {
		r.routes = append(r.routes, rg.add(method, path, handlers))
	}
	return r
}
1369871
func isValidRegexPattern(rewriteFrom, rewriteTo string) (*regexp.Regexp, error) {
	rewriteFromPattern, err := regexp.Compile(rewriteFrom)
	if err != nil {
		return nil, fmt.Errorf("invalid regex matching pattern: %s", rewriteFrom)
	}
	if getSubExprUsage(rewriteTo) > rewriteFromPattern.NumSubexp() {
		return nil, fmt.Errorf("the rewrite regex pattern (%s) uses more subexpressions than its corresponding matching regex pattern (%s)", rewriteTo, rewriteFrom)
	}
	return rewriteFromPattern, nil
}
1352215
func (b *RouteBuilder) To(function RouteFunction) *RouteBuilder {
	b.function = function
	return b
}
109578
func (rule *prefixTtlRule) Rewrite(ctx context.Context, state request.Request) Result {
	if strings.HasPrefix(state.Name(), rule.Prefix) {
		return RewriteDone
	}
	return RewriteIgnored
}
1345518
func (p *Pipe) To(w io.Writer) *Pipe {
	go func() {
		total, err := io.Copy(w, p.reader)
		p.TotalOut = total
		p.errorWriter <- err
	}()
	return p
}
569017
func (rule *edns0NsidRule) Rewrite(ctx context.Context, state request.Request) Result {
	o := setupEdns0Opt(state.Req)

	for _, s := range o.Option {
		if e, ok := s.(*dns.EDNS0_NSID); ok {
			if rule.action == Replace || rule.action == Set {
				e.Nsid = "" // make sure it is empty for request
				return RewriteDone
			}
		}
	}

	// add option if not found
	if rule.action == Append || rule.action == Set {
		o.Option = append(o.Option, &dns.EDNS0_NSID{Code: dns.EDNS0NSID, Nsid: ""})
		return RewriteDone
	}

	return RewriteIgnored
}
1108895
func (p *GSPath) WriteTo(out io.Writer) (int64, error) {
	glog.V(4).Infof("Reading file %q", p)

	response, err := p.client.Objects.Get(p.bucket, p.key).Download()
	if err != nil {
		if isGCSNotFound(err) {
			return 0, os.ErrNotExist
		}
		return 0, fmt.Errorf("error reading %s: %v", p, err)
	}
	if response == nil {
		return 0, fmt.Errorf("no response returned from reading %s", p)
	}
	defer response.Body.Close()

	return io.Copy(out, response.Body)
}
191881
func rewriteSyntax(prog *cc.Prog) {
	cc.Preorder(prog, func(x cc.Syntax) {
		switch x := x.(type) {
		case *cc.Stmt:
			rewriteStmt(x)

		case *cc.Expr:
			switch x.Op {
			case cc.Number:
				// Rewrite char literal.
				// In general we'd need to rewrite all string and char literals
				// but these are the only forms that comes up.
				switch x.Text {
				case `'\0'`:
					x.Text = `'\x00'`
				case `'\"'`:
					x.Text = `'"'`
				}

			case cc.Paren:
				switch x.Left.Op {
				case cc.Number, cc.Name:
					fixMerge(x, x.Left)
				}

			case cc.OrEq, cc.AndEq, cc.Or, cc.Eq, cc.EqEq, cc.NotEq, cc.LtEq, cc.GtEq, cc.Lt, cc.Gt:
				cutParen(x, cc.Or, cc.And, cc.Lsh, cc.Rsh)
			}

		case *cc.Type:
			// Rewrite int f(void) to int f().
			if x.Kind == cc.Func && len(x.Decls) == 1 && x.Decls[0].Name == "" && x.Decls[0].Type.Is(cc.Void) {
				x.Decls = nil
			}
		}
	})

	// Apply changed struct tags to typedefs.
	// Excise dead pieces.
	cc.Postorder(prog, func(x cc.Syntax) {
		switch x := x.(type) {
		case *cc.Type:
			if x.Kind == cc.TypedefType && x.Base != nil && x.Base.Tag != "" {
				x.Name = x.Base.Tag
			}

		case *cc.Stmt:
			if x.Op == cc.StmtExpr && x.Expr.Op == cc.Comma && len(x.Expr.List) == 0 {
				x.Op = cc.Empty
			}
			x.Block = filterBlock(x.Block)

		case *cc.Expr:
			if x.Op == c2go.ExprBlock {
				x.Block = filterBlock(x.Block)
			}

			switch x.Op {
			case cc.Add, cc.Sub:
				// Turn p + y - z, which is really (p + y) - z, into p + (y - z),
				// so that there is only one pointer addition (which will turn into
				// a slice operation using y-z as the index).
				if x.XType != nil && x.XType.Kind == cc.Ptr {
					switch x.Left.Op {
					case cc.Add, cc.Sub:
						if x.Left.XType != nil && x.Left.XType.Kind == cc.Ptr {
							p, op1, y, op2, z := x.Left.Left, x.Left.Op, x.Left.Right, x.Op, x.Right
							if op1 == cc.Sub {
								y = &cc.Expr{Op: cc.Minus, Left: y, XType: y.XType}
							}
							x.Op = cc.Add
							x.Left = p
							x.Right = &cc.Expr{Op: op2, Left: y, Right: z, XType: x.XType}
						}
					}
				}
			}

			// Turn c + p - q, which is really (c + p) - q, into c + (p - q),
			// so that there is no int + ptr addition, only a ptr - ptr subtraction.
			if x.Op == cc.Sub && x.Left.Op == cc.Add && !isPtrOrArray(x.XType) && isPtrOrArray(x.Left.XType) && !isPtrOrArray(x.Left.Left.XType) {
				c, p, q := x.Left.Left, x.Left.Right, x.Right
				expr := x.Left
				expr.Left = p
				expr.Right = q
				expr.Op = cc.Sub
				x.Op = cc.Add
				x.Left = c
				x.Right = expr
				expr.XType = x.XType
			}
		}
	})
}
242379
func (r ComplexRule) Rewrite(fs http.FileSystem, req *http.Request) (re Result) {
	replacer := newReplacer(req)

	// validate regexp if present
	if r.Regexp != nil {
		matches := regexpMatches(r.Regexp, r.Base, req.URL.Path)
		switch len(matches) {
		case 0:
			// no match
			return
		default:
			// set regexp match variables {1}, {2} ...

			// url escaped values of ? and #.
			q, f := url.QueryEscape("?"), url.QueryEscape("#")

			for i := 1; i < len(matches); i++ {
				// Special case of unescaped # and ? by stdlib regexp.
				// Reverse the unescape.
				if strings.ContainsAny(matches[i], "?#") {
					matches[i] = strings.NewReplacer("?", q, "#", f).Replace(matches[i])
				}

				replacer.Set(fmt.Sprint(i), matches[i])
			}
		}
	}

	// attempt rewrite
	return To(fs, req, r.To, replacer)
}
914169
func (r *ReindexDestination) Routing(routing string) *ReindexDestination {
	r.routing = routing
	return r
}
337414
func (rule *regexNameRule) Rewrite(ctx context.Context, state request.Request) Result {
	regexGroups := rule.Pattern.FindStringSubmatch(state.Name())
	if len(regexGroups) == 0 {
		return RewriteIgnored
	}
	s := rule.Replacement
	for groupIndex, groupValue := range regexGroups {
		groupIndexStr := "{" + strconv.Itoa(groupIndex) + "}"
		if strings.Contains(s, groupIndexStr) {
			s = strings.Replace(s, groupIndexStr, groupValue, -1)
		}
	}
	state.Req.Question[0].Name = s
	return RewriteDone
}
326142
func (it *LinksTo) NextPath(ctx context.Context) bool {
	ok := it.primaryIt.NextPath(ctx)
	if !ok {
		it.err = it.primaryIt.Err()
	}
	return ok
}