Exemplo n.º 1
0
        public JobContainer EvaluateJobContainer(
            TemplateToken token,
            DictionaryContextData contextData)
        {
            var result = default(JobContainer);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.Container, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = PipelineTemplateConverter.ConvertToJobContainer(context, token);
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result);
        }
Exemplo n.º 2
0
        public Dictionary <String, String> EvaluateJobDefaultsRun(
            TemplateToken token,
            DictionaryContextData contextData)
        {
            var result = default(Dictionary <String, String>);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.JobDefaultsRun, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = new Dictionary <String, String>(StringComparer.OrdinalIgnoreCase);
                    var mapping = token.AssertMapping("defaults run");
                    foreach (var pair in mapping)
                    {
                        // Literal key
                        var key = pair.Key.AssertString("defaults run key");

                        // Literal value
                        var value = pair.Value.AssertString("defaults run value");
                        result[key.Value] = value.Value;
                    }
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result);
        }
Exemplo n.º 3
0
        public Int32 EvaluateStepTimeout(
            TemplateToken token,
            DictionaryContextData contextData)
        {
            var result = default(Int32?);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.NumberStepsContext, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = PipelineTemplateConverter.ConvertToStepTimeout(context, token);
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result ?? 0);
        }
Exemplo n.º 4
0
        public Dictionary <String, String> EvaluateStepEnvironment(
            TemplateToken token,
            DictionaryContextData contextData,
            StringComparer keyComparer)
        {
            var result = default(Dictionary <String, String>);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.StepEnv, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = PipelineTemplateConverter.ConvertToStepEnvironment(context, token, keyComparer);
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result ?? new Dictionary <String, String>(keyComparer));
        }
Exemplo n.º 5
0
        public static Tuple <Region, List <Method> > Serialize(IMethodImpl method, DocumentConfig documentConfig)
        {
            var template = documentConfig.Templates.FirstOrDefault(t => t.Name == method.Template);

            if (template == null)
            {
                throw new InvalidOperationException($"Template '{method.Template}' does not exist");
            }

            template = new TemplateEvaluator(method, template, documentConfig.Templates).ResolveAll();

            var finalRegions = template.Regions.Select(r => r.Serialize(method, documentConfig)).Where(r => r != null).ToReadOnlyList();
            var finalMethods = template.MethodDefs.SelectMany(m => m.Serialize(method, documentConfig)).ToList();

            if (method.Region)
            {
                var regionName = (method.Description ?? method.Name);

                if (method.PluralRegion)
                {
                    regionName += "s";
                }

                return(Tuple.Create(new Region(regionName, finalRegions, finalMethods.ToReadOnlyList(), false), new List <Method>()));
            }
            else
            {
                return(Tuple.Create <Region, List <Method> >(null, finalMethods));
            }
        }
Exemplo n.º 6
0
        public DictionaryContextData EvaluateStepScopeOutputs(
            TemplateToken token,
            DictionaryContextData contextData)
        {
            var result = default(DictionaryContextData);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.StepsScopeOutputs, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = token.ToContextData().AssertDictionary("steps scope outputs");
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result ?? new DictionaryContextData());
        }
Exemplo n.º 7
0
        public Boolean EvaluateStepIf(
            TemplateToken token,
            DictionaryContextData contextData,
            IList <IFunctionInfo> expressionFunctions,
            IEnumerable <KeyValuePair <String, Object> > expressionState)
        {
            var result = default(Boolean?);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData, expressionFunctions, expressionState);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.StepIfResult, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = PipelineTemplateConverter.ConvertToIfResult(context, token);
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result ?? throw new InvalidOperationException("Step if cannot be null"));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Evaluates a given expression for truthiness.
        /// </summary>
        /// <param name="expressionOrVariableOrText">The value or expression to evaluate.</param>
        /// <returns>Whether the expression evaluates with no errors and the result is truthy (Not empty, 0 or false).</returns>
        public bool EvaluateTruthy(string expressionOrVariableOrText)
        {
            string error;
            var    result = Evaluate(expressionOrVariableOrText, out error);

            return(string.IsNullOrWhiteSpace(error) && result != null && TemplateEvaluator.IsTruthy(result));
        }
Exemplo n.º 9
0
        public DictionaryContextData EvaluateCompositeOutputs(
            IExecutionContext executionContext,
            TemplateToken token,
            IDictionary <string, PipelineContextData> extraExpressionValues)
        {
            var result = default(DictionaryContextData);

            if (token != null)
            {
                var context = CreateContext(executionContext, extraExpressionValues);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, "outputs", token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = token.ToContextData().AssertDictionary("composite outputs");
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result ?? new DictionaryContextData());
        }
Exemplo n.º 10
0
        public List <ActionStep> LoadCompositeSteps(
            TemplateToken token
            )
        {
            var result = default(List <ActionStep>);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(null, null, setMissingContext: false);
                // TODO: we might want to to have a bool to prevent it from filling in with missing context w/ dummy variables
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.StepsInTemplate, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = PipelineTemplateConverter.ConvertToSteps(context, token);
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }
            return(result);
        }
Exemplo n.º 11
0
        public string EvaluateDefaultInput(
            IExecutionContext executionContext,
            string inputName,
            TemplateToken token)
        {
            string result = "";

            if (token != null)
            {
                var context = CreateContext(executionContext);
                try
                {
                    var evaluateResult = TemplateEvaluator.Evaluate(context, "input-default-context", token, 0, null, omitHeader: true);
                    context.Errors.Check();

                    Trace.Info($"Input '{inputName}': default value evaluate result: {StringUtil.ConvertToJson(evaluateResult)}");

                    // String
                    result = evaluateResult.AssertString($"default value for input '{inputName}'").Value;
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    Trace.Error(ex);
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result);
        }
Exemplo n.º 12
0
        public String EvaluateStepDisplayName(
            TemplateToken token,
            DictionaryContextData contextData,
            IList <IFunctionInfo> expressionFunctions)
        {
            var result = default(String);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData, expressionFunctions);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.StringStepsContext, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = PipelineTemplateConverter.ConvertToStepDisplayName(context, token);
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result);
        }
Exemplo n.º 13
0
        //Serialize to either a collection of methods or a region that contains the methods
        public static IEnumerable <IElement> Serialize(IMethodImpl method, DocumentConfig documentConfig)
        {
            var template = documentConfig.Templates.FirstOrDefault(t => t.Name == method.Template);

            if (template == null)
            {
                throw new InvalidOperationException($"Template '{method.Template}' does not exist");
            }

            template = new TemplateEvaluator(method, template, documentConfig.Templates).ResolveAll();

            var finalRegions = template.Regions.Select(r => r.Serialize(method, documentConfig)).Where(r => r != null);
            var finalMethods = template.MethodDefs.SelectMany(m => m.Serialize(method, documentConfig)).ToList();

            if (method.Region)
            {
                var regionName = (method.Description ?? method.Name);

                if (method.PluralRegion)
                {
                    regionName += "s";
                }

                var regionMembers = new List <IElement>();
                regionMembers.AddRange(finalRegions);
                regionMembers.AddRange(finalMethods);

                return(new IElement[] { new Region(regionName, regionMembers.ToReadOnlyList(), false) });
            }
            else
            {
                return(finalMethods);
            }
        }
Exemplo n.º 14
0
        public IList <KeyValuePair <String, JobContainer> > EvaluateJobServiceContainers(
            TemplateToken token,
            DictionaryContextData contextData,
            IList <IFunctionInfo> expressionFunctions)
        {
            var result = default(List <KeyValuePair <String, JobContainer> >);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData, expressionFunctions);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.Services, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = PipelineTemplateConverter.ConvertToJobServiceContainers(context, token);
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result);
        }
Exemplo n.º 15
0
        public TemplateToken EvaluateEnvironmentUrl(
            TemplateToken token,
            DictionaryContextData contextData,
            IList <IFunctionInfo> expressionFunctions)
        {
            var result = default(TemplateToken);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData, expressionFunctions);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, TemplateConstants.StringRunnerContextNoSecrets, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = token.AssertString("environment.url");
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result);
        }
Exemplo n.º 16
0
        public Dictionary <String, String> EvaluateStepInputs(
            TemplateToken token,
            DictionaryContextData contextData,
            IList <IFunctionInfo> expressionFunctions)
        {
            var result = default(Dictionary <String, String>);

            if (token != null && token.Type != TokenType.Null)
            {
                var context = CreateContext(contextData, expressionFunctions);
                try
                {
                    token = TemplateEvaluator.Evaluate(context, PipelineTemplateConstants.StepWith, token, 0, null, omitHeader: true);
                    context.Errors.Check();
                    result = PipelineTemplateConverter.ConvertToStepInputs(context, token);
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result ?? new Dictionary <String, String>(StringComparer.OrdinalIgnoreCase));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Evaluates a given expression as if it were the value of a variable.
        /// </summary>
        /// <param name="expressionOrVariableOrText">The value or expression to evaluate.</param>
        /// <param name="error">Any parsing errors silently found.</param>
        /// <param name="haltOnError">Stop parsing if an error is found.</param>
        /// <returns>The result of the expression.</returns>
        public string Evaluate(string expressionOrVariableOrText, out string error, bool haltOnError = true)
        {
            error = null;
            if (expressionOrVariableOrText == null)
            {
                return(null);
            }

            if (CanEvaluationBeSkippedForExpression(expressionOrVariableOrText))
            {
                return(expressionOrVariableOrText);
            }

            Template template;

            if (!TemplateParser.TryParseTemplate(expressionOrVariableOrText, out template, out error, haltOnError))
            {
                return(expressionOrVariableOrText);
            }

            using (var writer = new StringWriter())
            {
                string[] missingTokens;
                TemplateEvaluator.Evaluate(template, Binding, writer, out missingTokens);
                if (missingTokens.Any())
                {
                    var tokenList = string.Join(", ", missingTokens.Select(token => "'" + token + "'"));
                    error = string.Format("The following tokens were unable to be evaluated: {0}", tokenList);
                }


                return(writer.ToString());
            }
        }
Exemplo n.º 18
0
        public void Setup()
        {
            var mocker = new AutoMoqer();

            _templateEvaluator = mocker.Create <TemplateEvaluator>();
            _evaluator         = mocker.GetMock <ICSharpEvaluator>();
            _evaluator.Setup(e => e.Run(It.IsAny <string>())).Returns(EmptyResult);
        }
Exemplo n.º 19
0
        public void Evaluate_template_that_has_no_expressions()
        {
            TemplateEvaluator templateEvaluator = new TemplateEvaluator();

            string[] actualEvaluations = templateEvaluator.Evaluate(StringConstants.TemplateWithNoExpressions);

            Assert.Equal(StringConstants.TemplateWithNoExpressions, actualEvaluations[0]);
        }
Exemplo n.º 20
0
        private Template GetResolvedTemplate(IMethodImpl methodImpl, DocumentConfig config)
        {
            var template = config.Templates.First(t => t.Name == methodImpl.Template);

            var evaluatedTemplate = new TemplateEvaluator(methodImpl, template, config.Templates);
            var resolvedTemplate  = evaluatedTemplate.ResolveAll();

            return(resolvedTemplate);
        }
Exemplo n.º 21
0
        public void GetResult_return_empty_string()
        {
            var model = new Model(null);

            var templateEvaluator = new TemplateEvaluator(model);

            string result = templateEvaluator.GetResult();

            Assert.IsEmpty(result);
        }
Exemplo n.º 22
0
        public void EvalText_GetResult_return_text()
        {
            var model             = new Model(null);
            var templateEvaluator = new TemplateEvaluator(model);

            var element = new TextTemplateElement("123");

            templateEvaluator.EvalText(element);

            string result = templateEvaluator.GetResult();

            Assert.AreEqual("123", result);
        }
        public static string Eval(string template, Model model)
        {
            var parser = new Parser();

            TemplateModel templateModel = parser.Parse(template);

            var evaluator = new TemplateEvaluator(model);

            foreach (TemplateElement element in templateModel.Elements)
            {
                element.Accept(evaluator);
            }

            return(evaluator.GetResult());
        }
Exemplo n.º 24
0
        public void EvalMethod_GetResult_return_result_of_method()
        {
            var model = new ModelWithMethod(null, "123");

            var evaluator = new TemplateEvaluator(model);

            var element = new MethodCallTemplateElement
            {
                MethodName = "GetText"
            };

            evaluator.EvalMethod(element);

            Assert.AreEqual("123", evaluator.GetResult());
        }
Exemplo n.º 25
0
        public void EvalMethod_throw_TemplateEvaluateException_if_method_does_not_exist()
        {
            var model = new Model(null);

            var evaluator = new TemplateEvaluator(model);

            var element = new MethodCallTemplateElement
            {
                MethodName = "SomeMethod"
            };

            var exception = Assert.Throws <TemplateEvaluateException>(() => evaluator.EvalMethod(element));

            Assert.AreEqual("Method with name 'SomeMethod' does not exist in model.", exception.Message);
        }
Exemplo n.º 26
0
        public Dictionary <string, string> EvaluateContainerEnvironment(
            IExecutionContext executionContext,
            MappingToken token,
            IDictionary <string, PipelineContextData> extraExpressionValues)
        {
            var result = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            if (token != null)
            {
                var context = CreateContext(executionContext, extraExpressionValues);
                try
                {
                    var evaluateResult = TemplateEvaluator.Evaluate(context, "container-runs-env", token, 0, null, omitHeader: true);
                    context.Errors.Check();

                    Trace.Info($"Environments evaluate result: {StringUtil.ConvertToJson(evaluateResult)}");

                    // Mapping
                    var mapping = evaluateResult.AssertMapping("container env");

                    foreach (var pair in mapping)
                    {
                        // Literal key
                        var key = pair.Key.AssertString("container env key");

                        // Literal value
                        var value = pair.Value.AssertString("container env value");
                        result[key.Value] = value.Value;

                        Trace.Info($"Add env {key} = {value}");
                    }
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    Trace.Error(ex);
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result);
        }
Exemplo n.º 27
0
        public void EvalOutputValue_GetResult_return_property_value_as_string()
        {
            var model             = new Model(new { Count = 5 });
            var templateEvaluator = new TemplateEvaluator(model);

            var element = new OutputValueTemplateElement
            {
                ValueAccess = new PropertyValueAccess
                {
                    Name = "Count"
                }
            };

            templateEvaluator.EvalOutputValue(element);

            string result = templateEvaluator.GetResult();

            Assert.AreEqual("5", result);
        }
Exemplo n.º 28
0
        public List <string> EvaluateContainerArguments(
            IExecutionContext executionContext,
            SequenceToken token,
            IDictionary <string, PipelineContextData> extraExpressionValues)
        {
            var result = new List <string>();

            if (token != null)
            {
                var context = CreateContext(executionContext, extraExpressionValues);
                try
                {
                    var evaluateResult = TemplateEvaluator.Evaluate(context, "container-runs-args", token, 0, null, omitHeader: true);
                    context.Errors.Check();

                    Trace.Info($"Arguments evaluate result: {StringUtil.ConvertToJson(evaluateResult)}");

                    // Sequence
                    var args = evaluateResult.AssertSequence("container args");

                    foreach (var arg in args)
                    {
                        var str = arg.AssertString("container arg").Value;
                        result.Add(str);
                        Trace.Info($"Add argument {str}");
                    }
                }
                catch (Exception ex) when(!(ex is TemplateValidationException))
                {
                    Trace.Error(ex);
                    context.Errors.Add(ex);
                }

                context.Errors.Check();
            }

            return(result);
        }
Exemplo n.º 29
0
 internal override void Accept(TemplateEvaluator evaluator)
 {
     evaluator.EvalCondition(this);
 }
 internal override void Accept(TemplateEvaluator evaluator)
 {
     evaluator.EvalText(this);
 }