Exemplo n.º 1
0
        private static void FindNodes(YamlMappingNode container, string name, List<KeyValuePair<YamlMappingNode, YamlNode>> matches)
        {
            var key = new YamlScalarNode(name);
            YamlNode matchNode;

            if (container.Children.TryGetValue(key, out matchNode))
            {
                matches.Add(new KeyValuePair<YamlMappingNode, YamlNode>(container, new YamlScalarNode(name)));
            }

            var nodes = container.Children.Values.OfType<YamlMappingNode>();
            foreach (var node in nodes)
            {
                FindNodes(node, name, matches);
            }

            var sequenceNodes = container.Children.Values.OfType<YamlSequenceNode>();
            foreach (var sequenceNode in sequenceNodes)
            {
                foreach (var node in sequenceNode.Children.OfType<YamlMappingNode>())
                {
                    FindNodes(node, name, matches);
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Finds a child node by its name and enumerates its contents
        /// </summary>
        /// <param name="parent">Parent node</param>
        /// <param name="groupName">Name of the group to find</param>
        /// <returns>Returns a sequence of key-node pairs</returns>
        public IEnumerable<KeyValuePair<string, YamlNode>> EnumerateNamedNodesOf(YamlNode parent, string groupName)
        {
            Contract.Requires(parent != null);
            Contract.Requires(!String.IsNullOrWhiteSpace(groupName));
            Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, YamlNode>>>() != null);

            var mapping = parent as YamlMappingNode;
            if (mapping != null)
            {
                var groupNameNode = new YamlScalarNode(groupName);
                if (mapping.Children.ContainsKey(groupNameNode))
                {
                    var groupSeq = mapping.Children[groupNameNode] as YamlSequenceNode;

                    if (groupSeq != null)
                    {
                        foreach (var item in EnumerateNodesOf(groupSeq))
                        {
                            if (item is YamlScalarNode)
                            {
                                yield return new KeyValuePair<string, YamlNode>(((YamlScalarNode)item).Value, null);
                            }
                            else if (item is YamlMappingNode)
                            {
                                var mappingChild = (YamlMappingNode)item;
                                yield return new KeyValuePair<string, YamlNode>(
                                    GetScalarValue(mappingChild, "name"),
                                    mappingChild);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Gets a scalar value identified by its key
        /// </summary>
        /// <param name="parent">Parent node</param>
        /// <param name="key">Key of the value</param>
        /// <param name="errorMessage">Error message if the key does not exists</param>
        /// <returns>Returns the scalar value</returns>
        public string GetScalarValue(YamlNode parent, string key, string errorMessage = null)
        {
            Contract.Requires(parent != null);
            Contract.Requires(key != null);
            Contract.Ensures(Contract.Result<string>() != null);

            try
            {
                var mapping = (YamlMappingNode)parent;
                var pairs = EnumerateNodesOf(mapping);
                var keyNode = new YamlScalarNode(key);

                foreach (var pair in pairs)
                {
                    if (keyNode.Equals(pair.Key))
                    {
                        if (pair.Value is YamlScalarNode)
                        {
                            var v = ((YamlScalarNode) pair.Value).Value;
                            if (v != null)
                                return v;
                        }

                        throw new InvalidSpecificationException(errorMessage ?? String.Format("No value for key {0}", key));
                    }
                }

                throw new InvalidSpecificationException(String.Format("Parent has no child with key {0}", key));
            }
            catch (Exception ex)
            {
                throw new InvalidSpecificationException(errorMessage ?? ex.Message, ex);
            }
        }
        protected void EnterContext(YamlScalarNode scalar)
        {
            string value = IsNull(scalar)
                ? string.Empty
                : scalar.Value;

            EnterContext(value);
        }
        private void VisitYamlMappingNode(YamlScalarNode yamlNodeKey, YamlMappingNode yamlNodeValue)
        {
            EnterContext(yamlNodeKey.Value);

            VisitYamlMappingNode(yamlNodeValue);

            ExitContext();
        }
        protected override void Visit(YamlScalarNode scalar)
        {
            var key = ConfigurationPath.Combine(context.Reverse());

            string value = IsNull(scalar)
                ? string.Empty
                : scalar.Value;

            this.items.Add(new KeyValuePair<string, string>(key, value));
        }
        private void VisitYamlScalarNode(YamlScalarNode yamlNodeKey, YamlScalarNode yamlNodeValue)
        {
            EnterContext(yamlNodeKey.Value);
            var key = _currentPath;

            if (_data.ContainsKey(key)) {
                throw new FormatException(string.Format("FormatError_KeyIsDuplicated({0})", key));
            }
            _data[key] = yamlNodeValue.Value;
            ExitContext();
        }
 protected override void Visit(YamlScalarNode scalar)
 {
     switch (_mappingIndentation)
     {
         case 1:
             Model.Name = scalar.Value;
             break;
         case 2:
         {
             State parsed;
             _state = !Enum.TryParse(scalar.Value, out parsed) ? State.None : parsed;
         }
             break;
         case 3:
             switch (_state)
             {
                 case State.Commands:
                     _model.Commands.Add(new Command { Name = scalar.Value });
                     _current = _model.Commands[_model.Commands.Count - 1];
                     break;
                 case State.CommandDataTypes:
                     _model.CommandDataTypes.Add(new DataType { Name = scalar.Value });
                     _current = _model.CommandDataTypes[_model.CommandDataTypes.Count - 1];
                     break;
                 case State.Events:
                     _model.Events.Add(new Event { Name = scalar.Value });
                     _current = _model.Events[_model.Events.Count - 1];
                     break;
                 case State.EventDataTypes:
                     _model.EventDataTypes.Add(new DataType { Name = scalar.Value });
                     _current = _model.EventDataTypes[_model.EventDataTypes.Count - 1];
                     break;
                 case State.SharedDataTypes:
                     _model.SharedDataTypes.Add(new DataType { Name = scalar.Value });
                     _current = _model.SharedDataTypes[_model.SharedDataTypes.Count - 1];
                     break;
             }
             break;
         case 4:
             switch ((_scalarCount % 2))
             {
                 case 0:
                     _current.Properties.Add(new Property { Name = scalar.Value });
                     break;
                 case 1:
                     _current.Properties[_current.Properties.Count - 1].DataType = scalar.Value;
                     break;
             }
             _scalarCount++;
             break;
     }
 }
Exemplo n.º 9
0
        public static string getStartCommand(string stagingInfoFile)
        {
            string startCommand;

            using (var stream = new StreamReader(stagingInfoFile))
            {
                var yaml = new YamlStream();
                yaml.Load(stream);

                var startCommandScalar = new YamlScalarNode("start_command");
                var elements = ((YamlMappingNode)yaml.Documents[0].RootNode).Children;

                startCommand = elements[startCommandScalar].ToString();
            }

            return startCommand;
        }
Exemplo n.º 10
0
        public static string GetDetectedBuildpack(string stagingInfoFile)
        {
            string buildpack = string.Empty;
            if (File.Exists(stagingInfoFile))
            {
                using (var stream = new StreamReader(stagingInfoFile))
                {
                    var yaml = new YamlStream();
                    yaml.Load(stream);

                    var startCommandScalar = new YamlScalarNode("detected_buildpack");
                    var elements = ((YamlMappingNode)yaml.Documents[0].RootNode).Children;

                    buildpack = elements[startCommandScalar].ToString();
                }
            }
            return buildpack;
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            // Setup the input
            var input = new StringReader(Document);

            // Load the stream
            var yaml = new YamlStream();
            yaml.Load(input);

            // Examine the stream
            var mapping =
                (YamlMappingNode)yaml.Documents[0].RootNode;

            // Loop trough all child entries and print our keys
            string key = string.Empty;
            foreach (var entry in mapping.Children)
            {
                var myKey = ((YamlScalarNode)entry.Key).Value;
                Console.WriteLine("Key: {0}", myKey);
                if(myKey != "items")
                {
                    continue;
                }

                YamlScalarNode myYamlScalarNode = new YamlScalarNode(myKey);
                var tmpItem = mapping.Children[myYamlScalarNode];

                // The next line will throw:
                // An unhandled exception of type 'System.InvalidCastException' occurred in yamldotnet.exe
                // Additional information: Unable to cast object of type 'YamlDotNet.RepresentationModel.YamlMappingNode' to type 'YamlDotNet.RepresentationModel.YamlSequenceNode'.
                var items = (YamlSequenceNode)tmpItem;
                foreach (YamlMappingNode item in items)
                {
                    Console.WriteLine(
                        "{0}\t{1}",
                        item.Children[new YamlScalarNode("part_no")],
                        item.Children[new YamlScalarNode("descrip")]
                    );
                }
                Console.WriteLine("Press any key to exit.");
                System.Console.ReadKey();
            }
        }
Exemplo n.º 12
0
        private static void WriteHtmlForScalarNode(StringWriter htmlwriter, YamlScalarNode scalar)
        {
            var regex = new Regex(@"(.*)\[(.*?)\]");

            var match = regex.Match(scalar.ToString());
            string href = null;
            string caption = scalar.ToString();

            if (match.Success)
            {
                caption = match.Groups[1].ToString();
                href = match.Groups[2] + ".html";
            }

            if (href != null)
                htmlwriter.Write("<a href='{0}'>", href);

            htmlwriter.Write(caption);

            if (href != null)
                htmlwriter.Write("</a>");
        }
        private static bool IsNull(YamlScalarNode scalar)
        {
            if (string.IsNullOrEmpty(scalar.Value))
            {
                return true;
            }

            if (string.Equals(scalar.Tag, "tag:yaml.org,2002:null", StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (string.Equals(scalar.Value, "null", StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (string.Equals(scalar.Value, "~", StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            return false;
        }
Exemplo n.º 14
0
 protected override void Visit(YamlScalarNode scalar)
 {
     VisitNode(scalar);
 }
Exemplo n.º 15
0
        /// <summary>
        /// Gets an optional scalar value identified by its key
        /// </summary>
        /// <param name="parent">Parent node</param>
        /// <param name="key">Key of the value</param>
        /// <param name="defaultValue">Default value to be used if the key is not found in parent</param>
        /// <returns>Returns either the scalar value read from the parent node, or the default value.</returns>
        public string GetOptionalScalarValue(YamlNode parent, string key, string defaultValue)
        {
            Contract.Requires(parent != null);
            Contract.Requires(key != null);
            Contract.Ensures(Contract.Result<string>() != null || Contract.Result<string>() == defaultValue);

            var mapping = parent as YamlMappingNode;
            if (mapping != null)
            {
                var pairs = EnumerateNodesOf(mapping);
                var keyNode = new YamlScalarNode(key);

                foreach (var pair in pairs)
                {
                    if (keyNode.Equals(pair.Key) &&
                        pair.Value is YamlScalarNode)
                        return ((YamlScalarNode)pair.Value).Value;
                }
            }

            return defaultValue;
        }
 /// <summary>
 /// Called after this object finishes visiting a <see cref="YamlScalarNode"/>.
 /// </summary>
 /// <param name="scalar">
 /// The <see cref="YamlScalarNode"/> that has been visited.
 /// </param>
 protected virtual void Visited(YamlScalarNode scalar)
 {
     // Do nothing.
 }
Exemplo n.º 17
0
        private bool TryGetValueByYamlKeyAndType(YamlScalarNode yamlKey, Type type, out object result)
        {
            if (mappingNode.Children.ContainsKey(yamlKey))
            {
                var value = mappingNode.Children[yamlKey];
                if (YamlDoc.TryMapValue(value, out result))
                {
                    return true;
                }
            }

            return FailToGetValue(out result);
        }
Exemplo n.º 18
0
 public override void Visit(YamlScalarNode scalar)
 {
     VisitNodeAndFindDuplicates(scalar);
 }
Exemplo n.º 19
0
 protected override void Visit(YamlScalarNode scalar)
 {
     current.AppendChild(myDocument.CreateTextNode(scalar.Value));
 }
Exemplo n.º 20
0
        private static FractalNode ParseYamlFile(YamlStream yaml)
        {
            var node = new FractalNode();

            try
            {
                var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;

                //the mapping is index with yamlscalars and not strings
                //So we need to build a new yamlscalarnode for every named entry
                //Before checking them and adding them ot the node.

                var titleScalar = new YamlScalarNode("Title");
                if (mapping.Children.Keys.Contains(titleScalar))
                    node.Title = mapping.Children[titleScalar].ToString();

                var nameScalar = new YamlScalarNode("Name");
                if (mapping.Children.Keys.Contains(nameScalar))
                    node.Name = mapping.Children[nameScalar].ToString();

                var textScalar = new YamlScalarNode("Text");
                if (mapping.Children.Keys.Contains(textScalar))
                    node.Text = mapping.Children[textScalar].ToString();

                var sideTitleScalar = new YamlScalarNode("SidebarTitle");
                if (mapping.Children.Keys.Contains(sideTitleScalar))
                    node.SidebarTitle = mapping.Children[sideTitleScalar].ToString();

                var sideTextScalar = new YamlScalarNode("SidebarText");
                if (mapping.Children.Keys.Contains(sideTextScalar))
                    node.SidebarText = mapping.Children[sideTextScalar].ToString();

                var sideUrlScalar = new YamlScalarNode("SidebarURL");
                if (mapping.Children.Keys.Contains(sideUrlScalar))
                    node.SidebarUrl = mapping.Children[sideUrlScalar].ToString();

                //Check for a nodes node, if it exists iterate over all its children
                var nodesScalar = new YamlScalarNode("Nodes");
                if (mapping.Children.Keys.Contains(nodesScalar))
                {
                    var subnodes = (YamlSequenceNode) mapping.Children[nodesScalar];

                    foreach (YamlMappingNode subnode in subnodes)
                    {
                        var nodeWeighted = new FractalNodeWeighted();

                        //check for a type entry, and if it exists add it, Type is the one mandatory entry
                        var typeScalar = new YamlScalarNode("Type");
                        if(subnode.Children.Keys.Contains(typeScalar))
                        {
                            nodeWeighted.Type = subnode.Children[typeScalar].ToString();
                        }
                        else
                        {
                            break; //if there is no Type this entry isn't meaningful
                        }

                        //Parsing into an int can be tricky and users are likely to put in something that won't parse so we need more sanity checks here
                        var chanceScalar = new YamlScalarNode("PercentageChance");
                        if (subnode.Children.Keys.Contains(chanceScalar))
                        {
                            var amount = 1;

                            if (!int.TryParse(subnode.Children[chanceScalar].ToString(), out amount))
                            {
                                Console.WriteLine("Could not parse int from subnode: {0} defaulting to 1", subnode);
                            }

                            if( amount > 0 && amount <= 100)
                            {
                                nodeWeighted.PercentageChance = amount;
                            }
                            else
                            {
                                nodeWeighted.PercentageChance = 100;
                            }

                        }
                        else
                        {
                            nodeWeighted.PercentageChance = 100;
                        }

                        //need to do things a bit more complex because minimum may not exceed maximum
                        var maxScalar = new YamlScalarNode("MaxAmount");
                        if (subnode.Children.Keys.Contains(maxScalar))
                        {
                            var amount = 1;

                            if (!int.TryParse(subnode.Children[maxScalar].ToString(), out amount))
                            {
                                Console.WriteLine("Could not parse int from subnode: {0} defaulting to 1", subnode);
                            }

                            nodeWeighted.MaxAmount = amount;
                        }
                        else
                        {
                            nodeWeighted.MaxAmount = 1;
                        }

                        var minScalar = new YamlScalarNode("MinAmount");
                        if (subnode.Children.Keys.Contains(minScalar))
                        {
                            var amount = 1;

                            if (!int.TryParse(subnode.Children[minScalar].ToString(), out amount))
                            {
                                Console.WriteLine("Could not parse int from subnode: {0} defaulting to 1", subnode);
                            }

                            nodeWeighted.MinAmount = (amount > nodeWeighted.MaxAmount) ? nodeWeighted.MaxAmount : amount;
                        }
                        else
                        {
                            nodeWeighted.MinAmount = 1;
                        }

                        if(node.Nodes == null)
                        {
                            node.Nodes = new List<FractalNodeWeighted>();
                        }

                        node.Nodes.Add(nodeWeighted);
                    }
                }

                var choiceNodesScalar = new YamlScalarNode("ChoiceNodes");
                if(mapping.Children.Keys.Contains(choiceNodesScalar))
                {
                    var choiceNodes = (YamlSequenceNode) mapping.Children[choiceNodesScalar];
                    node.ChoiceNodes = new List<WeightedChoiceEntry>();

                    foreach (YamlSequenceNode choiceNode in choiceNodes)
                    {
                        var entry = new WeightedChoiceEntry {WeightedStrings = new Dictionary<string, int>()};

                        foreach (YamlSequenceNode subnode in choiceNode)
                        {
                            var subnodeData = subnode.Children;

                            var text = subnodeData[0].ToString();
                            var weight = 1;

                            if (!int.TryParse(subnodeData[1].ToString(), out weight))
                            {
                                Console.WriteLine("Could not parse int from subnode: {0} defaulting to 1", subnode);
                            }

                            entry.TotalWeight += weight;
                            entry.WeightedStrings.Add(text,weight);
                        }

                        node.ChoiceNodes.Add(entry);
                    }

                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error parsing: {0}", _curFileName);
                Console.WriteLine(e);
                return null;
            }

            return node;
        }
Exemplo n.º 21
0
        public override bool Equals(object other)
        {
            YamlScalarNode node = other as YamlScalarNode;

            return(((node != null) && base.Equals(node)) && SafeEquals(this.Value, node.Value));
        }
Exemplo n.º 22
0
			protected override void Visit(YamlScalarNode scalar)
			{
				VisitNode(scalar);
			}
Exemplo n.º 23
0
        private void LoadPackager(Suite suite , Product product, YamlNode node)
        {
            var mapping = node as YamlMappingNode;
            if (mapping != null)
            {
                var packagerKey = new YamlScalarNode("packager");
                if (mapping.Children.ContainsKey(packagerKey))
                {
                    var packagerNode = mapping.Children[packagerKey] as YamlMappingNode;
                    if (packagerNode != null)
                    {
                        string type = parser.GetScalarValue(packagerNode, "type", "Packager type is not defined");

                        var loader = parametersLoaders.FirstOrDefault(l => l.Supports(type));
                        IPackagerParameters param = null;
                        if (loader != null)
                        {

                            YamlNode paramNode;
                            if (packagerNode.Children.TryGetValue(new YamlScalarNode("param"), out paramNode))
                            {
                                param = loader.Load(suite, type, paramNode, parser) as IPackagerParameters;
                            }
                            else
                            {
                                param = loader.Load(suite, type, new YamlMappingNode(), parser) as IPackagerParameters;
                            }
                        }

                        product.Packager = new PackagerDefinition(type, param);
                    }
                }
            }
        }
Exemplo n.º 24
0
 public void Reload(YamlNode node)
 {
     yamlNode = node;
     mappingNode = yamlNode as YamlMappingNode;
     sequenceNode = yamlNode as YamlSequenceNode;
     scalarNode = yamlNode as YamlScalarNode;
     children = null;
 }
Exemplo n.º 25
0
        private bool TryGetValueByYamlKeyAndType(YamlScalarNode yamlKey, Type type, out object result)
        {
            if (mappingNode.Children.ContainsKey(yamlKey))
            {
                var value = mappingNode.Children[yamlKey];
                if (YamlDoc.TryMapValue(value, out result))
                {
                    return true;
                }
            }

            return IsNullableType(type) ? SuccessfullyGetValue(out result, new DynamicYaml((YamlNode)null)) : FailToGetValue(out result);
        }
Exemplo n.º 26
0
		protected override void Visit(YamlScalarNode scalar)
		{
			WriteIndent();
			Console.WriteLine("Visit(YamlScalarNode, {0}, {1}) - {2}", scalar.Anchor, scalar.Tag, scalar.Value);
			indent++;
		}
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="YamlDocument"/> class with a single scalar node.
 /// </summary>
 public YamlDocument(string rootNode)
 {
     RootNode = new YamlScalarNode(rootNode);
 }
Exemplo n.º 28
0
 /// <summary>
 /// Called after this object finishes visiting a <see cref="YamlScalarNode"/>.
 /// </summary>
 /// <param name="scalar">
 /// The <see cref="YamlScalarNode"/> that has been visited.
 /// </param>
 protected virtual void Visited(YamlScalarNode scalar)
 {
     // Do nothing.
 }
		public virtual void Visit(YamlScalarNode scalar)
		{
		}
Exemplo n.º 30
0
        private bool TryGetValueByKeyAndType(string key, Type type, out object result)
        {
            if (mappingNode == null)
            {
                return FailToGetValue(out result);
            }

            // try and get an exact match to the key first
            if (TryGetValueByYamlKeyAndType(key, type, out result))
            {
                return true;
            }

            // otherwise try and match the key with a different cased first character
            var yamlKey = new YamlScalarNode(key.InverseFirstCapital());
            if (TryGetValueByYamlKeyAndType(yamlKey, type, out result))
            {
                return true;
            }

            return IsNullableType(type) ? SuccessfullyGetValue(new DynamicYaml((YamlNode)null), out result) : FailToGetValue(out result);
        }
Exemplo n.º 31
0
 private bool TryGetValueByKeyAndType(string key,
     Type type,
     out object result)
 {
     if (mappingNode == null)
     {
         return FailToGetValue(out result);
     }
     var yamlKey = new YamlScalarNode(key.Decapitalize());
     var yamlKey2 = new YamlScalarNode(key.Capitalize());
     return TryGetValueByYamlKeyAndType(yamlKey, type, out result) ||
         TryGetValueByYamlKeyAndType(yamlKey2, type, out result);
 }
Exemplo n.º 32
0
 protected override void Visit(YamlScalarNode scalar)
 {
     // Do not assign anchors to scalars
 }
Exemplo n.º 33
0
		protected override void Visited(YamlScalarNode scalar)
		{
			indent--;
			WriteIndent();
			Console.WriteLine("Visited(YamlScalarNode)");
		}
Exemplo n.º 34
0
 void IYamlVisitor.Visit(YamlScalarNode scalar)
 {
     this.Visit(scalar);
     this.Visited(scalar);
 }
Exemplo n.º 35
0
 void IYamlVisitor.Visit(YamlScalarNode scalar)
 {
     Visit(scalar);
     Visited(scalar);
 }
Exemplo n.º 36
0
 protected virtual void Visited(YamlScalarNode scalar)
 {
 }
 void IYamlVisitor.Visit(YamlScalarNode scalar)
 {
     Visit(scalar);
     Visited(scalar);
 }
Exemplo n.º 38
0
        public override bool Equals(object obj)
        {
            YamlScalarNode yamlScalarNode = obj as YamlScalarNode;

            return(yamlScalarNode != null && Equals(yamlScalarNode) && YamlNode.SafeEquals(Value, yamlScalarNode.Value));
        }
Exemplo n.º 39
0
 public override void Visit(YamlScalarNode scalar)
 {
     VisitNodeAndFindDuplicates(scalar);
 }
Exemplo n.º 40
0
			protected override void Visit(YamlScalarNode scalar)
			{
				events.Add(new YamlNodeEvent(YamlNodeEventType.Scalar, scalar.Anchor, scalar.Tag, scalar.Value));
			}