Пример #1
0
        private void ProcessTemplateItem(StringBuilder newContent, TemplateToken token, object model )
        {
            var value = token.Value;

            if ( value.Length >= 2 && value[1].Equals( '!' ) ) {
                var newValue = @"#{" + value.Substring( 3 );

                ReplaceMatch(newContent, token, newValue );
            } else {
                // Find the processor key
                ITemplateValueProcessor selectedProcessor
                    = GetValueProcessor( token.Key );

                if ( selectedProcessor == null )
                    ReplaceMatch(newContent, token, "<b style='color: red'>TEMPLATE ERROR: Key invalid</b>" );
                else {
                    ReplaceMatch( newContent, token, selectedProcessor.ProcessValue( token.Value, model ) );
                }
            }
        }
Пример #2
0
        internal static TemplateException OptionNamesCannotStartWithDigit(string template, TemplateToken token)
        {
            // Rewrite the token to point to the option name instead of the whole string.
            token = new TemplateToken(
                token.TokenKind,
                token.TokenKind == TemplateToken.Kind.ShortName ? token.Position + 1 : token.Position + 2,
                token.Value, token.Value);

            return(TemplateExceptionFactory.Create(template, token,
                                                   "Option names cannot start with a digit.",
                                                   "Invalid option name."));
        }
Пример #3
0
        private ActionExecutionData ConvertRuns(
            IExecutionContext executionContext,
            TemplateContext templateContext,
            TemplateToken inputsToken,
            String fileRelativePath,
            MappingToken outputs = null)
        {
            var runsMapping         = inputsToken.AssertMapping("runs");
            var usingToken          = default(StringToken);
            var imageToken          = default(StringToken);
            var argsToken           = default(SequenceToken);
            var entrypointToken     = default(StringToken);
            var envToken            = default(MappingToken);
            var mainToken           = default(StringToken);
            var pluginToken         = default(StringToken);
            var preToken            = default(StringToken);
            var preEntrypointToken  = default(StringToken);
            var preIfToken          = default(StringToken);
            var postToken           = default(StringToken);
            var postEntrypointToken = default(StringToken);
            var postIfToken         = default(StringToken);
            var steps = default(List <Pipelines.Step>);

            foreach (var run in runsMapping)
            {
                var runsKey = run.Key.AssertString("runs key").Value;
                switch (runsKey)
                {
                case "using":
                    usingToken = run.Value.AssertString("using");
                    break;

                case "image":
                    imageToken = run.Value.AssertString("image");
                    break;

                case "args":
                    argsToken = run.Value.AssertSequence("args");
                    break;

                case "entrypoint":
                    entrypointToken = run.Value.AssertString("entrypoint");
                    break;

                case "env":
                    envToken = run.Value.AssertMapping("env");
                    break;

                case "main":
                    mainToken = run.Value.AssertString("main");
                    break;

                case "plugin":
                    pluginToken = run.Value.AssertString("plugin");
                    break;

                case "post":
                    postToken = run.Value.AssertString("post");
                    break;

                case "post-entrypoint":
                    postEntrypointToken = run.Value.AssertString("post-entrypoint");
                    break;

                case "post-if":
                    postIfToken = run.Value.AssertString("post-if");
                    break;

                case "pre":
                    preToken = run.Value.AssertString("pre");
                    break;

                case "pre-entrypoint":
                    preEntrypointToken = run.Value.AssertString("pre-entrypoint");
                    break;

                case "pre-if":
                    preIfToken = run.Value.AssertString("pre-if");
                    break;

                case "steps":
                    var stepsToken = run.Value.AssertSequence("steps");
                    steps = PipelineTemplateConverter.ConvertToSteps(templateContext, stepsToken);
                    templateContext.Errors.Check();
                    break;

                default:
                    Trace.Info($"Ignore run property {runsKey}.");
                    break;
                }
            }

            if (usingToken != null)
            {
                if (string.Equals(usingToken.Value, "docker", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(imageToken?.Value))
                    {
                        throw new ArgumentNullException($"You are using a Container Action but an image is not provided in {fileRelativePath}.");
                    }
                    else
                    {
                        return(new ContainerActionExecutionData()
                        {
                            Image = imageToken.Value,
                            Arguments = argsToken,
                            EntryPoint = entrypointToken?.Value,
                            Environment = envToken,
                            Pre = preEntrypointToken?.Value,
                            InitCondition = preIfToken?.Value ?? "always()",
                            Post = postEntrypointToken?.Value,
                            CleanupCondition = postIfToken?.Value ?? "always()"
                        });
                    }
                }
                else if (string.Equals(usingToken.Value, "node12", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(mainToken?.Value))
                    {
                        throw new ArgumentNullException($"You are using a JavaScript Action but there is not an entry JavaScript file provided in {fileRelativePath}.");
                    }
                    else
                    {
                        return(new NodeJSActionExecutionData()
                        {
                            Script = mainToken.Value,
                            Pre = preToken?.Value,
                            InitCondition = preIfToken?.Value ?? "always()",
                            Post = postToken?.Value,
                            CleanupCondition = postIfToken?.Value ?? "always()"
                        });
                    }
                }
                else if (string.Equals(usingToken.Value, "composite", StringComparison.OrdinalIgnoreCase))
                {
                    if (steps == null)
                    {
                        throw new ArgumentNullException($"You are using a composite action but there are no steps provided in {fileRelativePath}.");
                    }
                    else
                    {
                        return(new CompositeActionExecutionData()
                        {
                            Steps = steps.Cast <Pipelines.ActionStep>().ToList(),
                            Outputs = outputs
                        });
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException($"'using: {usingToken.Value}' is not supported, use 'docker' or 'node12' instead.");
                }
            }
            else if (pluginToken != null)
            {
                return(new PluginActionExecutionData()
                {
                    Plugin = pluginToken.Value
                });
            }

            throw new NotSupportedException(nameof(ConvertRuns));
        }
Пример #4
0
 public virtual IToken NewToken(int ttype, string text)
 {
     TemplateToken t = new TemplateToken(ttype, text);
     t.StartIndex = startCharIndex;
     t.StopIndex = input.Index - 1;
     t.Line = startLine;
     t.CharPositionInLine = startCharPositionInLine;
     return t;
 }
Пример #5
0
 public TemplateTokenResult(TemplateToken token, char? start = null, char? end = null) {
     Token = token;
     Start = start;
     End = end;
 }
Пример #6
0
 private void ReplaceMatch( StringBuilder newContent, TemplateToken token, string newValue )
 {
     newContent.Remove( token.StartIndexInTemplate, token.Length );
     newContent.Insert( token.StartIndexInTemplate, newValue );
 }
Пример #7
0
 protected override string OnEvalExpression(ExpressionParser parser, TemplateToken templateToken, IParserContext context)
 {
     return(ReplaceEscapes(base.OnEvalExpression(parser, templateToken, context)));
 }
        public ParserNode HandleLevel_Identifier()
        {
            ParserNode ParserNode;

            switch (CurrentTokenType)
            {
            case "OperatorTemplateToken":
                String Operator = CurrentToken.Text;
                switch (Operator)
                {
                // Unary Operators
                case "+":
                case "-":
                    Tokens.MoveNext();
                    ParserNode = new ParserNodeUnaryOperation()
                    {
                        Parent   = HandleLevel_Identifier(),
                        Operator = Operator,
                    };
                    Tokens.MoveNext();
                    break;

                case "(":
                    Tokens.MoveNext();
                    ParserNode = HandleLevel_Expression();
                    Tokens.ExpectValueAndNext(")");
                    break;

                default:
                    throw (new Exception(String.Format("Invalid operator '{0}'('{1}')", CurrentTokenType, CurrentToken.Text)));
                }
                break;

            case "NumericLiteralTemplateToken":
                ParserNode = new ParserNodeNumericLiteral()
                {
                    Value = Int64.Parse(CurrentToken.Text),
                };
                Tokens.MoveNext();
                break;

            case "IdentifierTemplateToken":
                String Id = CurrentToken.Text;
                Tokens.MoveNext();

                // Constants.
                switch (Id)
                {
                case "true":
                    ParserNode = new ParserNodeConstant(Id);
                    break;

                case "false":
                    ParserNode = new ParserNodeConstant(Id);
                    break;

                case "none":
                    ParserNode = new ParserNodeConstant(Id);
                    break;

                default:
                    ParserNode = new ParserNodeIdentifier(Id);

                    while (true)
                    {
                        if (CurrentToken.Text == ".")
                        {
                            Tokens.MoveNext();
                            TemplateToken AcessToken = Tokens.ExpectTypeAndNext(typeof(IdentifierTemplateToken));
                            ParserNode = new ParserNodeAccess(ParserNode, new ParserNodeStringLiteral(AcessToken.Text));
                        }
                        else if (CurrentToken.Text == "[")
                        {
                            Tokens.MoveNext();
                            ParserNode AccessNode = HandleLevel_Expression();
                            Tokens.ExpectValueAndNext("]");
                            ParserNode = new ParserNodeAccess(ParserNode, AccessNode);
                        }
                        else
                        {
                            break;
                        }
                    }

                    break;
                }

                break;

            case "StringLiteralTemplateToken":
                ParserNode = new ParserNodeStringLiteral(((StringLiteralTemplateToken)CurrentToken).UnescapedText);
                Tokens.MoveNext();
                break;

            default:
                throw (new Exception(String.Format("Invalid Identifier '{0}'('{1}')", CurrentTokenType, CurrentToken.Text)));
            }

            return(ParserNode);
        }
Пример #9
0
        internal static JobContainer ConvertToJobContainer(
            TemplateContext context,
            TemplateToken value,
            bool allowExpressions = false)
        {
            var result = new JobContainer();

            if (allowExpressions && value.Traverse().Any(x => x is ExpressionToken))
            {
                return(result);
            }

            if (value is StringToken containerLiteral)
            {
                if (String.IsNullOrEmpty(containerLiteral.Value))
                {
                    return(null);
                }

                result.Image = containerLiteral.Value;
            }
            else
            {
                var containerMapping = value.AssertMapping($"{PipelineTemplateConstants.Container}");
                foreach (var containerPropertyPair in containerMapping)
                {
                    var propertyName = containerPropertyPair.Key.AssertString($"{PipelineTemplateConstants.Container} key");

                    switch (propertyName.Value)
                    {
                    case PipelineTemplateConstants.Image:
                        result.Image = containerPropertyPair.Value.AssertString($"{PipelineTemplateConstants.Container} {propertyName}").Value;
                        break;

                    case PipelineTemplateConstants.Env:
                        var env     = containerPropertyPair.Value.AssertMapping($"{PipelineTemplateConstants.Container} {propertyName}");
                        var envDict = new Dictionary <String, String>(env.Count);
                        foreach (var envPair in env)
                        {
                            var envKey   = envPair.Key.ToString();
                            var envValue = envPair.Value.AssertString($"{PipelineTemplateConstants.Container} {propertyName} {envPair.Key.ToString()}").Value;
                            envDict.Add(envKey, envValue);
                        }
                        result.Environment = envDict;
                        break;

                    case PipelineTemplateConstants.Options:
                        result.Options = containerPropertyPair.Value.AssertString($"{PipelineTemplateConstants.Container} {propertyName}").Value;
                        break;

                    case PipelineTemplateConstants.Ports:
                        var ports    = containerPropertyPair.Value.AssertSequence($"{PipelineTemplateConstants.Container} {propertyName}");
                        var portList = new List <String>(ports.Count);
                        foreach (var portItem in ports)
                        {
                            var portString = portItem.AssertString($"{PipelineTemplateConstants.Container} {propertyName} {portItem.ToString()}").Value;
                            portList.Add(portString);
                        }
                        result.Ports = portList;
                        break;

                    case PipelineTemplateConstants.Volumes:
                        var volumes    = containerPropertyPair.Value.AssertSequence($"{PipelineTemplateConstants.Container} {propertyName}");
                        var volumeList = new List <String>(volumes.Count);
                        foreach (var volumeItem in volumes)
                        {
                            var volumeString = volumeItem.AssertString($"{PipelineTemplateConstants.Container} {propertyName} {volumeItem.ToString()}").Value;
                            volumeList.Add(volumeString);
                        }
                        result.Volumes = volumeList;
                        break;

                    default:
                        propertyName.AssertUnexpectedValue($"{PipelineTemplateConstants.Container} key");
                        break;
                    }
                }
            }

            if (result.Image.StartsWith("docker://", StringComparison.Ordinal))
            {
                result.Image = result.Image.Substring("docker://".Length);
            }

            if (String.IsNullOrEmpty(result.Image))
            {
                context.Error(value, "Container image cannot be empty");
            }

            return(result);
        }
        private ActionExecutionData ConvertRuns(
            TemplateContext context,
            TemplateToken inputsToken)
        {
            var runsMapping         = inputsToken.AssertMapping("runs");
            var usingToken          = default(StringToken);
            var imageToken          = default(StringToken);
            var argsToken           = default(SequenceToken);
            var entrypointToken     = default(StringToken);
            var envToken            = default(MappingToken);
            var mainToken           = default(StringToken);
            var pluginToken         = default(StringToken);
            var postToken           = default(StringToken);
            var postEntrypointToken = default(StringToken);
            var postIfToken         = default(StringToken);

            foreach (var run in runsMapping)
            {
                var runsKey = run.Key.AssertString("runs key").Value;
                switch (runsKey)
                {
                case "using":
                    usingToken = run.Value.AssertString("using");
                    break;

                case "image":
                    imageToken = run.Value.AssertString("image");
                    break;

                case "args":
                    argsToken = run.Value.AssertSequence("args");
                    break;

                case "entrypoint":
                    entrypointToken = run.Value.AssertString("entrypoint");
                    break;

                case "env":
                    envToken = run.Value.AssertMapping("env");
                    break;

                case "main":
                    mainToken = run.Value.AssertString("main");
                    break;

                case "plugin":
                    pluginToken = run.Value.AssertString("plugin");
                    break;

                case "post":
                    postToken = run.Value.AssertString("post");
                    break;

                case "post-entrypoint":
                    postEntrypointToken = run.Value.AssertString("post-entrypoint");
                    break;

                case "post-if":
                    postIfToken = run.Value.AssertString("post-if");
                    break;

                default:
                    Trace.Info($"Ignore run property {runsKey}.");
                    break;
                }
            }

            if (usingToken != null)
            {
                if (string.Equals(usingToken.Value, "docker", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(imageToken?.Value))
                    {
                        throw new ArgumentNullException($"Image is not provided.");
                    }
                    else
                    {
                        return(new ContainerActionExecutionData()
                        {
                            Image = imageToken.Value,
                            Arguments = argsToken,
                            EntryPoint = entrypointToken?.Value,
                            Environment = envToken,
                            Cleanup = postEntrypointToken?.Value,
                            CleanupCondition = postIfToken?.Value
                        });
                    }
                }
                else if (string.Equals(usingToken.Value, "node12", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(mainToken?.Value))
                    {
                        throw new ArgumentNullException($"Entry javascript fils is not provided.");
                    }
                    else
                    {
                        return(new NodeJSActionExecutionData()
                        {
                            Script = mainToken.Value,
                            Cleanup = postToken?.Value,
                            CleanupCondition = postIfToken?.Value
                        });
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException($"'using: {usingToken.Value}' is not supported, use 'docker' or 'node12' instead.");
                }
            }
            else if (pluginToken != null)
            {
                return(new PluginActionExecutionData()
                {
                    Plugin = pluginToken.Value
                });
            }

            throw new NotSupportedException(nameof(ConvertRuns));
        }
Пример #11
0
        protected override CompiledTemplate OnEvalParseFile(ExpressionParser parser, TemplateParser templateParser, string fileName, TemplateToken token, IParserContext context, out Dictionary <string, IValueWithType> parameters)
        {
            TemplateParserContext parserContext = (TemplateParserContext)context;

            TemplateToken.ParameterizedExpression pExpr = token.ExtractParameters();

            parameters = new Dictionary <string, IValueWithType>(StringComparer.InvariantCultureIgnoreCase);

            foreach (KeyValuePair <string, string> var in pExpr.Parameters)
            {
                parameters[var.Key] = parser.Evaluate(var.Value, context, token.TokenPosition);
            }

            ICompiledTemplate subTemplate = parserContext.Template.CompileSubTemplate(parser.Evaluate <string>(pExpr.MainExpression, context, token.TokenPosition));

            //TODO : fix this. It should be possible to include templates with different syntax
            return(((ViciCompiledTemplate)subTemplate).CompiledTemplate);
        }
Пример #12
0
 protected override string OnEvalIncludeFile(ExpressionParser parser, string fileName, TemplateToken token, IParserContext context)
 {
     return(((TemplateParserContext)context).Template.ReadSubTemplate(fileName));
 }
Пример #13
0
        /// <summary>
        /// When empty, default to "success()".
        /// When a status function is not referenced, format as "success() &amp;&amp; &lt;CONDITION&gt;".
        /// </summary>
        private static String ConvertToIfCondition(
            TemplateContext context,
            TemplateToken token,
            Boolean isJob,
            Boolean isDefaultScope)
        {
            String condition;

            if (token is null)
            {
                condition = null;
            }
            else if (token is BasicExpressionToken expressionToken)
            {
                condition = expressionToken.Expression;
            }
            else
            {
                var stringToken = token.AssertString($"{(isJob ? "job" : "step")} {PipelineTemplateConstants.If}");
                condition = stringToken.Value;
            }

            if (String.IsNullOrWhiteSpace(condition))
            {
                return($"{PipelineTemplateConstants.Success}()");
            }

            var expressionParser = new ExpressionParser();
            var functions        = default(IFunctionInfo[]);
            var namedValues      = default(INamedValueInfo[]);

            if (isJob)
            {
                namedValues = s_jobIfNamedValues;
                // TODO: refactor into seperate functions
                // functions = PhaseCondition.FunctionInfo;
            }
            else
            {
                namedValues = isDefaultScope ? s_stepNamedValues : s_stepInTemplateNamedValues;
                functions   = s_stepConditionFunctions;
            }

            var node = default(ExpressionNode);

            try
            {
                node = expressionParser.CreateTree(condition, null, namedValues, functions) as ExpressionNode;
            }
            catch (Exception ex)
            {
                context.Error(token, ex);
                return(null);
            }

            if (node == null)
            {
                return($"{PipelineTemplateConstants.Success}()");
            }

            var hasStatusFunction = node.Traverse().Any(x =>
            {
                if (x is Function function)
                {
                    return(String.Equals(function.Name, PipelineTemplateConstants.Always, StringComparison.OrdinalIgnoreCase) ||
                           String.Equals(function.Name, PipelineTemplateConstants.Cancelled, StringComparison.OrdinalIgnoreCase) ||
                           String.Equals(function.Name, PipelineTemplateConstants.Failure, StringComparison.OrdinalIgnoreCase) ||
                           String.Equals(function.Name, PipelineTemplateConstants.Success, StringComparison.OrdinalIgnoreCase));
                }

                return(false);
            });

            return(hasStatusFunction ? condition : $"{PipelineTemplateConstants.Success}() && ({condition})");
        }
Пример #14
0
        private static ActionStep ConvertToStep(
            TemplateContext context,
            TemplateToken stepsItem)
        {
            var step            = stepsItem.AssertMapping($"{PipelineTemplateConstants.Steps} item");
            var continueOnError = default(ScalarToken);
            var env             = default(TemplateToken);
            var id             = default(StringToken);
            var ifCondition    = default(String);
            var ifToken        = default(ScalarToken);
            var name           = default(ScalarToken);
            var run            = default(ScalarToken);
            var scope          = default(StringToken);
            var timeoutMinutes = default(ScalarToken);
            var uses           = default(StringToken);
            var with           = default(TemplateToken);
            var workingDir     = default(ScalarToken);
            var path           = default(ScalarToken);
            var clean          = default(ScalarToken);
            var fetchDepth     = default(ScalarToken);
            var lfs            = default(ScalarToken);
            var submodules     = default(ScalarToken);
            var shell          = default(ScalarToken);

            foreach (var stepProperty in step)
            {
                var propertyName = stepProperty.Key.AssertString($"{PipelineTemplateConstants.Steps} item key");

                switch (propertyName.Value)
                {
                case PipelineTemplateConstants.Clean:
                    clean = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Clean}");
                    break;

                case PipelineTemplateConstants.ContinueOnError:
                    ConvertToStepContinueOnError(context, stepProperty.Value, allowExpressions: true);     // Validate early if possible
                    continueOnError = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} {PipelineTemplateConstants.ContinueOnError}");
                    break;

                case PipelineTemplateConstants.Env:
                    ConvertToStepEnvironment(context, stepProperty.Value, StringComparer.Ordinal, allowExpressions: true);     // Validate early if possible
                    env = stepProperty.Value;
                    break;

                case PipelineTemplateConstants.FetchDepth:
                    fetchDepth = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.FetchDepth}");
                    break;

                case PipelineTemplateConstants.Id:
                    id = stepProperty.Value.AssertString($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Id}");
                    if (!NameValidation.IsValid(id.Value, true))
                    {
                        context.Error(id, $"Step id {id.Value} is invalid. Ids must start with a letter or '_' and contain only alphanumeric characters, '-', or '_'");
                    }
                    break;

                case PipelineTemplateConstants.If:
                    ifToken = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.If}");
                    break;

                case PipelineTemplateConstants.Lfs:
                    lfs = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Lfs}");
                    break;

                case PipelineTemplateConstants.Name:
                    name = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Name}");
                    break;

                case PipelineTemplateConstants.Path:
                    path = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Path}");
                    break;

                case PipelineTemplateConstants.Run:
                    run = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Run}");
                    break;

                case PipelineTemplateConstants.Shell:
                    shell = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Shell}");
                    break;

                case PipelineTemplateConstants.Scope:
                    scope = stepProperty.Value.AssertString($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Scope}");
                    break;

                case PipelineTemplateConstants.Submodules:
                    submodules = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Submodules}");
                    break;

                case PipelineTemplateConstants.TimeoutMinutes:
                    ConvertToStepTimeout(context, stepProperty.Value, allowExpressions: true);     // Validate early if possible
                    timeoutMinutes = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.TimeoutMinutes}");
                    break;

                case PipelineTemplateConstants.Uses:
                    uses = stepProperty.Value.AssertString($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Uses}");
                    break;

                case PipelineTemplateConstants.With:
                    ConvertToStepInputs(context, stepProperty.Value, allowExpressions: true);     // Validate early if possible
                    with = stepProperty.Value;
                    break;

                case PipelineTemplateConstants.WorkingDirectory:
                    workingDir = stepProperty.Value.AssertScalar($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.WorkingDirectory}");
                    break;

                default:
                    propertyName.AssertUnexpectedValue($"{PipelineTemplateConstants.Steps} item key");     // throws
                    break;
                }
            }

            // Fixup the if-condition
            var isDefaultScope = String.IsNullOrEmpty(scope?.Value);

            ifCondition = ConvertToIfCondition(context, ifToken, false, isDefaultScope);

            if (run != null)
            {
                var result = new ActionStep
                {
                    ScopeName        = scope?.Value,
                    ContextName      = id?.Value,
                    ContinueOnError  = continueOnError,
                    DisplayNameToken = name,
                    Condition        = ifCondition,
                    TimeoutInMinutes = timeoutMinutes,
                    Environment      = env,
                    Reference        = new ScriptReference(),
                };

                var inputs = new MappingToken(null, null, null);
                inputs.Add(new StringToken(null, null, null, PipelineConstants.ScriptStepInputs.Script), run);

                if (workingDir != null)
                {
                    inputs.Add(new StringToken(null, null, null, PipelineConstants.ScriptStepInputs.WorkingDirectory), workingDir);
                }

                if (shell != null)
                {
                    inputs.Add(new StringToken(null, null, null, PipelineConstants.ScriptStepInputs.Shell), shell);
                }

                result.Inputs = inputs;

                return(result);
            }
            else
            {
                uses.AssertString($"{PipelineTemplateConstants.Steps} item {PipelineTemplateConstants.Uses}");
                var result = new ActionStep
                {
                    ScopeName        = scope?.Value,
                    ContextName      = id?.Value,
                    ContinueOnError  = continueOnError,
                    DisplayNameToken = name,
                    Condition        = ifCondition,
                    TimeoutInMinutes = timeoutMinutes,
                    Inputs           = with,
                    Environment      = env,
                };

                if (uses.Value.StartsWith("docker://", StringComparison.Ordinal))
                {
                    var image = uses.Value.Substring("docker://".Length);
                    result.Reference = new ContainerRegistryReference {
                        Image = image
                    };
                }
                else if (uses.Value.StartsWith("./") || uses.Value.StartsWith(".\\"))
                {
                    result.Reference = new RepositoryPathReference
                    {
                        RepositoryType = PipelineConstants.SelfAlias,
                        Path           = uses.Value
                    };
                }
                else
                {
                    var usesSegments = uses.Value.Split('@');
                    var pathSegments = usesSegments[0].Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
                    var gitRef       = usesSegments.Length == 2 ? usesSegments[1] : String.Empty;

                    if (usesSegments.Length != 2 ||
                        pathSegments.Length < 2 ||
                        String.IsNullOrEmpty(pathSegments[0]) ||
                        String.IsNullOrEmpty(pathSegments[1]) ||
                        String.IsNullOrEmpty(gitRef))
                    {
                        // todo: loc
                        context.Error(uses, $"Expected format {{org}}/{{repo}}[/path]@ref. Actual '{uses.Value}'");
                    }
                    else
                    {
                        var repositoryName = $"{pathSegments[0]}/{pathSegments[1]}";
                        var directoryPath  = pathSegments.Length > 2 ? String.Join("/", pathSegments.Skip(2)) : String.Empty;

                        result.Reference = new RepositoryPathReference
                        {
                            RepositoryType = RepositoryTypes.GitHub,
                            Name           = repositoryName,
                            Ref            = gitRef,
                            Path           = directoryPath,
                        };
                    }
                }

                return(result);
            }
        }
Пример #15
0
        internal static TemplateException InvalidCharacterInOptionName(string template, TemplateToken token, char character)
        {
            // Rewrite the token to point to the invalid character instead of the whole value.
            token = new TemplateToken(
                token.TokenKind,
                (token.TokenKind == TemplateToken.Kind.ShortName ? token.Position + 1 : token.Position + 2) + token.Value.IndexOf(character),
                token.Value, character.ToString(CultureInfo.InvariantCulture));

            return(TemplateExceptionFactory.Create(template, token,
                                                   $"Encountered invalid character '{character}' in option name.",
                                                   "Invalid character."));
        }
Пример #16
0
        internal static TemplateException LongOptionMustHaveMoreThanOneCharacter(string template, TemplateToken token)
        {
            // Rewrite the token to point to the option name instead of the whole option.
            token = new TemplateToken(token.TokenKind, token.Position + 2, token.Value, token.Value);

            return(TemplateExceptionFactory.Create(template, token,
                                                   "Long option names must consist of more than one character.",
                                                   "Invalid option name."));
        }
Пример #17
0
 internal static TemplateException MultipleShortOptionNamesNotAllowed(string template, TemplateToken token)
 {
     return(TemplateExceptionFactory.Create(template, token,
                                            "Multiple short option names are not supported.",
                                            "Too many short options."));
 }
Пример #18
0
 public TemplateTokenResult(TemplateToken token, char?start = null, char?end = null)
 {
     Token = token;
     Start = start;
     End   = end;
 }
Пример #19
0
        internal static TemplateException ShortOptionMustOnlyBeOneCharacter(string template, TemplateToken token)
        {
            // Rewrite the token to point to the option name instead of the whole option.
            token = new TemplateToken(token.TokenKind, token.Position + 1, token.Value, token.Value);

            return(TemplateExceptionFactory.Create(template, token,
                                                   "Short option names can not be longer than one character.",
                                                   "Invalid option name."));
        }
Пример #20
0
        public static TemplateToken TemplateToken(int? counter)
        {
            var rtValue = new TemplateToken();
            rtValue.Name = "Name" + counter.Extra();
            rtValue.TemplateType = new TemplateType();

            return rtValue;
        }
Пример #21
0
 internal static TemplateException UnterminatedValueName(string template, TemplateToken token)
 {
     return(TemplateExceptionFactory.Create(template, token,
                                            $"Encountered unterminated value name '{token.Value}'.",
                                            "Unterminated value name."));
 }
Пример #22
0
 internal static TemplateException ArgumentCannotContainOptions(string template, TemplateToken token)
 {
     return(TemplateExceptionFactory.Create(template, token,
                                            "Arguments can not contain options.",
                                            "Not permitted."));
 }
Пример #23
0
 internal static TemplateException MultipleValuesAreNotSupported(string template, TemplateToken token)
 {
     return(TemplateExceptionFactory.Create(template, token,
                                            "Multiple values are not supported.",
                                            "Too many values."));
 }
Пример #24
0
 public virtual IToken NewToken(int ttype)
 {
     TemplateToken t = new TemplateToken(input, ttype, startCharIndex, input.Index - 1);
     t.Line = startLine;
     t.CharPositionInLine = startCharPositionInLine;
     return t;
 }
Пример #25
0
 internal static TemplateException OptionsMustHaveName(string template, TemplateToken token)
 {
     return(TemplateExceptionFactory.Create(template, token,
                                            "Options without name are not allowed.",
                                            "Missing option name."));
 }
Пример #26
0
 public virtual IToken NewTokenFromPreviousChar(int ttype)
 {
     TemplateToken t = new TemplateToken(input, ttype, input.Index - 1, input.Index - 1);
     t.Line = input.Line;
     t.CharPositionInLine = input.CharPositionInLine - 1;
     return t;
 }
Пример #27
0
        /// <summary>
        /// Job request message sent to the runner
        /// </summary>
        /// <param name="environmentVariables">Hierarchy of environment variables to overlay, last wins.</param>
        public AgentJobRequestMessage(
            TaskOrchestrationPlanReference plan,
            TimelineReference timeline,
            Guid jobId,
            String jobDisplayName,
            String jobName,
            TemplateToken jobContainer,
            TemplateToken jobServiceContainers,
            IList <TemplateToken> environmentVariables,
            IDictionary <String, VariableValue> variables,
            IList <MaskHint> maskHints,
            JobResources jobResources,
            DictionaryContextData contextData,
            WorkspaceOptions workspaceOptions,
            IEnumerable <JobStep> steps,
            IEnumerable <ContextScope> scopes,
            IList <String> fileTable,
            TemplateToken jobOutputs,
            IList <TemplateToken> defaults)
        {
            this.MessageType          = JobRequestMessageTypes.PipelineAgentJobRequest;
            this.Plan                 = plan;
            this.JobId                = jobId;
            this.JobDisplayName       = jobDisplayName;
            this.JobName              = jobName;
            this.JobContainer         = jobContainer;
            this.JobServiceContainers = jobServiceContainers;
            this.Timeline             = timeline;
            this.Resources            = jobResources;
            this.Workspace            = workspaceOptions;
            this.JobOutputs           = jobOutputs;

            m_variables = new Dictionary <String, VariableValue>(variables, StringComparer.OrdinalIgnoreCase);
            m_maskHints = new List <MaskHint>(maskHints);
            m_steps     = new List <JobStep>(steps);

            if (scopes != null)
            {
                m_scopes = new List <ContextScope>(scopes);
            }

            if (environmentVariables?.Count > 0)
            {
                m_environmentVariables = new List <TemplateToken>(environmentVariables);
            }

            if (defaults?.Count > 0)
            {
                m_defaults = new List <TemplateToken>(defaults);
            }

            this.ContextData = new Dictionary <String, PipelineContextData>(StringComparer.OrdinalIgnoreCase);
            if (contextData?.Count > 0)
            {
                foreach (var pair in contextData)
                {
                    this.ContextData[pair.Key] = pair.Value;
                }
            }

            if (fileTable?.Count > 0)
            {
                m_fileTable = new List <String>(fileTable);
            }
        }