Beispiel #1
0
        public void TestMetadataCommandFromCSProjectWithFilterInOption()
        {
            // Create default project
            var projectFile = Path.Combine(_projectFolder, "test.csproj");
            var sourceFile  = Path.Combine(_projectFolder, "test.cs");
            var filterFile  = Path.Combine(_projectFolder, "filter.yaml");

            File.Copy("Assets/test.csproj.sample.1", projectFile);
            File.Copy("Assets/test.cs.sample.1", sourceFile);
            File.Copy("Assets/filter.yaml.sample", filterFile);

            new MetadataCommand(new MetadataCommandOptions
            {
                OutputFolder = Path.Combine(Directory.GetCurrentDirectory(), _outputFolder),
                Projects     = new List <string> {
                    projectFile
                },
                FilterConfigFile = filterFile,
            }).Exec(null);

            Assert.True(File.Exists(Path.Combine(_outputFolder, ".manifest")));

            var file = Path.Combine(_outputFolder, "toc.yml");

            Assert.True(File.Exists(file));
            var tocViewModel = YamlUtility.Deserialize <TocViewModel>(file);

            Assert.Equal("Foo", tocViewModel[0].Uid);
            Assert.Equal("Foo", tocViewModel[0].Name);
            Assert.Equal("Foo.Bar", tocViewModel[0].Items[0].Uid);
            Assert.Equal("Bar", tocViewModel[0].Items[0].Name);

            file = Path.Combine(_outputFolder, "Foo.yml");
            Assert.True(File.Exists(file));
            var memberViewModel = YamlUtility.Deserialize <PageViewModel>(file);

            Assert.Equal("Foo", memberViewModel.Items[0].Uid);
            Assert.Equal("Foo", memberViewModel.Items[0].Id);
            Assert.Equal("Foo", memberViewModel.Items[0].Name);
            Assert.Equal("Foo", memberViewModel.Items[0].FullName);

            file = Path.Combine(_outputFolder, "Foo.Bar.yml");
            Assert.True(File.Exists(file));
            memberViewModel = YamlUtility.Deserialize <PageViewModel>(file);
            Assert.Equal("Foo.Bar", memberViewModel.Items[0].Uid);
            Assert.Equal("Bar", memberViewModel.Items[0].Id);
            Assert.Equal("Bar", memberViewModel.Items[0].Name);
            Assert.Equal("Foo.Bar", memberViewModel.Items[0].FullName);
            Assert.Single(memberViewModel.Items);
            Assert.NotNull(memberViewModel.References.Find(s => s.Uid.Equals("Foo")));
        }
Beispiel #2
0
        public void TestXrefResolver()
        {
            using (var listener = new TestListenerScope("TestXrefResolver"))
            {
                // arrange
                var schemaFile   = CreateFile("template/schemas/mref.test.schema.json", File.ReadAllText("TestData/schemas/mref.test.schema.json"), _templateFolder);
                var templateXref = CreateFile(
                    "template/partials/overview.tmpl", @"{{name}}:{{{summary}}}|{{#boolProperty}}{{intProperty}}{{/boolProperty}}|{{#monikers}}<span>{{.}}</span>{{/monikers}}",
                    _templateFolder);
                var            templateFile  = CreateFile("template/ManagedReference.html.tmpl", @"
{{#items}}
{{#children}}
<xref uid={{.}} template=""partials/overview.tmpl""/>
{{/children}}
{{/items}}
", _templateFolder);
                var            inputFileName = "inputs/CatLibrary.ICat.yml";
                var            inputFile     = CreateFile(inputFileName, File.ReadAllText("TestData/inputs/CatLibrary.ICat.yml"), _inputFolder);
                FileCollection files         = new FileCollection(_defaultFiles);
                files.Add(DocumentType.Article, new[] { inputFile }, _inputFolder);

                // act
                BuildDocument(files);

                // assert
                Assert.Single(listener.Items);
                listener.Items.Clear();

                var xrefspec = Path.Combine(_outputFolder, "xrefmap.yml");
                var xrefmap  = YamlUtility.Deserialize <XRefMap>(xrefspec);
                Assert.Equal(2, xrefmap.References.Count);
                Assert.Equal(8, xrefmap.References[0].Keys.Count);
                Assert.Equal(10, xrefmap.References[1].Keys.Count);

                Assert.Equal("ICat", xrefmap.References[0].Name);
                Assert.Equal("CatLibrary.ICat.CatLibrary.ICatExtension.Sleep(System.Int64)", xrefmap.References[0]["extensionMethods/0"]);
                var outputFileName = Path.ChangeExtension(inputFileName, ".html");
                Assert.Equal(outputFileName, xrefmap.References[0].Href);
                Assert.NotNull(xrefmap.References[0]["summary"]);

                var outputFilePath = Path.Combine(_outputFolder, outputFileName);
                Assert.True(File.Exists(outputFilePath));
                var outputFileContent = File.ReadAllLines(outputFilePath);
                Assert.Equal($@"
eat:<p>eat event of cat. Every cat must implement this event.
This method is within <a class=""xref"" href=""CatLibrary.ICat.html"">ICat</a></p>
|666|<span>net472</span><span>netstandard2_0</span>".Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None),
                             outputFileContent);
            }
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            var items = new List <TocItemViewModel>();

            foreach (var file in args)
            {
                var toc = YamlUtility.Deserialize <TocViewModel>(file);
                items.AddRange(toc);
            }
            var combined = new TocViewModel();

            combined.AddRange(items.OrderBy(item => item.Name));
            YamlUtility.Serialize(Console.Out, combined, "YamlMime:TableOfContent");
        }
        public void TestNotWorkInYamlDotNet39()
        {
            const string Text = "😄";
            var          sw   = new StringWriter();

            YamlUtility.Serialize(sw, new BasicClass {
                C = Text
            });
            var yaml  = sw.ToString();
            var value = YamlUtility.Deserialize <BasicClass>(new StringReader(yaml));

            Assert.NotNull(value);
            Assert.Equal(Text, value.C);
        }
        public void ProcessMrefWithMergeOverwriteProcessorShouldSucceed()
        {
            var files = new FileCollection(Directory.GetCurrentDirectory());

            files.Add(DocumentType.Article, new[] { "TestData/mref/CatLibrary.Cat-2.yml" }, "TestData/");
            files.Add(DocumentType.Overwrite, new[]
            {
                "TestData/overwrite/mref.overwrite.default.md",
                "TestData/overwrite/mref.overwrite.simple.md",
            });

            var outputDir = GetRandomFolder();

            var parameters = new DocumentBuildParameters
            {
                Files                 = files,
                OutputBaseDir         = outputDir,
                MarkdownEngineName    = "momd",
                ApplyTemplateSettings = new ApplyTemplateSettings("", outputDir),
            };

            var assemblies = new[]
            {
                typeof(ManagedReferenceDocumentProcessor).Assembly,
                typeof(MergeMrefOverwriteDocumentProcessor).Assembly,
            };

            using (var builder = new DocumentBuilder(assemblies, ImmutableArray <string> .Empty, null))
            {
                builder.Build(parameters);
            }

            var yaml = YamlUtility.Deserialize <PageViewModel>(Path.Combine(outputDir, "mref/CatLibrary.Cat-2.yml"));

            Assert.Collection(
                yaml.Items.Where(item => item.Uid == "CatLibrary.Cat`2.#ctor"),
                e =>
            {
                Assert.Equal("Overwrite *markdown* summary\n\n", e.Summary);
                Assert.Equal("Overwrite *markdown* content\n\n", e.Conceptual);
            });

            Assert.Collection(
                yaml.Items.Where(item => item.Uid == "CatLibrary.Cat`2"),
                e =>
            {
                Assert.Equal("Overwrite <b>html</b> content\n\n", e.Summary);
                Assert.Equal("original conceptual", e.Conceptual);
            });
        }
Beispiel #6
0
 private async Task <IActionResult> Upload(string url)
 {
     using (var client = new WebClient())
     {
         using (var stream = await client.OpenReadTaskAsync(url))
         {
             using (var sr = new StreamReader(stream))
             {
                 var xm = YamlUtility.Deserialize <XRefMap>(sr);
                 return(await AddXrefs(xm?.References));
             }
         }
     }
 }
Beispiel #7
0
        private void CheckResult()
        {
            Assert.True(File.Exists(Path.Combine(_outputFolder, ".manifest")));

            var file = Path.Combine(_outputFolder, "toc.yml");

            Assert.True(File.Exists(file));
            var tocViewModel = YamlUtility.Deserialize <TocViewModel>(file);

            Assert.Equal("Foo", tocViewModel[0].Uid);
            Assert.Equal("Foo", tocViewModel[0].Name);
            Assert.Equal("Foo.Bar", tocViewModel[0].Items[0].Uid);
            Assert.Equal("Bar", tocViewModel[0].Items[0].Name);

            file = Path.Combine(_outputFolder, "Foo.yml");
            Assert.True(File.Exists(file));
            var memberViewModel = YamlUtility.Deserialize <PageViewModel>(file);

            Assert.Equal("Foo", memberViewModel.Items[0].Uid);
            Assert.Equal("Foo", memberViewModel.Items[0].Id);
            Assert.Equal("Foo", memberViewModel.Items[0].Name);
            Assert.Equal("Foo", memberViewModel.Items[0].FullName);

            file = Path.Combine(_outputFolder, "Foo.Bar.yml");
            Assert.True(File.Exists(file));
            memberViewModel = YamlUtility.Deserialize <PageViewModel>(file);
            Assert.Equal("Foo.Bar", memberViewModel.Items[0].Uid);
            Assert.Equal("Bar", memberViewModel.Items[0].Id);
            Assert.Equal("Bar", memberViewModel.Items[0].Name);
            Assert.Equal("Foo.Bar", memberViewModel.Items[0].FullName);
            Assert.Equal("Foo.Bar.FooBar``1(System.Int32[],System.Byte*,``0,System.Collections.Generic.List{``0[]})", memberViewModel.Items[1].Uid);
            Assert.Equal("FooBar``1(System.Int32[],System.Byte*,``0,System.Collections.Generic.List{``0[]})", memberViewModel.Items[1].Id);
            Assert.Equal("FooBar<TArg>(Int32[], Byte*, TArg, List<TArg[]>)", memberViewModel.Items[1].Name);
            Assert.Equal("Foo.Bar.FooBar<TArg>(System.Int32[], System.Byte*, TArg, System.Collections.Generic.List<TArg[]>)", memberViewModel.Items[1].FullName);
            Assert.NotNull(memberViewModel.References.Find(
                               s => s.Uid.Equals("System.Collections.Generic.List{System.String}")
                               ));
            Assert.NotNull(memberViewModel.References.Find(
                               s => s.Uid.Equals("System.Int32[]")
                               ));
            Assert.NotNull(memberViewModel.References.Find(
                               s => s.Uid.Equals("System.Byte*")
                               ));
            Assert.NotNull(memberViewModel.References.Find(
                               s => s.Uid.Equals("{TArg}")
                               ));
            Assert.NotNull(memberViewModel.References.Find(
                               s => s.Uid.Equals("System.Collections.Generic.List{{TArg}[]}")
                               ));
        }
Beispiel #8
0
        public void TestListOfClassWithExtensibleMembers()
        {
            var sw = new StringWriter();

            YamlUtility.Serialize(
                sw,
                (from i in Enumerable.Range(0, 10)
                 select new ClassWithExtensibleMembers
            {
                B = i,
                C = $"Good{i}!",
                StringExtensions =
                {
                    [$"a{i}"] = $"aaa{i}",
                    [$"b{i}"] = $"bbb{i}",
                },
                IntegerExtensions =
                {
                    [$"x{i}"] = i + 1,
                    [$"y{i}"] = i + 2,
                },
                ObjectExtensions =
                {
                    [$"foo{i}"] = new List <string> {
                        $"foo{i}"
                    },
                    [$"bar{i}"] = $"bar{i}",
                }
            }).ToList());
            var yaml   = sw.ToString();
            var values = YamlUtility.Deserialize <List <ClassWithExtensibleMembers> >(new StringReader(yaml));

            Assert.NotNull(values);
            Assert.Equal(10, values.Count);
            for (int i = 0; i < values.Count; i++)
            {
                Assert.Equal(i, values[i].B);
                Assert.Equal($"Good{i}!", values[i].C);
                Assert.Equal(2, values[i].StringExtensions.Count);
                Assert.Equal($"aaa{i}", values[i].StringExtensions[$"a{i}"]);
                Assert.Equal($"bbb{i}", values[i].StringExtensions[$"b{i}"]);
                Assert.Equal(2, values[i].IntegerExtensions.Count);
                Assert.Equal(i + 1, values[i].IntegerExtensions[$"x{i}"]);
                Assert.Equal(i + 2, values[i].IntegerExtensions[$"y{i}"]);
                Assert.Equal(2, values[i].ObjectExtensions.Count);
                Assert.Equal(new[] { $"foo{i}" }, (List <object>)values[i].ObjectExtensions[$"foo{i}"]);
                Assert.Equal($"bar{i}", (string)values[i].ObjectExtensions[$"bar{i}"]);
            }
        }
Beispiel #9
0
        private int SaveData(TextReader reader)
        {
            XRefMap xrefMap = YamlUtility.Deserialize <XRefMap>(reader);

            foreach (var spec in xrefMap.References)
            {
                XRefSpecObject xrefSpec = new XRefSpecObject();
                xrefSpec.Uid          = spec["uid"];
                xrefSpec.HashedUid    = MD5Encryption.CalculateMD5Hash(xrefSpec.Uid);
                xrefSpec.XRefSpecJson = JsonUtility.Serialize(spec);
                _db.XRefSpecObjects.Add(xrefSpec);
            }
            _db.SaveChanges();
            return(0);
        }
        public void ProcessMrefWithXRefMapShouldSucceed()
        {
            var files = new FileCollection(_defaultFiles);

            BuildDocument(files);

            var xrefMapPath = Path.Combine(Directory.GetCurrentDirectory(), _outputFolder, XRefArchive.MajorFileName);

            Assert.True(File.Exists(xrefMapPath));

            var xrefMap = YamlUtility.Deserialize <XRefMap>(xrefMapPath);

            Assert.NotNull(xrefMap.References);
            Assert.Equal(34, xrefMap.References.Count);
        }
Beispiel #11
0
 private static bool TryParseYamlMetadataFile(string metadataFileName, out MetadataItem projectMetadata)
 {
     projectMetadata = null;
     try
     {
         using StreamReader reader = new StreamReader(metadataFileName);
         projectMetadata           = YamlUtility.Deserialize <MetadataItem>(reader);
         return(true);
     }
     catch (Exception e)
     {
         Logger.LogInfo($"Error parsing yaml metadata file: {e.Message}");
         return(false);
     }
 }
Beispiel #12
0
        public void TestYamlUtility()
        {
            var helloWorld = new HelloWorld {
                Greeting = "Hello World!"
            };
            string helloWorldYaml = YamlUtility.Serialize(helloWorld);

            Assert.AreEqual("Hello World!", YamlUtility.Deserialize <HelloWorld>(helloWorldYaml).Greeting);
            var complexObject = new Pod
            {
                ApiVersion = "v1",
                Kind       = "Pod",
                Metadata   = new Metadata {
                    Annotations = new Dictionary <string, string> {
                        { "sidecar.istio.io/status", "{\"version\":\"887285bb7fa76191bf7f637f283183f0ba057323b078d44c3db45978346cbc1a\",\"initContainers\":[\"istio-init\"],\"containers\":[\"istio-proxy\"],\"volumes\":[\"istio-envoy\",\"istio-certs\"],\"imagePullSecrets\":null}" }
                    },
                    CreationTimestamp = DateTime.Now,
                    Labels            = new Dictionary <string, string> {
                        { "app", "fewbox" }, { "pod-template-hash", "76d889886b" }, { "version", "v1" }
                    },
                    Name            = "fewbox-76d889886b-9dtk",
                    Namespace       = "fewbox",
                    ResourceVersion = "32616085",
                    SelfLink        = "/api/v1/namespaces/fewbox/pods/fewbox-76d889886b-9dtk6",
                    Uid             = "49bb928f-d384-11e9-b929-fa163eab28fb"
                },
                Spec = new PodSpec
                {
                    Containers = new List <Container>
                    {
                        new Container
                        {
                            Image           = "111.111.111.111:5000/fewbox/fewbox:v1",
                            ImagePullPolicy = "IfNotPresent",
                            Name            = "fewbox",
                            Ports           = new List <Container_Port>
                            {
                                new Container_Port
                                {
                                    ContainerPort = 80
                                }
                            }
                        }
                    }
                }
            };
            string complexObjectYaml = YamlUtility.Serialize(complexObject);
        }
Beispiel #13
0
        static Dictionary <string, Dictionary <string, object> > LoadFile(string path)
        {
            var rval    = new Dictionary <string, Dictionary <string, object> >();
            var text    = File.ReadAllText(path);
            var matches = YamlHeaderRegex.Matches(text);

            if (matches != null && matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    using (StringReader reader = new StringReader(match.Groups[1].Value))
                    {
                        Dictionary <string, object> result = null;
                        try
                        {
                            result = YamlUtility.Deserialize <Dictionary <string, object> >(reader);
                        }
                        catch (Exception ex)
                        {
                            OPSLogger.LogUserError(LogCode.ECMA2Yaml_YamlHeader_ParseFailed_WithException, path, ex);
                        }
                        if (result == null)
                        {
                            OPSLogger.LogUserError(LogCode.ECMA2Yaml_YamlHeader_ParseFailed, path, match.Value);
                        }
                        else if (!result.ContainsKey("uid"))
                        {
                            OPSLogger.LogUserError(LogCode.ECMA2Yaml_YamlHeader_ParseFailed, path, match.Value);
                        }
                        else
                        {
                            var uid = result["uid"].ToString();
                            result.Remove("uid");
                            if (rval.ContainsKey(uid))
                            {
                                OPSLogger.LogUserWarning(LogCode.ECMA2Yaml_Uid_Duplicated, path, uid);
                            }
                            else
                            {
                                rval[uid] = result;
                            }
                        }
                    }
                }
            }

            return(rval);
        }
Beispiel #14
0
        public override FileModel Load(FileAndType file, ImmutableDictionary <string, object> metadata)
        {
            switch (file.Type)
            {
            case DocumentType.Article:
                var page = YamlUtility.Deserialize <PageViewModel>(Path.Combine(file.BaseDir, file.File));
                if (page.Items == null || page.Items.Count == 0)
                {
                    return(null);
                }
                if (page.Metadata == null)
                {
                    page.Metadata = metadata.ToDictionary(p => p.Key, p => p.Value);
                }
                else
                {
                    foreach (var item in metadata)
                    {
                        if (!page.Metadata.ContainsKey(item.Key))
                        {
                            page.Metadata[item.Key] = item.Value;
                        }
                    }
                }
                var filePath = Path.Combine(file.BaseDir, file.File);
                var repoInfo = GitUtility.GetGitDetail(filePath);
                // Item's source is the path for the original code, should not be used here
                var displayLocalPath = repoInfo?.RelativePath ?? filePath.ToDisplayPath();
                return(new FileModel(file, page, serializer: new BinaryFormatter())
                {
                    Uids = (from item in page.Items select new UidDefinition(item.Uid, displayLocalPath)).ToImmutableArray(),

                    Properties =
                    {
                        LinkToFiles = new HashSet <string>(),
                        LinkToUids  = new HashSet <string>(),
                    },
                    LocalPathFromRepoRoot = displayLocalPath,
                });

            case DocumentType.Overwrite:
                // TODO: Refactor current behavior that overwrite file is read multiple times by multiple processors
                return(OverwriteDocumentReader.Read(file));

            default:
                throw new NotSupportedException();
            }
        }
Beispiel #15
0
 private static ParseResult TryParseYamlMetadataFile(string metadataFileName, out MetadataItem projectMetadata)
 {
     projectMetadata = null;
     try
     {
         using (StreamReader reader = new StreamReader(metadataFileName))
         {
             projectMetadata = YamlUtility.Deserialize <MetadataItem>(reader);
             return(new ParseResult(ResultLevel.Success));
         }
     }
     catch (Exception e)
     {
         return(new ParseResult(ResultLevel.Error, e.Message));
     }
 }
Beispiel #16
0
        private void MergeToc(MetadataMergeParameters parameters)
        {
            var tocFiles =
                (from f in parameters.Files.EnumerateFiles()
                 where f.Type == DocumentType.Article && "toc.yml".Equals(Path.GetFileName(f.File), StringComparison.OrdinalIgnoreCase)
                 select f).ToList();
            var vm = MergeTocViewModel(
                from f in tocFiles
                select YamlUtility.Deserialize <TocViewModel>(f.File));

            CopyMetadataToToc(vm);
            YamlUtility.Serialize(
                ((RelativePath)tocFiles[0].DestinationDir + (((RelativePath)tocFiles[0].File) - (RelativePath)tocFiles[0].SourceDir)).ToString(),
                vm,
                YamlMime.TableOfContent);
        }
Beispiel #17
0
        protected static async Task <XRefMap> DownloadFromWebAsync(Uri uri)
        {
            var baseUrl = uri.GetLeftPart(UriPartial.Path);

            baseUrl = baseUrl.Substring(0, baseUrl.LastIndexOf('/') + 1);

            using (var wc = new WebClient())
                using (var stream = await wc.OpenReadTaskAsync(uri))
                    using (var sr = new StreamReader(stream))
                    {
                        var map = YamlUtility.Deserialize <XRefMap>(sr);
                        map.BaseUrl = baseUrl;
                        UpdateHref(map, null);
                        return(map);
                    }
        }
        public override FileModel Load(FileAndType file, ImmutableDictionary <string, object> metadata)
        {
            switch (file.Type)
            {
            case DocumentType.Article:
                var page = YamlUtility.Deserialize <PageViewModel>(Path.Combine(file.BaseDir, file.File));
                if (page.Items == null || page.Items.Count == 0)
                {
                    return(null);
                }
                if (page.Metadata == null)
                {
                    page.Metadata = metadata.ToDictionary(p => p.Key, p => p.Value);
                }
                else
                {
                    foreach (var item in metadata)
                    {
                        if (!page.Metadata.ContainsKey(item.Key))
                        {
                            page.Metadata[item.Key] = item.Value;
                        }
                    }
                }
                var filePath         = Path.Combine(file.BaseDir, file.File);
                var displayLocalPath = filePath.ToDisplayPath();

                object baseDirectory;
                if (metadata.TryGetValue("baseRepositoryDirectory", out baseDirectory))
                {
                    displayLocalPath = PathUtility.MakeRelativePath((string)baseDirectory, filePath);
                }

                return(new FileModel(file, page, serializer: new BinaryFormatter())
                {
                    Uids = (from item in page.Items select new UidDefinition(item.Uid, displayLocalPath)).ToImmutableArray(),
                    LocalPathFromRepoRoot = displayLocalPath,
                });

            case DocumentType.Overwrite:
                // TODO: Refactor current behavior that overwrite file is read multiple times by multiple processors
                return(OverwriteDocumentReader.Read(file));

            default:
                throw new NotSupportedException();
            }
        }
Beispiel #19
0
        protected static async Task <XRefMap> DownloadFromWebAsync(Uri uri)
        {
            var baseUrl = uri.GetLeftPart(UriPartial.Path);

            baseUrl = baseUrl.Substring(0, baseUrl.LastIndexOf('/') + 1);

            using var wc = new WebClient();
            ServicePointManager.CheckCertificateRevocationList = true;
            using var stream = await wc.OpenReadTaskAsync(uri);

            using var sr = new StreamReader(stream);
            var map = YamlUtility.Deserialize <XRefMap>(sr);

            map.BaseUrl = baseUrl;
            UpdateHref(map, null);
            return(map);
        }
Beispiel #20
0
        private static XRefSpec GetExternalReference(ExternalReferencePackageCollection externalReferences, string uid)
        {
            ReferenceViewModel vm;

            if (!externalReferences.TryGetReference(uid, out vm))
            {
                return(null);
            }
            using (var sw = new StringWriter())
            {
                YamlUtility.Serialize(sw, vm);
                using (var sr = new StringReader(sw.ToString()))
                {
                    return(YamlUtility.Deserialize <XRefSpec>(sr));
                }
            }
        }
Beispiel #21
0
        private static void MergeToc(MetadataMergeParameters parameters, string outputBase)
        {
            var tocFiles =
                (from f in parameters.Files.EnumerateFiles()
                 where f.Type == DocumentType.Article && "toc.yml".Equals(Path.GetFileName(f.File), StringComparison.OrdinalIgnoreCase)
                 select f).ToList();
            var vm = MergeTocViewModel(
                from f in tocFiles
                select YamlUtility.Deserialize <TocViewModel>(Path.Combine(f.BaseDir, f.File)));

            YamlUtility.Serialize(
                Path.Combine(
                    outputBase,
                    (TypeForwardedToRelativePath)tocFiles[0].DestinationDir + (((TypeForwardedToRelativePath)tocFiles[0].File) - (TypeForwardedToRelativePath)tocFiles[0].SourceDir)),
                vm,
                YamlMime.TableOfContent);
        }
Beispiel #22
0
        public static SearchItem ExtractIndexFromYml(string text)
        {
            var input = new StringReader(text);
            var item  = YamlUtility.Deserialize <PageViewModel>(input);

            if (item == null)
            {
                return(null);
            }
            var title   = string.Join(WordsJoinSpliter, SplitItemsWords(item.Items, t => t.Name));
            var keyword = string.Join(WordsJoinSpliter,
                                      SplitItemsWords(item.Items, t => t.FullName + " " + t.Summary + " " + t.Remarks));

            return(new SearchItem {
                Title = title, Keywords = keyword
            });
        }
Beispiel #23
0
        public override FileModel Load(FileAndType file, ImmutableDictionary <string, object> metadata)
        {
            switch (file.Type)
            {
            case DocumentType.Article:
                var page = YamlUtility.Deserialize <PageViewModel>(Path.Combine(file.BaseDir, file.File));
                if (page.Metadata == null)
                {
                    page.Metadata = metadata.ToDictionary(p => p.Key, p => p.Value);
                }
                else
                {
                    foreach (var item in metadata)
                    {
                        if (!page.Metadata.ContainsKey(item.Key))
                        {
                            page.Metadata[item.Key] = item.Value;
                        }
                    }
                }
                var result = new FileModel(file, page, serializer: new BinaryFormatter())
                {
                    Uids = (from item in page.Items select item.Uid).ToImmutableArray(),
                };
                result.Properties.LinkToFiles = new HashSet <string>();
                result.Properties.LinkToUids  = new HashSet <string>();
                return(result);

            case DocumentType.Override:
                var overrides = MarkdownReader.ReadMarkdownAsOverride(file.BaseDir, file.File);
                return(new FileModel(file, overrides, serializer: new BinaryFormatter())
                {
                    Uids = (from item in overrides
                            select item.Uid).ToImmutableArray(),
                    Properties =
                    {
                        LinkToFiles = new HashSet <string>(),
                        LinkToUids  = new HashSet <string>(),
                    }
                });

            default:
                throw new NotSupportedException();
            }
        }
Beispiel #24
0
 private void ValidateYaml(string ymlFile)
 {
     try
     {
         YamlUtility.Deserialize <Dictionary <string, object> >(ymlFile);
     }
     catch (Exception)
     {
         ConsoleLogger.WriteLine(
             new LogEntry
         {
             Phase   = StepName,
             Level   = LogLevel.Error,
             Message = $"Invalid yaml after add artifact.",
         });
         throw;
     }
 }
Beispiel #25
0
        public void TestBasicClass()
        {
            var sw = new StringWriter();

            YamlUtility.Serialize(sw, new BasicClass {
                B = 1, C = "Good!"
            });
            var yaml = sw.ToString();

            Assert.Equal(@"B: 1
C: Good!
".Replace("\r\n", "\n"), yaml.Replace("\r\n", "\n"));
            var value = YamlUtility.Deserialize <BasicClass>(new StringReader(yaml));

            Assert.NotNull(value);
            Assert.Equal(1, value.B);
            Assert.Equal("Good!", value.C);
        }
Beispiel #26
0
        private XRefMap DownloadFromAssembly(Uri uri)
        {
            var path  = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
            var index = path.IndexOf('/');

            if (index == -1)
            {
                throw new ArgumentException($"Invalid uri {uri.OriginalString}, expect: {uri.Scheme}:{{assemblyName}}/{{resourceName}}", nameof(uri));
            }
            var assemblyName = path.Remove(index);
            var resourceName = assemblyName + "." + path.Substring(index + 1);

            var assembly = AppDomain.CurrentDomain.Load(assemblyName);

            using var stream = assembly.GetManifestResourceStream(resourceName);
            using var sr     = new StreamReader(stream);
            return(YamlUtility.Deserialize <XRefMap>(sr));
        }
Beispiel #27
0
        private static void TraversePathCore(string prefix, string curPath, string tocName, ICollection <SearchItem> searchItemList)
        {
            var tocFilePath = Path.Combine(curPath, tocName);

            if (!File.Exists(tocFilePath))
            {
                var msg = $"{tocFilePath} not found";
                Logger.Log(LogLevel.Info, msg);
                return;
            }

            var items = YamlUtility.Deserialize <TocViewModel>(tocFilePath);

            foreach (var item in items)
            {
                AddItem(item, prefix, curPath, tocName, searchItemList);
            }
        }
        public override FileModel Load(FileAndType file, ImmutableDictionary <string, object> metadata)
        {
            switch (file.Type)
            {
            case DocumentType.Article:
                // TODO: Support dynamic in YAML deserializer
                try
                {
                    // MUST be a dictionary
                    var obj = YamlUtility.Deserialize <Dictionary <string, object> >(file.File);
                    foreach (var pair in metadata)
                    {
                        if (!obj.ContainsKey(pair.Key))
                        {
                            obj[pair.Key] = pair.Value;
                        }
                    }
                    var content = ConvertToObjectHelper.ConvertToDynamic(obj);

                    var localPathFromRoot = PathUtility.MakeRelativePath(EnvironmentContext.BaseDirectory, EnvironmentContext.FileAbstractLayer.GetPhysicalPath(file.File));

                    var fm = new FileModel(
                        file,
                        content,
                        serializer: new BinaryFormatter())
                    {
                        LocalPathFromRoot = localPathFromRoot,
                    };

                    fm.Properties.Schema = _schema;
                    return(fm);
                }
                catch (YamlDotNet.Core.YamlException e)
                {
                    throw new DocumentException($"{file.File} is not in supported format: {e.Message}", e);
                }

            case DocumentType.Overwrite:
                return(OverwriteDocumentReader.Read(file));

            default:
                throw new NotSupportedException();
            }
        }
Beispiel #29
0
        public static MarkdownFragment ToMarkdownFragment(this MarkdownFragmentModel model, string originalContent = null)
        {
            Dictionary <string, object> metadata = null;

            if (!string.IsNullOrEmpty(model.YamlCodeBlock))
            {
                using (TextReader sr = new StringReader(model.YamlCodeBlock))
                {
                    metadata = YamlUtility.Deserialize <Dictionary <string, object> >(sr);
                }
            }

            return(new MarkdownFragment()
            {
                Uid = model.Uid,
                Metadata = metadata,
                Properties = model.Contents?.Select(prop => prop.ToMarkdownProperty(originalContent)).ToDictionary(p => p.OPath, p => p)
            });
        }
Beispiel #30
0
        private static IEnumerable <T> ReadMarkDownCore <T>(string file) where T : IOverrideDocumentViewModel
        {
            var content     = File.ReadAllText(file);
            var repoInfo    = GitUtility.GetGitDetail(file);
            var lineIndex   = GetLineIndex(content).ToList();
            var yamlDetails = YamlHeaderParser.Select(content);

            if (yamlDetails == null)
            {
                yield break;
            }
            var sections = from detail in yamlDetails
                           let id = detail.Id
                                    from ms in detail.MatchedSections
                                    from location in ms.Value.Locations
                                    orderby location.StartLocation descending
                                    select new { Detail = detail, Id = id, Location = location };
            var currentEnd = Coordinate.GetCoordinate(content);

            foreach (var item in sections)
            {
                if (!string.IsNullOrEmpty(item.Id))
                {
                    int start = lineIndex[item.Location.EndLocation.Line] + item.Location.EndLocation.Column + 1;
                    int end   = lineIndex[currentEnd.Line] + currentEnd.Column + 1;
                    using (var sw = new StringWriter())
                    {
                        YamlUtility.Serialize(sw, item.Detail.Properties);
                        using (var sr = new StringReader(sw.ToString()))
                        {
                            var vm = YamlUtility.Deserialize <T>(sr);
                            vm.Conceptual    = content.Substring(start, end - start + 1);
                            vm.Documentation = new SourceDetail {
                                Remote = repoInfo, StartLine = item.Location.EndLocation.Line, EndLine = currentEnd.Line
                            };
                            vm.Uid = item.Id;
                            yield return(vm);
                        }
                    }
                }
                currentEnd = item.Location.StartLocation;
            }
        }