|
| 1 | +// Licensed to Elasticsearch B.V under one or more agreements. |
| 2 | +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. |
| 3 | +// See the LICENSE file in the project root for more information |
| 4 | + |
| 5 | +using System.IO.Abstractions; |
| 6 | +using System.Xml.Linq; |
| 7 | +using Elastic.Markdown.IO.Navigation; |
| 8 | + |
| 9 | +namespace Documentation.Assembler.Building; |
| 10 | + |
| 11 | +public class SitemapBuilder(IReadOnlyCollection<INavigationItem> navigationItems, IFileSystem fileSystem, IDirectoryInfo outputFolder) |
| 12 | +{ |
| 13 | + private static readonly Uri BaseUri = new("https://www.elastic.co"); |
| 14 | + private readonly IReadOnlyCollection<INavigationItem> _navigationItems = navigationItems; |
| 15 | + private readonly IFileSystem _fileSystem = fileSystem; |
| 16 | + private readonly IDirectoryInfo _outputFolder = outputFolder; |
| 17 | + |
| 18 | + public void Generate() |
| 19 | + { |
| 20 | + var flattenedNavigationItems = GetNavigationItems(_navigationItems); |
| 21 | + |
| 22 | + var doc = new XDocument() |
| 23 | + { |
| 24 | + Declaration = new XDeclaration("1.0", "utf-8", "yes"), |
| 25 | + }; |
| 26 | + |
| 27 | + var root = new XElement( |
| 28 | + "urlset", |
| 29 | + new XAttribute("xlmns", "http://www.sitemaps.org/schemas/sitemap/0.9"), |
| 30 | + flattenedNavigationItems |
| 31 | + .OfType<FileNavigationItem>() |
| 32 | + .Select(n => n.File.Url) |
| 33 | + .Distinct() |
| 34 | + .Select(u => new Uri(BaseUri, u)) |
| 35 | + .Select(u => new XElement("url", new XElement("loc", u))) |
| 36 | + ); |
| 37 | + |
| 38 | + doc.Add(root); |
| 39 | + |
| 40 | + using var fileStream = _fileSystem.File.Create(Path.Combine(_outputFolder.ToString() ?? string.Empty, "sitemap.xml")); |
| 41 | + doc.Save(fileStream); |
| 42 | + } |
| 43 | + |
| 44 | + private static IReadOnlyCollection<INavigationItem> GetNavigationItems(IReadOnlyCollection<INavigationItem> items) |
| 45 | + { |
| 46 | + var result = new List<INavigationItem>(); |
| 47 | + foreach (var item in items) |
| 48 | + { |
| 49 | + switch (item) |
| 50 | + { |
| 51 | + case FileNavigationItem file: |
| 52 | + result.Add(file); |
| 53 | + break; |
| 54 | + case GroupNavigationItem group: |
| 55 | + result.AddRange(GetNavigationItems(group.Group.NavigationItems)); |
| 56 | + break; |
| 57 | + } |
| 58 | + } |
| 59 | + return result; |
| 60 | + } |
| 61 | +} |
0 commit comments