void YamlDotNetYamlRead()
    {
        //textAsset
        string fileName=AssetDatabase.GetAssetPath(textAsset);
        // open
        var input = new StreamReader(fileName, Encoding.UTF8);
        var yaml = new YamlStream();
        yaml.Load(input);
        //var mapping = (YamlMappingNode)yaml.Documents[0].RootNode;
        Debug.Log("yaml.Documents.Count="+ yaml.Documents.Count);
        //foreach (YamlMappingNode item in (YamlMappingNode)yaml.Documents) {
        for(int i = 0; i < yaml.Documents.Count; i++){

            string str="";
            //str="(YamlMappingNode)yaml.Documents["+i+"].RootNode= ";
            str=str+(YamlMappingNode)yaml.Documents[i].RootNode+"\n";//Macの場合 optionキーを押しながら¥を押す
            Debug.Log(str);
            //for(int j = 0; j < yaml.Documents[i].AllNodes.Count(); j++){
                //string str1="";
                //str="(YamlMappingNode)yaml.Documents["+i+"].RootNode= ";
            //	str1=str1+(YamlDotNet.RepresentationModel.YamlNode)yaml.Documents[i].AllNodes[j]+"\n";//Macの場合 optionキーを押しながら¥を押す
            //}
            foreach (YamlDotNet.RepresentationModel.YamlNode yamlNode in yaml.Documents[i].AllNodes) {
                Debug.Log(yamlNode.ToString());
            }
            //foreach (var child in item) {
            //	Debug.Log(((YamlScalarNode)child.Key).Value + "\t" +
            //		((YamlScalarNode)child.Value).Value);
            //}

        }
        TextWriter textWriter = new StreamWriter(Application.dataPath + "/YamlDotNetForUnityYAML/Editor/YamlDotNetYamlReadAndSave_yaml.yaml");
        textWriter.WriteLine("%YAML 1.1");//無視される。
        textWriter.WriteLine("%TAG !u! tag:unity3d.com,2011:");//無視される。
        yaml.Save(textWriter);

        textWriter.Close();
        AssetDatabase.Refresh();
        //var Year = (YamlScalarNode)mapping.Children[new YamlScalarNode("Year")];
        //Debug.Log("Year "+ Year.Value);
        //var Description = (YamlScalarNode)mapping.Children[new YamlScalarNode("Description")];
        //Debug.Log("Desciption "+ Description.Value);
        //Debug.Log("Contents:");

        //var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("Contents")];
        //foreach (YamlMappingNode item in items) {
        //	foreach (var child in item) {
        //		Debug.Log(((YamlScalarNode)child.Key).Value + "\t" +
        //			((YamlScalarNode)child.Value).Value);
        //	}
        //}
    }
示例#2
0
        public override Task ExecuteAsync(OutputContext output, Application application, ServiceEntry service)
        {
            var yaml = service.Outputs.OfType <IYamlManifestOutput>().ToArray();

            if (yaml.Length == 0)
            {
                output.WriteDebugLine($"No yaml manifests found for service '{service.FriendlyName}'. Skipping.");
                return(Task.CompletedTask);
            }

            var outputFilePath = Path.Combine(OutputDirectory.FullName, $"{service.Service.Name}.yaml");

            output.WriteInfoLine($"Writing output to '{outputFilePath}'.");
            if (File.Exists(outputFilePath) && !Force)
            {
                throw new CommandException($"'{service.Service.Name}.yaml' already exists for project. use '--force' to overwrite.");
            }

            File.Delete(outputFilePath);

            using var stream = File.OpenWrite(outputFilePath);
            using var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: -1, leaveOpen: true);
            var yamlStream = new YamlStream(yaml.Select(y => y.Yaml));

            yamlStream.Save(writer, assignAnchors: false);

            return(Task.CompletedTask);
        }
示例#3
0
文件: Program.cs 项目: odalet/CsWin32
        private void Worker(CancellationToken cancellationToken)
        {
            Console.WriteLine("Enumerating documents to be parsed...");
            string[] paths = Directory.GetFiles(this.contentBasePath, "??-*-*.md", SearchOption.AllDirectories)
                             ////.Where(p => Path.GetFileNameWithoutExtension(p).Contains("lastinputinfo")).ToArray()
            ;

            Console.WriteLine("Parsing documents...");
            var timer       = Stopwatch.StartNew();
            var parsedNodes = from path in paths.AsParallel()
                              let result = this.ParseDocFile(path)
                                           where result is { }
            select(Path: path, result.Value.ApiName, result.Value.YamlNode);
            var results = new ConcurrentDictionary <YamlNode, YamlNode>();

            if (Debugger.IsAttached)
            {
                parsedNodes = parsedNodes.WithDegreeOfParallelism(1); // improve debuggability
            }

            parsedNodes
            .WithCancellation(cancellationToken)
            .ForAll(result => results.TryAdd(new YamlScalarNode(result.ApiName), result.YamlNode));
            Console.WriteLine("Parsed {2} documents in {0} ({1} per document)", timer.Elapsed, timer.Elapsed / paths.Length, paths.Length);

            Console.WriteLine("Writing results to \"{0}\"", this.outputPath);
            var yamlDocument = new YamlDocument(new YamlMappingNode(results));
            var yamlStream   = new YamlStream(yamlDocument);

            Directory.CreateDirectory(Path.GetDirectoryName(this.outputPath) !);
            using var yamlWriter = File.CreateText(this.outputPath);
            yamlWriter.WriteLine($"# This file was generated by the {Assembly.GetExecutingAssembly().GetName().Name} tool in this repo.");
            yamlStream.Save(yamlWriter);
        }
示例#4
0
        public virtual V Convert <V>(YamlNode node)
        {
            if (node.NodeType == YamlNodeType.Alias)
            {
                return(default(V));
            }

            var deserializer = new DeserializerBuilder().WithNamingConvention(new CamelCaseNamingConvention()).Build();

            if (node.NodeType == YamlNodeType.Scalar)
            {
                return(deserializer.Deserialize <V>(((YamlScalarNode)node).Value));
            }

            YamlDocument yamlDocument = new YamlDocument(node);
            YamlStream   yamlStream   = new YamlStream();

            yamlStream.Add(yamlDocument);
            using (MemoryStream stream = new MemoryStream())
            {
                StreamWriter writer = new StreamWriter(stream);
                yamlStream.Save(writer);
                writer.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                StreamReader reader = new StreamReader(stream);
                return(deserializer.Deserialize <V>(reader));
            }
        }
        static void Main(string[] args)
        {
            var yaml     = new YamlStream();
            var rootNode = new YamlMappingNode();

            for (int i = 0; i < 5; i++)
            {
                var random = new Random(i).Next(100, 2000).ToString();

                // repro with this line
                rootNode.Add(random, random);

                // NO repro with this line instead of the one above
                //rootNode.Add("key" + i, "value" + i);
            }
            yaml.Documents.Add(new YamlDocument(rootNode));
            var writer = new StringWriter();

            yaml.Save(writer);
            Console.WriteLine(writer.ToString().Replace("\r\n...\r\n", ""));

            //Output look like this
            // &1944107265 1479: 1479
            // &1075620271 572: 572
            // &1182217550 1565: 1565
            // &2008746139 657: 657
            // &1222564548 1650: 1650
        }
示例#6
0
        // TODO: Testable
        public void Update()
        {
            foreach (var file in opts.ManifestValuesFiles)
            {
                var ys = new YamlStream();

                var path = Path.Combine(opts.WorkDir, opts.ManifestRepoName, opts.ManifestRoot, file);
                using (var sr = new StreamReader(path))
                {
                    ys.Load(sr);
                    foreach (var doc in ys.Documents)
                    {
                        foreach (var nestedKey in opts.ManifestTagKeys)
                        {
                            var oldVal = YamlUtil.UpdateByNestedKey(
                                doc.RootNode,
                                nestedKey.Split("."),
                                oldVal => TagUpdater.TagReplacer(oldVal, opts.AppCurrCommit));
                            opts.AppPrevCommit = TagUpdater.ExtractTag(oldVal);
                        }
                    }
                }

                var tmpPath = Path.Combine(opts.WorkDir, Guid.NewGuid().ToString());
                using (var sw = new StreamWriter(tmpPath))
                {
                    ys.Save(sw, false);
                }

                var backupPath = Path.Combine(opts.WorkDir, Guid.NewGuid().ToString());
                File.Replace(tmpPath, path, backupPath);
            }
        }
示例#7
0
        private void WriteChangelogPart(ChangelogData data)
        {
            try
            {
                var fileName = Path.Combine(
                    _cfg.Value.ChangelogRepo !,
                    "Resources", "Changelog", "Parts", $"pr-{data.Number}.yml");

                _log.LogTrace("Writing changelog part {PartFileName}", fileName);

                var yamlStream = new YamlStream(new YamlDocument(new YamlMappingNode
                {
                    { "author", data.Author },
                    { "time", data.Time.ToString("O") },
                    {
                        "changes",
                        new YamlSequenceNode(
                            data.Changes.Select(c => new YamlMappingNode
                        {
                            { "type", c.Item1.ToString() },
                            { "message", c.Item2 },
                        }))
                    }
                }));

                using var writer = new StreamWriter(fileName);
                yamlStream.Save(writer);
            }
            catch (Exception e)
            {
                _log.LogError(e, "Exception while writing changelog to disk!");
            }
        }
示例#8
0
        public void TestHomeQuote()
        {
            EAMetaModel meta = new EAMetaModel().setupAPIPackage();
            EAFactory   api  = APIModels.APIModel.createHomeQuote(meta);

            YamlMappingNode map = new YamlMappingNode();

            //Test
            APIManager.reifyAPI(EARepository.Repository, api.clientElement, map);

            YamlDocument d = new YamlDocument(map);

            YamlStream stream = new YamlStream();

            stream.Documents.Add(d);

            StringWriter writer = new StringWriter();

            stream.Save(writer, false);

            string yaml = writer.ToString();

            FileManager fileManager = new FileManager(null);

            fileManager.initializeAPI(EARepository.currentPackage.Name);
            fileManager.setup(APIAddinClass.RAML_0_8);
            fileManager.exportAPI(EARepository.currentPackage.Name, APIAddinClass.RAML_0_8, yaml);
        }
示例#9
0
        /// <inheritdoc />
        public void SaveMap(MapId mapId, string yamlPath)
        {
            var context = new MapContext(_mapManager, _tileDefinitionManager, _serverEntityManager, _pauseManager);

            foreach (var grid in _mapManager.GetAllMapGrids(mapId))
            {
                context.RegisterGrid(grid);
            }

            var document = new YamlDocument(context.Serialize());

            var resPath = new ResourcePath(yamlPath).ToRootedPath();

            _resMan.UserData.CreateDir(resPath.Directory);

            using (var file = _resMan.UserData.Open(resPath, FileMode.Create))
            {
                using (var writer = new StreamWriter(file))
                {
                    var stream = new YamlStream();

                    stream.Add(document);
                    stream.Save(new YamlMappingFix(new Emitter(writer)), false);
                }
            }
        }
示例#10
0
 internal void Save()
 {
     using (TextWriter writer = File.CreateText(filePath))
     {
         yaml.Save(writer, false);
     }
 }
示例#11
0
        //         [InlineData(
        //             @"spec:
        //   template:
        //     spec:
        //       containers:
        //       - - image: 'host:port/owner/name:1234567890abcdef'
        //       - - image: 'host:port/owner/name:1234567890abcdef'",
        //             new string[] { "spec.template.spec.containers[*].[*].image" },
        //             "123abc",
        //             @"spec:
        //   template:
        //     spec:
        //       containers:
        //       - - image: 'host:port/owner/name:123abc'
        //       - - image: 'host:port/owner/name:123abc'
        // ...
        // ")] // Nested array is not supported
        public void UpdateByNestedKeyTest(string yaml, string[] nestedKeys, string newTag, string expected)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            var sr = new StringReader(yaml);
            var ys = new YamlStream();

            ys.Load(sr);

            foreach (var doc in ys.Documents)
            {
                foreach (var nestedKey in nestedKeys)
                {
                    var oldVal = YamlUtil.UpdateByNestedKey(
                        doc.RootNode,
                        nestedKey.Split("."),
                        oldVal =>
                        TagUpdater.TagReplacer(oldVal, newTag)
                        );
                }
            }
            ys.Save(sw, false);
            Assert.Equal(expected, sw.ToString());
        }
        public void SaveMain()
        {
            string root = "variables:";

            using (StringReader reader = new StringReader(root))
            {
                YamlStream stream = new YamlStream();
                stream.Load(reader);

                YamlMappingNode rootMappingNode = (YamlMappingNode)stream.Documents[0].RootNode;
                YamlMappingNode npcs            = new YamlMappingNode();

                foreach (Conversation conversation in quest.Conversations)
                {
                    Console.WriteLine(conversation.NPCID.ToString() + " " + conversation.NPCName);
                    npcs.Add(conversation.NPCID.ToString(), conversation.NPCName);
                }

                rootMappingNode.Add("npcs", npcs);

                using (TextWriter writer = File.CreateText(pathDirectory + @"\main.yml"))
                {
                    stream.Save(writer, false);
                }
            }
        }
        public void SaveProperties(List <Property> properties, string directory)
        {
            if (properties.Count == 0)
            {
                return;
            }

            string root = properties[0].ID + ": " + properties[0].Command;

            using (StringReader reader = new StringReader(root))
            {
                YamlStream stream = new YamlStream();
                stream.Load(reader);

                YamlMappingNode rootNode = (YamlMappingNode)stream.Documents[0].RootNode;

                for (int n = 1; n < properties.Count; n++)
                {
                    rootNode.Add(properties[n].ID, properties[n].Command);
                }

                using (TextWriter writer = File.CreateText(directory))
                {
                    stream.Save(writer, false);
                }
            }
        }
示例#14
0
        private void RoundtripTest(string yamlFileName)
        {
            var original = new YamlStream();

            original.Load(Yaml.ReaderFrom(yamlFileName));

            var buffer = new StringBuilder();

            original.Save(new StringWriter(buffer));

            var final = new YamlStream();

            final.Load(new StringReader(buffer.ToString()));

            var originalBuilder = new YamlDocumentStructureBuilder();

            original.Accept(originalBuilder);

            var finalBuilder = new YamlDocumentStructureBuilder();

            final.Accept(finalBuilder);

            Assert.Equal(originalBuilder.Events.Count, finalBuilder.Events.Count);

            for (var i = 0; i < originalBuilder.Events.Count; ++i)
            {
                var originalEvent = originalBuilder.Events[i];
                var finalEvent    = finalBuilder.Events[i];

                Assert.Equal(originalEvent.Type, finalEvent.Type);
                Assert.Equal(originalEvent.Value, finalEvent.Value);
            }
        }
示例#15
0
        //包括了文件名和后缀名
        public void Save(string filePath)
        {
            using (TextWriter writer = File.CreateText(filePath))
            {
                writer.WriteLine("%YAML 1.1");
                writer.WriteLine("%TAG !u! tag:unity3d.com,2011:");
                Yaml.Save(writer, false);
            }

            //去掉结尾...
            //每个yaml document的 开头 &149962 编号前面没有内容 !u!, 不是unity的格式 替换掉
            string content = File.ReadAllText(filePath);

            content = content.Replace("...", "");
            string pattern = @".*&.*";
            var    matches = Regex.Matches(content, pattern);

            for (int i = 0; i < matches.Count; i++)
            {
                string ori        = matches[i].Value;
                string toReplaced = InfoList[i].OriContent;
                content = content.Replace(ori, toReplaced);
            }
            File.WriteAllText(filePath, content);
            UnityEditor.AssetDatabase.Refresh();
            Debug.Log("======SAVE FINISH======");
        }
示例#16
0
        /// <inheritdoc />
        public void SaveMap(MapId mapId, string yamlPath)
        {
            Logger.InfoS("map", $"Saving map {mapId} to {yamlPath}");
            var context = new MapContext(_mapManager, _tileDefinitionManager, _serverEntityManager, _pauseManager, _componentManager, _prototypeManager);

            foreach (var grid in _mapManager.GetAllMapGrids(mapId))
            {
                context.RegisterGrid(grid);
            }

            var document = new YamlDocument(context.Serialize());

            var resPath = new ResourcePath(yamlPath).ToRootedPath();

            _resMan.UserData.CreateDir(resPath.Directory);

            using (var file = _resMan.UserData.Create(resPath))
            {
                using (var writer = new StreamWriter(file))
                {
                    var stream = new YamlStream();

                    stream.Add(document);
                    stream.Save(new YamlMappingFix(new Emitter(writer)), false);
                }
            }
            Logger.InfoS("map", "Save completed!");
        }
示例#17
0
        public void Save(string configurationFilePath)
        {
            if (configurationFilePath == null)
            {
                Log.Error("Configuration cannot be saved as configuration file path was not provided.");
                return;
            }
            if (!File.Exists(configurationFilePath))
            {
                Log.WarnFormat("{0} configuration file does not exists. Creating it.", configurationFilePath);
                Directory.CreateDirectory(Path.GetDirectoryName(configurationFilePath));
                File.Create(configurationFilePath).Close();
            }

            var parser  = new YamlStream();
            var mapping = new YamlMappingNode();

            foreach (Service service in services)
            {
                mapping.Add(new YamlScalarNode(service.Name), service.ToConfig());
            }

            parser.Add(new YamlDocument(mapping));
            var writer = new StreamWriter(configurationFilePath);

            parser.Save(writer);
            writer.Close();
            Log.Info("Services configuration updated.");
        }
示例#18
0
#pragma warning restore 649

        /// <inheritdoc />
        public void SaveBlueprint(GridId gridId, string yamlPath)
        {
            var grid = _mapManager.GetGrid(gridId);

            var context = new MapContext(_mapManager, _tileDefinitionManager, _serverEntityManager, _pauseManager, _componentFactory, _componentManager);

            context.RegisterGrid(grid);
            var root     = context.Serialize();
            var document = new YamlDocument(root);

            var resPath = new ResourcePath(yamlPath).ToRootedPath();

            _resMan.UserData.CreateDir(resPath.Directory);

            using (var file = _resMan.UserData.Open(resPath, FileMode.Create))
            {
                using (var writer = new StreamWriter(file))
                {
                    var stream = new YamlStream();

                    stream.Add(document);
                    stream.Save(new YamlMappingFix(new Emitter(writer)), false);
                }
            }
        }
        internal void GenerateNewConfig(Stream outputStream)
        {
            var outputWriter = new StreamWriter(outputStream);

            var rootNodeName = Data.ElementAt(0).Key;

            var docMapping = new YamlMappingNode();

            foreach (var item in Data.Skip(1))
            {
                docMapping.Add(item.Key.Replace((rootNodeName + ":"), string.Empty), (item.Value ?? EmptyValue));
                // TODO: If contains ":" then Mapping node etc
            }

            var yamlStream = new YamlStream(
                new YamlDocument(
                    new YamlMappingNode(
                        new YamlScalarNode(rootNodeName),
                        docMapping
                        )
                    )
                );

            yamlStream.Save(outputWriter);
            outputWriter.Flush();
        }
示例#20
0
        /// <inheritdoc />
        public void SaveBlueprint(GridId gridId, string yamlPath)
        {
            var grid = _mapManager.GetGrid(gridId);

            var context = new MapContext();

            context.RegisterGrid(grid);
            var root     = context.Serialize();
            var document = new YamlDocument(root);

            var resPath = new ResourcePath(yamlPath).ToRootedPath();

            _resMan.UserData.CreateDir(resPath.Directory);

            using (var file = _resMan.UserData.Open(resPath, FileMode.Create))
            {
                using (var writer = new StreamWriter(file))
                {
                    var stream = new YamlStream();

                    stream.Add(document);
                    stream.Save(writer, false);
                }
            }
        }
示例#21
0
        /// <inheritdoc />
        public void SaveMap(IMap map, string yamlPath)
        {
            var context = new MapContext();

            foreach (var grid in map.GetAllGrids())
            {
                context.RegisterGrid(grid);
            }

            var document = new YamlDocument(context.Serialize());

            var resPath = new ResourcePath(yamlPath).ToRootedPath();

            _resMan.UserData.CreateDir(resPath.Directory);

            using (var file = _resMan.UserData.Open(resPath, FileMode.Create))
            {
                using (var writer = new StreamWriter(file))
                {
                    var stream = new YamlStream();

                    stream.Add(document);
                    stream.Save(writer, false);
                }
            }
        }
示例#22
0
        /// <summary>
        /// Generates a .unitypackage file from this package
        /// </summary>
        /// <param name="root">Root directory name, usually starts with Assets/</param>
        public void GeneratePackage(string outputPath, string root = "")
        {
            var tmpPath = Path.Combine(Path.GetTempPath(), "packUnity" + _name);

            if (Directory.Exists(tmpPath))
            {
                Directory.Delete(tmpPath, true);
            }
            Directory.CreateDirectory(tmpPath);

            foreach (var file in _files)
            {
                /*
                 * For every file there exists a directory named file.guid in the tar archive that looks like:
                 *     + /asset -> actual asset data
                 *     + /asset.meta -> meta file
                 *     + /pathname -> actual path in the package
                 *
                 * There can be more files such as preview but are optional.
                 */

                string fdirpath = Path.Combine(tmpPath, file.Value.GetHash());
                Directory.CreateDirectory(fdirpath);

                File.Copy(file.Value.GetDiskPath(), Path.Combine(fdirpath, "asset"));                 // copy to asset file

                using (StreamWriter writer = new StreamWriter(Path.Combine(fdirpath, "pathname")))    // the pathname file
                {
                    var altName = file.Value.PackPath;
                    if (altName.StartsWith("."))
                    {
                        altName = altName.Replace("." + Path.DirectorySeparatorChar, "");
                    }

                    writer.Write(root + altName.Replace(Path.DirectorySeparatorChar + "", "/"));
                }

                if (file.Value.GetMeta() != null)
                {
                    using (StreamWriter writer = new StreamWriter(Path.Combine(fdirpath, "asset.meta")))                     // the meta file
                    {
                        var doc = new YamlDocument(file.Value.GetMeta());
                        var ys  = new YamlStream(doc);
                        ys.Save(writer);
                    }
                    var fi = new FileInfo(Path.Combine(fdirpath, "asset.meta"));
                    using (var fs = fi.Open(FileMode.Open))
                    {
                        fs.SetLength(fi.Length - 3 - Environment.NewLine.Length);
                    }
                }
            }

            Directory.CreateDirectory(outputPath);
            string unityPackage = Path.Combine(outputPath, _name) + ".unitypackage";

            CreateTarGZ(unityPackage, tmpPath);
            Directory.Delete(tmpPath, true);
        }
示例#23
0
        private void CreateYaml(string type)
        {
            string str            = _mapUpdateInfo.Guid.ToString();
            string initialContent = "\nkey: " + str + "\n";

            var sr     = new StringReader(initialContent);
            var stream = new YamlStream();

            stream.Load(sr);

            var rootMappingNode = (YamlMappingNode)stream.Documents[0].RootNode;

            rootMappingNode.Add("map_name", _mapUpdateInfo.MapName);

            if (type.ToLower() != "_cancel")
            {
                string dataKind = _mapUpdateInfo.MapName.Substring(0, 1);

                rootMappingNode.Add("data_kind", dataKind);
                rootMappingNode.Add("file_count", _dic_file.Count.ToString());

                var seq = new YamlSequenceNode();

                foreach (DictionaryEntry dic in _dic_file)
                {
                    var    props = new YamlMappingNode();
                    string name  = Path.GetFileName(dic.Key.ToString());
                    props.Add("name", name);
                    props.Add("size", dic.Value.ToString());
                    seq.Add(props);
                }
                rootMappingNode.Add("files", seq);
            }

            string zipPath  = Path.GetDirectoryName(_mapUpdateInfo.ZipPath);
            string yamlName = _mapUpdateInfo.FileName + type + ".yaml";
            string yamlPath = Path.Combine(zipPath, yamlName);

            try
            {
                using (TextWriter writer = File.CreateText(yamlPath))
                {
                    stream.Save(writer, false);
                }

                if (type.ToLower() != "_cancel")
                {
                    FileInfo file = new FileInfo(yamlPath);
                    _dic_file.Insert(0, yamlPath, file.Length);
                    //_dic_file.Add(yaml_path, file.Length);
                }
            }
            catch (Exception ex)
            {
            }
        }
示例#24
0
        public void Save(FileStream tempStream)
        {
            using var textWriter = new StreamWriter(tempStream);

            QuoteValues(_doc);

            var yamlStream = new YamlStream(_doc);

            yamlStream.Save(textWriter, assignAnchors: false);
        }
示例#25
0
        public string Save()
        {
            StringBuilder s = new StringBuilder();

            using (TextWriter tw = new StringWriter(s))
            {
                _yaml.Save(tw, false);
            }
            return(s.ToString());
        }
示例#26
0
        /// <summary>
        /// Writes the content of this YAML node to the specified writer.
        /// </summary>
        /// <param name="writer">The writer to output YAML to.</param>
        /// <param name="settings">The settings to use to generate YAML. If null, a default <see cref="SerializerSettings"/> will be used.</param>
        public void WriteTo(TextWriter writer, SerializerSettings settings)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }
            var preferredIndent = (settings ?? DefaultSettings).PreferredIndent;

            yamlStream.Save(writer, true, preferredIndent);
            writer.Flush();
        }
示例#27
0
        /// <summary>
        /// Writes a YAML node to a file.
        /// Any exceptions are caught, logged, and then ignored.
        /// </summary>
        /// <param name="rootNode">The YAML node to write.</param>
        /// <param name="rootPath">The path of the directory where the file should be written.</param>
        /// <param name="fileBaseName">The base name of the file. The correct YAML extension will be added.</param>
        internal static void WriteYamlFile(YamlNode rootNode, string rootPath, string fileBaseName)
        {
            var doc    = new YamlDocument(rootNode);
            var stream = new YamlStream(doc);

            var fileName = Path.Combine(rootPath, fileBaseName + YamlExtension);

            using (var text = new StreamWriter(File.Open(fileName, FileMode.Create)))
            {
                stream.Save(text, false);
            }
        }
示例#28
0
        public override async Task ExecuteAsync(OutputContext output, Application application, ServiceEntry service)
        {
            var yaml = service.Outputs.OfType <IYamlManifestOutput>().ToArray();

            if (yaml.Length == 0)
            {
                output.WriteDebugLine($"No yaml manifests found for service '{service.FriendlyName}'. Skipping.");
                return;
            }

            if (!await KubectlDetector.Instance.IsKubectlInstalled.Value)
            {
                throw new CommandException($"Cannot apply manifests for '{service.Service.Name}' because kubectl is not installed.");
            }

            if (!await KubectlDetector.Instance.IsKubectlConnectedToCluster.Value)
            {
                throw new CommandException($"Cannot apply manifests for '{service.Service.Name}' because kubectl is not connected to a cluster.");
            }

            using var tempFile = TempFile.Create();
            output.WriteDebugLine($"Writing output to '{tempFile.FilePath}'.");

            {
                using var stream = File.OpenWrite(tempFile.FilePath);
                using var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: -1, leaveOpen: true);
                var yamlStream = new YamlStream(yaml.Select(y => y.Yaml));
                yamlStream.Save(writer, assignAnchors: false);
            }

            // kubectl apply logic is implemented in the client in older versions of k8s. The capability
            // to get the same behavior in the server isn't present in every version that's relevant.
            //
            // https://kubernetes.io/docs/reference/using-api/api-concepts/#server-side-apply
            //
            output.WriteDebugLine("Running 'kubectl apply'.");
            output.WriteCommandLine("kubectl", $"apply -f \"{tempFile.FilePath}\"");
            var capture  = output.Capture();
            var exitCode = await Process.ExecuteAsync(
                $"kubectl",
                $"apply -f \"{tempFile.FilePath}\"",
                System.Environment.CurrentDirectory,
                stdOut : capture.StdOut,
                stdErr : capture.StdErr);

            output.WriteDebugLine($"Done running 'kubectl apply' exit code: {exitCode}");
            if (exitCode != 0)
            {
                throw new CommandException("'kubectl apply' failed.");
            }

            output.WriteInfoLine($"Deployed service '{service.FriendlyName}'.");
        }
        /// <summary>
        /// 导入项目的TagsAndLayers
        /// </summary>
        /// <param name="path">需要导入TagsAndLayers的项目路径</param>
        /// <param name="currentProjectTempPath">临时文件夹</param>
        /// <param name="projectName">需要导入项目名称</param>
        public override void Import(string path, string currentProjectTempPath, string projectName)
        {
            //需要导入的TagManager.asset的路径
            string settingsFilePath = path + "/ProjectSettings/TagManager.asset";

            StreamReader streamReader = new StreamReader(settingsFilePath, Encoding.UTF8);
            YamlStream   yaml         = new YamlStream();

            yaml.Load(streamReader);
            streamReader.Dispose();
            streamReader.Close();

            YamlNode         rootNode      = yaml.Documents[0].RootNode;
            YamlNode         firstNode     = rootNode["TagManager"];
            YamlSequenceNode tags          = (YamlSequenceNode)firstNode["tags"];
            YamlSequenceNode layers        = (YamlSequenceNode)firstNode["layers"];
            YamlSequenceNode sortingLayers = (YamlSequenceNode)firstNode["m_SortingLayers"];

            //当前项目的TagManager.asset的路径
            string myFilePath = ProjectImporterEditor.currentProjectPath + "/ProjectSettings/TagManager.asset";

            streamReader = new StreamReader(myFilePath, Encoding.UTF8);
            //记录头3行
            string[]   myHeadLines = { streamReader.ReadLine(), streamReader.ReadLine(), streamReader.ReadLine() };
            YamlStream myYaml      = new YamlStream();

            myYaml.Load(streamReader);
            streamReader.Dispose();
            streamReader.Close();

            YamlNode myRootNode  = myYaml.Documents[0].RootNode;
            YamlNode myFirstNode = myRootNode["TagManager"];
            //YamlSequenceNode myTags=(YamlSequenceNode)myFirstNode["tags"];
            YamlSequenceNode myLayers        = (YamlSequenceNode)myFirstNode["layers"];
            YamlSequenceNode mySortingLayers = (YamlSequenceNode)myFirstNode["m_SortingLayers"];

            ImportTags(tags);
            ImportSortingLayers(sortingLayers, mySortingLayers, projectName);
            ImportLayers(layers, myLayers, projectName);

            //保存修改到当前项目的TagManager.asset
            StreamWriter streamWriter = new StreamWriter(myFilePath);

            for (int i = 0; i < 3; i++)
            {
                streamWriter.WriteLine(myHeadLines[i]);
            }
            myYaml.Save(streamWriter, false);
            streamWriter.Dispose();
            streamWriter.Close();

            AssetDatabase.Refresh();
        }
示例#30
0
    public static string ValueToYamlString(IValue value)
    {
        var stream = new YamlStream(new YamlDocument(ValueToYaml(value)));

        // Generate yaml text
        //https://github.com/aaubry/YamlDotNet/blob/b3cf63744380a9ec031ef9cc2409c39e0c92c953/YamlDotNet/RepresentationModel/YamlStream.cs#L112
        using (var writer = new StringWriter())
        {
            stream.Save(writer);
            return(writer.ToString());
        }
    }
示例#31
0
        private void SaveYmalFile(string onSymbol, string offSymbol, int spacing)
        {
            var ymal = new YamlMappingNode();

            ymal.Children.Add("on-symbol", onSymbol);
            ymal.Children.Add("off-symbol", offSymbol);
            ymal.Children.Add("spaces", spacing.ToString());

            using (var writer = File.CreateText(CONFIG_PATH))
            {
                var stream = new YamlStream(new YamlDocument(ymal));
                stream.Save(writer, false);
            }
        }
        public static string Build(Asset source)
        {
            var nodes = GetNodes(source);

            var doc = new YamlDocument(nodes);
            var stream = new YamlStream(doc);

            String output = string.Empty;
            var sb = new StringBuilder();

            using (var writer = new StringWriter(sb))
            {
                stream.Save(writer, false);
                output = sb.ToString();
            }

            return output;
        }
示例#33
0
        public string Encrypt(string config)
        {
            var stream = new YamlStream();
            using (var reader = new StringReader(config))
            {
                stream.Load(reader);
            }

            var mapping = (YamlMappingNode)stream.Documents[0].RootNode;
            mapping.FindNodes("Password").ForEach(x => EncryptTaggedValue(_valueHandler, x));
            mapping.FindNodesToEncrypt().ForEach(x => EncryptTaggedValue(_valueHandler, x));

            var stringBuilder = new StringBuilder();
            using (var textWriter = new StringWriter(stringBuilder))
            {
                stream.Save(textWriter);
                return stringBuilder.ToString();
            }
        }
示例#34
0
        public string Decrypt(string config)
        {
            using (var reader = new StringReader(config))
            {
                var stream = new YamlStream();
                stream.Load(reader);
                var mapping = (YamlMappingNode)stream.Documents[0].RootNode;

                mapping.FindEncryptedNodes()
                    .ForEach(x => DecryptYamlValue(_valueHandler, x));

                var stringBuilder = new StringBuilder();
                using (var writer = new StringWriter(stringBuilder))
                {
                    stream.Save(writer);

                }
                return stringBuilder.ToString();
            }
        }
        protected virtual void ConfigureElasticsearch()
        {
            string configRoot = Path.Combine(_ElasticRoot, "Config");
            if (!Directory.Exists(configRoot))
            {
                Directory.CreateDirectory(configRoot);
            }
            string configFile = Path.Combine(configRoot,ELASTICSEARCH_CONFIG_FILE);

            using (var input = new StreamReader(_TemplateConfigFile))
            using (var output = new StreamWriter(configFile, false))
            {
                Trace.WriteLine("Loading Default Config");
                var config = new Dictionary<string, string>();
                // Load the stream
                var yamlInput = new YamlStream();
                yamlInput.Load(input);

                var rootOutputNode = new YamlMappingNode();
                var outputDoc = new YamlDocument(rootOutputNode);
                var yamlOutput = new YamlStream(outputDoc);

                if (yamlInput.Documents.Count > 0)
                {
                    var mapping = (YamlMappingNode)yamlInput.Documents[0].RootNode;
                    var reservedConfigs = new string[] { "path.data", "path.work", "path.logs", "path.plugins" };
                    foreach (var entry in mapping.Children.Where(m => !reservedConfigs.Contains(m.Key.ToString())))
                    {
                        rootOutputNode.Add(entry.Key, entry.Value);
                    }
                }

                Trace.WriteLine("Writing Critical Config values");
                //write important config values reglardless of what was provided in package

                rootOutputNode.Add(new YamlScalarNode("path.data"), new YamlScalarNode(_DataPath));
                rootOutputNode.Add(new YamlScalarNode("path.work"), new YamlScalarNode(_Settings.TempDirectory));
                rootOutputNode.Add(new YamlScalarNode("path.logs"), new YamlScalarNode(_Settings.LogDirectory));
                rootOutputNode.Add(new YamlScalarNode("path.plugin"), new YamlScalarNode(_PluginRoot));
                rootOutputNode.Add(new YamlScalarNode("node.name"), new YamlScalarNode(_Settings.NodeName));
                rootOutputNode.Add(new YamlScalarNode("cloud.azureruntime.bridge"), new YamlScalarNode(_BridgePipeName));

                yamlOutput.Save(output);
                Trace.TraceInformation("Saved elasticsearch config file {0}", configFile);

            }
        }
示例#36
0
		private void RoundtripTest(string yamlFileName)
		{
			var original = new YamlStream();
			original.Load(YamlFile(yamlFileName));

			var buffer = new StringBuilder();
			original.Save(new StringWriter(buffer));

			Dump.WriteLine(buffer);

			var final = new YamlStream();
			final.Load(new StringReader(buffer.ToString()));

			var originalBuilder = new YamlDocumentStructureBuilder();
			original.Accept(originalBuilder);

			var finalBuilder = new YamlDocumentStructureBuilder();
			final.Accept(finalBuilder);

			Dump.WriteLine("The original document produced {0} events.", originalBuilder.Events.Count);
			Dump.WriteLine("The final document produced {0} events.", finalBuilder.Events.Count);
			Assert.AreEqual(originalBuilder.Events.Count, finalBuilder.Events.Count);

			for (var i = 0; i < originalBuilder.Events.Count; ++i)
			{
				var originalEvent = originalBuilder.Events[i];
				var finalEvent = finalBuilder.Events[i];

				Assert.AreEqual(originalEvent.Type, finalEvent.Type);
				Assert.AreEqual(originalEvent.Value, finalEvent.Value);
			}
		}
示例#37
0
        public static bool MigrateAssetIfNeeded(AssetMigrationContext context, PackageLoadingAssetFile loadAsset)
        {
            var assetFullPath = loadAsset.FilePath.FullPath;

            // Determine if asset was Yaml or not
            var assetFileExtension = Path.GetExtension(assetFullPath);
            if (assetFileExtension == null)
                return false;

            assetFileExtension = assetFileExtension.ToLowerInvariant();

            var serializer = AssetSerializer.FindSerializer(assetFileExtension);
            if (!(serializer is AssetYamlSerializer))
                return false;

            // We've got a Yaml asset, let's get expected and serialized versions
            var serializedVersion = 0;
            int expectedVersion;
            Type assetType;

            // Read from Yaml file the asset version and its type (to get expected version)
            // Note: It tries to read as few as possible (SerializedVersion is expected to be right after Id, so it shouldn't try to read further than that)
            using (var assetStream = loadAsset.OpenStream())
            using (var streamReader = new StreamReader(assetStream))
            {
                var yamlEventReader = new EventReader(new Parser(streamReader));

                // Skip header
                yamlEventReader.Expect<StreamStart>();
                yamlEventReader.Expect<DocumentStart>();
                var mappingStart = yamlEventReader.Expect<MappingStart>();

                var yamlSerializerSettings = YamlSerializer.GetSerializerSettings();
                var tagTypeRegistry = yamlSerializerSettings.TagTypeRegistry;
                bool typeAliased;
                assetType = tagTypeRegistry.TypeFromTag(mappingStart.Tag, out typeAliased);

                expectedVersion = AssetRegistry.GetCurrentFormatVersion(assetType);

                Scalar assetKey;
                while ((assetKey = yamlEventReader.Allow<Scalar>()) != null)
                {
                    // Only allow Id before SerializedVersion
                    if (assetKey.Value == "Id")
                    {
                        yamlEventReader.Skip();
                        continue;
                    }
                    if (assetKey.Value == "SerializedVersion")
                    {
                        serializedVersion = Convert.ToInt32(yamlEventReader.Expect<Scalar>().Value, CultureInfo.InvariantCulture);
                        break;
                    }
                }
            }

            if (serializedVersion > expectedVersion)
            {
                // Try to open an asset newer than what we support (probably generated by a newer Paradox)
                throw new InvalidOperationException(string.Format("Asset of type {0} has been serialized with newer version {1}, but only version {2} is supported. Was this asset created with a newer version of Paradox?", assetType, serializedVersion, expectedVersion));
            }

            if (serializedVersion < expectedVersion)
            {
                // Perform asset upgrade
                context.Log.Verbose("{0} needs update, from version {1} to version {2}", Path.GetFullPath(assetFullPath), serializedVersion, expectedVersion);

                // transform the stream into string.
                string assetAsString;
                using (var assetStream = loadAsset.OpenStream())
                using (var assetStreamReader = new StreamReader(assetStream, Encoding.UTF8))
                {
                    assetAsString = assetStreamReader.ReadToEnd();
                }

                // Load the asset as a YamlNode object
                var input = new StringReader(assetAsString);
                var yamlStream = new YamlStream();
                yamlStream.Load(input);
                var yamlRootNode = (YamlMappingNode)yamlStream.Documents[0].RootNode;

                // Check if there is any asset updater
                var assetUpgraders = AssetRegistry.GetAssetUpgraders(assetType);
                if (assetUpgraders == null)
                {
                    throw new InvalidOperationException(string.Format("Asset of type {0} should be updated from version {1} to {2}, but no asset migration path was found", assetType, serializedVersion, expectedVersion));
                }

                // Instantiate asset updaters
                var currentVersion = serializedVersion;
                while (currentVersion != expectedVersion)
                {
                    int targetVersion;
                    // This will throw an exception if no upgrader is available for the given version, exiting the loop in case of error.
                    var upgrader = assetUpgraders.GetUpgrader(currentVersion, out targetVersion);
                    upgrader.Upgrade(context, currentVersion, targetVersion, yamlRootNode, loadAsset);
                    currentVersion = targetVersion;
                }

                // Make sure asset is updated to latest version
                YamlNode serializedVersionNode;
                var newSerializedVersion = 0;
                if (yamlRootNode.Children.TryGetValue(new YamlScalarNode("SerializedVersion"), out serializedVersionNode))
                {
                    newSerializedVersion = Convert.ToInt32(((YamlScalarNode)serializedVersionNode).Value);
                }

                if (newSerializedVersion != expectedVersion)
                {
                    throw new InvalidOperationException(string.Format("Asset of type {0} was migrated, but still its new version {1} doesn't match expected version {2}.", assetType, newSerializedVersion, expectedVersion));
                }

                context.Log.Info("{0} updated from version {1} to version {2}", Path.GetFullPath(assetFullPath), serializedVersion, expectedVersion);

                var preferredIndent = YamlSerializer.GetSerializerSettings().PreferredIndent;

                // Save asset back to disk
                using (var memoryStream = new MemoryStream())
                {
                    using (var streamWriter = new StreamWriter(memoryStream))
                    {
                        yamlStream.Save(streamWriter, true, preferredIndent);
                    }
                    loadAsset.AssetContent = memoryStream.ToArray();
                }

                return true;
            }

            return false;
        }
示例#38
0
        private void RoundtripTest(string yamlFileName)
        {
            YamlStream original = new YamlStream();
            original.Load(YamlFile(yamlFileName));

            StringBuilder buffer = new StringBuilder();
            original.Save(new StringWriter(buffer));

            Console.WriteLine(buffer.ToString());

            YamlStream final = new YamlStream();
            final.Load(new StringReader(buffer.ToString()));

            YamlDocumentStructureBuilder originalBuilder = new YamlDocumentStructureBuilder();
            original.Accept(originalBuilder);

            YamlDocumentStructureBuilder finalBuilder = new YamlDocumentStructureBuilder();
            final.Accept(finalBuilder);

            Console.WriteLine("The original document produced {0} events.", originalBuilder.Events.Count);
            Console.WriteLine("The final document produced {0} events.", finalBuilder.Events.Count);
            Assert.Equal(originalBuilder.Events.Count, finalBuilder.Events.Count);

            for (int i = 0; i < originalBuilder.Events.Count; ++i)
            {
                YamlNodeEvent originalEvent = originalBuilder.Events[i];
                YamlNodeEvent finalEvent = finalBuilder.Events[i];

                Assert.Equal(originalEvent.Type, finalEvent.Type);
                //Assert.Equal(originalEvent.Tag, finalEvent.Tag);
                //Assert.Equal(originalEvent.Anchor, finalEvent.Anchor);
                Assert.Equal(originalEvent.Value, finalEvent.Value);
            }
        }
        protected virtual void ConfigureCassandra()
        {
            string configRoot = Path.Combine(_CassandraRoot, "conf");
            if (!Directory.Exists(configRoot))
            {
                Directory.CreateDirectory(configRoot);
            }

            string configFile = Path.Combine(configRoot,CASSANDRA_CONFIG_FILE);

            using (var input = new StreamReader(_TemplateConfigFile))
            using (var output = new StreamWriter(configFile, false))
            {
                Trace.WriteLine("Loading Default Config");

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

                var rootOutputNode = new YamlMappingNode();
                var outputDoc = new YamlDocument(rootOutputNode);
                var yamlOutput = new YamlStream(outputDoc);

                if (yamlInput.Documents.Count > 0)
                {
                    var mapping = (YamlMappingNode)yamlInput.Documents[0].RootNode;
                    var reservedConfigs = new string[] { "data_file_directories" };
                    foreach (var entry in mapping.Children.Where(m => !reservedConfigs.Contains(m.Key.ToString())))
                    {
                        rootOutputNode.Add(entry.Key, entry.Value);
                    }
                }

                Trace.WriteLine("Writing Critical Config values");
                //write important config values reglardless of what was provided in package

                rootOutputNode.Add(new YamlScalarNode("data_file_directories"), new YamlSequenceNode(new YamlScalarNode(_DataPath)));

                //Write seeds
                //rootOutputNode.Add(new YamlScalarNode("cloud.azureruntime.bridge"), new YamlScalarNode(_BridgePipeName));

                yamlOutput.Save(output,false);

                //Not sure why this is happening but let us clean out chas in end of file.

                Trace.TraceInformation("Saved cassandra config file {0}", configFile);

            }
        }
        public override string ToString()
        {
            var nodes = Build();

            var doc = new YamlDocument(nodes);
            var stream = new YamlStream(doc);

            String output = string.Empty;
            var sb = new StringBuilder();

            using (var writer = new StringWriter(sb))
            {
                stream.Save(writer, false);
                output = sb.ToString();
            }

            return output;
        }