public void SetToken()

in Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Writers/YamlWriter.cs [114:183]


        public void SetToken(string yamlPath, object token, TokenType tokenType = TokenType.Other)
        {
            if (!IsValidPath(yamlPath))
            {
                throw new InvalidDataException($"'{yamlPath}' is not a valid '{nameof(yamlPath)}'");
            }
            if (token == null)
            {
                return;
            }

            var pathList = yamlPath.Split('.');
            var lastProperty = pathList.LastOrDefault();
            if (string.IsNullOrEmpty(lastProperty))
            {
                throw new InvalidOperationException($"Cannot set a token at '{yamlPath}' because the terminal property is null or empty");
            }

            YamlNode terminalToken;

            if (token is YamlNode yamlNode)
            {
                terminalToken = yamlNode;
            }
            else
            {
                switch (tokenType)
                {
                    case TokenType.List:
                        terminalToken = GetDeserializedToken<YamlSequenceNode>(token);
                        break;
                    case TokenType.KeyVal:
                    case TokenType.Object:
                        terminalToken = GetDeserializedToken<YamlMappingNode>(token);
                        break;
                    case TokenType.Other:
                        terminalToken = GetDeserializedToken<YamlScalarNode>(token);
                        break;
                    default:
                        throw new InvalidOperationException($"Failed to deserialize token because {nameof(tokenType)} is invalid");
                }
            }

            var currentNode = _rootNode;

            for (var i = 0; i < pathList.Length - 1; i++)
            {
                if (currentNode == null)
                {
                    throw new InvalidOperationException($"Cannot set a token at '{yamlPath}' because one of the nodes in the path is null");
                }

                var property = pathList[i];
                try
                {
                    currentNode = (YamlMappingNode)currentNode[property];
                }
                catch (KeyNotFoundException)
                {
                    currentNode.Children[property] = new YamlMappingNode();
                    currentNode = (YamlMappingNode)currentNode[property];
                }
                catch (InvalidCastException)
                {
                    throw new InvalidOperationException($"Cannot set a token at '{yamlPath}' because one of the nodes in the path cannot be converted to {nameof(YamlMappingNode)}");
                }
            }

            currentNode.Children[lastProperty] = terminalToken;
        }