Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@
<PackageVersion Include="Proc" Version="0.22.1" />
<PackageVersion Include="RazorSlices" Version="0.12.2" />
<PackageVersion Include="Sep" Version="0.18.0" />
<PackageVersion Include="Slugify.Core" Version="4.0.1" />
<PackageVersion Include="Spectre.Console" Version="0.57.2" />
<PackageVersion Include="SoftCircuits.IniFileParser" Version="3.1.2" />
<PackageVersion Include="System.IO.Abstractions" Version="23.0.0" />
Expand Down
1 change: 0 additions & 1 deletion src/Elastic.Documentation/Elastic.Documentation.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
<PackageReference Include="NetEscapades.EnumGenerators"/>
<PackageReference Include="Nullean.ScopedFileSystem" />
<PackageReference Include="SharpYaml" />
<PackageReference Include="Slugify.Core" />
</ItemGroup>

<ItemGroup>
Expand Down
51 changes: 48 additions & 3 deletions src/Elastic.Documentation/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,61 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.Globalization;
using System.Runtime.InteropServices;
using Slugify;
using System.Text;

namespace Elastic.Documentation.Extensions;

public static class StringExtensions
{
private static readonly SlugHelper SlugHelper = new();
/// <summary>
/// The URL slug of <paramref name="text"/>: trimmed, lower-cased, diacritics removed, whitespace runs turned into one <c>-</c>,
/// everything but <c>a-z 0-9 - _ .</c> dropped and repeated dashes collapsed. Null gives an empty string.
/// Whitespace means any Unicode whitespace (tab, newline, no-break space), as in Slugify.Core 4.0.1. Slugify.Core 5.x only
/// replaces a plain space and drops the others, so <c>a&#9;b</c> gives <c>a-b</c> here and <c>ab</c> there.
/// These rules produce the anchors, heading ids and changelog links, so changing them breaks existing links.
/// </summary>
public static string Slugify(this string? text)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;

var decomposed = text.Trim().Normalize(NormalizationForm.FormD);
var sb = new StringBuilder(decomposed.Length);
var pendingSeparator = false;
foreach (var original in decomposed)
{
if (CharUnicodeInfo.GetUnicodeCategory(original) == UnicodeCategory.NonSpacingMark)
continue;
if (char.IsWhiteSpace(original))
{
pendingSeparator = true;
continue;
}
var c = char.ToLowerInvariant(original);
if (!IsSlugChar(c))
continue;
if (pendingSeparator)
{
AppendSlugChar(sb, '-');
pendingSeparator = false;
}
AppendSlugChar(sb, c);
}
if (pendingSeparator)
AppendSlugChar(sb, '-');
return sb.ToString();
}

private static bool IsSlugChar(char c) => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '-' or '_' or '.';

public static string Slugify(this string? text) => text is null ? string.Empty : SlugHelper.GenerateSlug(text);
private static void AppendSlugChar(StringBuilder sb, char c)
{
if (c == '-' && sb.Length > 0 && sb[^1] == '-')
return;
_ = sb.Append(c);
}

/// <summary>Null for an empty string, so a Razor attribute bound to it is left out instead of written as <c>name=""</c>.</summary>
public static string? NullIfEmpty(this string? value) => string.IsNullOrEmpty(value) ? null : value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
<ItemGroup>
<PackageReference Include="Proc" />
<PackageReference Include="SharpYaml" />
<PackageReference Include="Slugify.Core" />
<PackageReference Include="Microsoft.Extensions.Logging" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using Elastic.Documentation.Extensions;
using Elastic.LegacyDocs.Migration.Asciidoc;
using Microsoft.Extensions.Logging;
using Slugify;

namespace Elastic.LegacyDocs.Migration;

Expand All @@ -17,8 +17,6 @@ public record LatestGeneratorOptions

public class LatestDocsetGenerator(ILogger<LatestDocsetGenerator> logger)
{
private static readonly SlugHelper SlugHelper = new();

public async Task GenerateAsync(LegacyConf conf, LatestGeneratorOptions options, CancellationToken ct = default)
{
var books = conf
Expand Down Expand Up @@ -95,7 +93,7 @@ private async Task ProcessBook(LegacyBook book, LatestGeneratorOptions options,
fileEntries.Add(new TocEntry { File = filename });
}

var projectName = SlugHelper.GenerateSlug(book.Title);
var projectName = book.Title.Slugify();
YamlWriter.WriteDocsetYaml(Path.Combine(docsDir, "docset.yml"), projectName, ["."]);
YamlWriter.WriteTocYaml(Path.Combine(docsDir, "toc.yml"), fileEntries);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

<ItemGroup>
<ProjectReference Include="..\..\src\Elastic.Documentation\Elastic.Documentation.csproj"/>
<None Include="slugify-4.0.1.golden.tsv" CopyToOutputDirectory="PreserveNewest"/>
</ItemGroup>

</Project>
36 changes: 36 additions & 0 deletions tests/Elastic.Documentation.Tests/StringExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
public void JoinOrNull_NoValues_ReturnsNull() => Array.Empty<string>().JoinOrNull(' ').Should().BeNull();

[Test]
public void JoinOrNull_OnlyEmptyValues_ReturnsNull() => new[] { "" }.JoinOrNull(' ').Should().BeNull();

Check warning on line 23 in tests/Elastic.Documentation.Tests/StringExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1861)

Check warning on line 23 in tests/Elastic.Documentation.Tests/StringExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1861)

Check warning on line 23 in tests/Elastic.Documentation.Tests/StringExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1861)

[Test]
public void JoinOrNull_Values_JoinsWithTheSeparator() => new[] { "a", "b" }.JoinOrNull(' ').Should().Be("a b");

Check warning on line 26 in tests/Elastic.Documentation.Tests/StringExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1861)

Check warning on line 26 in tests/Elastic.Documentation.Tests/StringExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1861)

Check warning on line 26 in tests/Elastic.Documentation.Tests/StringExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1861)

[Test]
[Arguments("get-actions-connector-oauth-callback-script", "Get Actions Connector Oauth Callback Script")]
Expand Down Expand Up @@ -54,4 +54,40 @@

[Test]
public void Slugify_NullInput_ReturnsEmptyString() => ((string?)null).Slugify().Should().BeEmpty();

[Test]
[Arguments("", "")]
[Arguments(" ", "")]
[Arguments(" Hello World ", "hello-world")]
[Arguments("a - b", "a-b")]
[Arguments("-a-", "-a-")]
[Arguments("Café Ünï", "cafe-uni")]
[Arguments("1.2.3 a_b", "1.2.3-a_b")]
[Arguments("C# (a/b?c)", "c-abc")]
[Arguments("日本語 text", "-text")]
[Arguments("a\tb", "a-b")]
[Arguments("a\u00a0b\nc", "a-b-c")]
public void Slugify_Rules_AreStable(string input, string expected) => input.Slugify().Should().Be(expected);

/// <summary>
/// <c>slugify-4.0.1.golden.tsv</c> holds what Slugify.Core 4.0.1 produced for the headings in <c>docs/</c> plus edge cases,
/// so a slug (and every link to it) stays the same now that the package is gone.
/// </summary>
[Test]
public void Slugify_MatchesSlugifyCore401Output()
{
var path = Path.Combine(AppContext.BaseDirectory, "slugify-4.0.1.golden.tsv");
var lines = File.ReadAllLines(path);
lines.Should().NotBeEmpty();
var mismatches = new List<string>();
foreach (var line in lines)
{
var tab = line.LastIndexOf('\t');
var input = line[..tab].Replace("\\t", "\t").Replace("\\\\", "\\");
var expected = line[(tab + 1)..];
if (input.Slugify() != expected)
mismatches.Add($"[{input}] expected [{expected}] got [{input.Slugify()}]");
}
mismatches.Should().BeEmpty();
}
}
Loading
Loading