Esempio n. 1
0
func (env *Environment) ExpandVars(args string, pe *PlayEnv) (string, error) {
	args, err := env.expandTemplates(args, pe)

	if err != nil {
		return "", err
	}

	a := []byte(args)

	var buf bytes.Buffer

	for {
		idx := bytes.Index(a, cExprStart)

		if idx == -1 {
			buf.Write(a)
			break
		}

		buf.Write(a[:idx])

		in := a[idx+1:]

		fin := findExprClose(in)

		if fin == -1 {
			return "", eUnclosedExpr
		}

		sexp := in[:fin+1]

		val, err := lisp.EvalString(string(sexp), pe.lispScope)

		if err != nil {
			return "", err
		}

		// fmt.Printf("%s => %s\n", string(sexp), val.Inspect())

		buf.WriteString(val.String())
		a = in[fin+1:]
	}

	return buf.String(), nil
}
Esempio n. 2
0
func ExpandVars(s Scope, args string) (string, error) {
	args, err := expandTemplates(s, args)

	if err != nil {
		return "", err
	}

	a := []byte(args)

	var buf bytes.Buffer

	for {
		idx := bytes.Index(a, cDollar)

		if idx == -1 {
			buf.Write(a)
			break
		} else if a[idx+1] == '(' {
			buf.Write(a[:idx])

			in := a[idx+1:]

			fin := findExprClose(in)

			if fin == -1 {
				return "", eUnclosedExpr
			}

			sexp := in[:fin+1]

			ls := lispInferredScope{s}

			val, err := lisp.EvalString(string(sexp), ls)

			if err != nil {
				return "", err
			}

			buf.WriteString(val.String())
			a = in[fin+1:]
		} else {
			buf.Write(a[:idx])

			in := a[idx+1:]

			fin := 0

			for fin < len(in) {
				if !varChar(rune(in[fin])) {
					break
				}
				fin++
			}

			if val, ok := s.Get(string(in[:fin])); ok {
				switch val := val.Read().(type) {
				case int64, int:
					buf.WriteString(fmt.Sprintf("%d", val))
				default:
					buf.WriteString(fmt.Sprintf("%s", val))
				}

				a = in[fin:]
			} else {
				return "", fmt.Errorf("Undefined variable: %s", string(in[:fin]))
			}
		}
	}

	return buf.String(), nil
}