diff --git a/.editorconfig b/.editorconfig
index f8ad6ea8e56..711ffa681ab 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -78,7 +78,8 @@ csharp_prefer_static_local_function = true:suggestion
dotnet_diagnostic.IDE0010.severity = suggestion # IDE0010: Add missing cases to switch statement
dotnet_style_object_initializer = true:suggestion # IDE0017: Use object initializers
csharp_style_inlined_variable_declaration = true:suggestion # IDE0018: Inline variable declaration
-dotnet_style_collection_initializer = true:suggestion # IDE0028: Use collection initializers
+dotnet_style_collection_initializer = true:suggestion # IDE0028: Use collection initializers or expressions
+dotnet_style_prefer_collection_expression = true:suggestion # IDE0028: Use collection initializers or expressions
dotnet_style_prefer_auto_properties = true:suggestion # IDE0032: Use auto-implemented property
dotnet_style_explicit_tuple_names = true:suggestion # IDE0033: Use explicitly provided tuple name
csharp_prefer_simple_default_expression = true:suggestion # IDE0034: Simplify default expression
@@ -153,7 +154,7 @@ dotnet_style_namespace_match_folder = true:suggestion # IDE013
dotnet_diagnostic.IDE0001.severity = suggestion # IDE0001: Simplify name
dotnet_diagnostic.IDE0002.severity = suggestion # IDE0002: Simplify member access
dotnet_diagnostic.IDE0004.severity = suggestion # IDE0004: Remove unnecessary cast
-dotnet_diagnostic.IDE0005.severity = suggestion # IDE0005: Remove unnecessary import
+dotnet_diagnostic.IDE0005.severity = warning # IDE0005: Remove unnecessary import
dotnet_diagnostic.IDE0035.severity = suggestion # IDE0035: Remove unreachable code
dotnet_diagnostic.IDE0051.severity = suggestion # IDE0051: Remove unused private member
dotnet_diagnostic.IDE0052.severity = suggestion # IDE0052: Remove unread private member
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7fbcefc84a4..93b3e6d0d29 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -9,6 +9,7 @@ on:
jobs:
test:
runs-on: ${{ matrix.os }}
+ timeout-minutes: 30
strategy:
fail-fast: false
matrix:
@@ -45,6 +46,11 @@ jobs:
env:
PERCY_TOKEN: ${{ secrets.PERCY_TOKEN }}
+ - uses: codecov/codecov-action@v5
+ if: matrix.os == 'ubuntu-latest'
+ with:
+ fail_ci_if_error: true
+
- run: echo "DOTNET_DbgEnableMiniDump=1" >> $GITHUB_ENV
if: matrix.os == 'ubuntu-latest'
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
new file mode 100644
index 00000000000..aedbb8704f2
--- /dev/null
+++ b/.github/workflows/lint.yml
@@ -0,0 +1,44 @@
+name: lint
+
+on:
+ pull_request:
+ types:
+ - opened
+ - reopened
+ - synchronize
+ - ready_for_review
+ workflow_dispatch:
+
+jobs:
+ build:
+ name: Lint
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ if: github.event.pull_request.draft == false
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Setup .NET SDK
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: |
+ 9.x
+
+ - name: Run `dotnet format` command
+ run: |
+ dotnet restore
+ dotnet format --no-restore --verify-no-changes
+
+ - name: Report failures as Job Summary
+ if: ${{ failure() }}
+ shell: pwsh
+ run: |
+ $content = '
+ ## Failed to run the `lint.yml` workflow
+ To fix workflow errors. Please follow the steps below.
+ 1. Run `dotnet format` command.
+ 2. Commit changes as separated commit.
+ 3. Push changes to source branch of PR.
+ '
+ Write-Output $content >> $env:GITHUB_STEP_SUMMARY
diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml
index 6ba3f724aba..c799d493e7d 100644
--- a/.github/workflows/nightly.yml
+++ b/.github/workflows/nightly.yml
@@ -1,5 +1,6 @@
name: nightly
on:
+ workflow_dispatch:
schedule:
- cron: '0 0 * * *'
@@ -10,6 +11,7 @@ jobs:
publish-github-packages:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
+ timeout-minutes: 30
permissions:
packages: write
steps:
@@ -40,3 +42,44 @@ jobs:
run: |
dotnet nuget push drop/nuget/*.nupkg --api-key "${{ secrets.GITHUB_TOKEN }}" --skip-duplicate --source https://nuget.pkg.github.com/dotnet/index.json
+ test-nightly-package:
+ if: github.repository == 'dotnet/docfx'
+ runs-on: ubuntu-latest
+ needs: [publish-github-packages]
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ steps:
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Create NuGet.config
+ shell: pwsh
+ run: |
+ @'
+
+
+
+
+
+
+
+
+
+
+
+
+
+ '@ | Out-File NuGet.config -Encoding UTF8
+
+ - name: Install nightly build package
+ run: |
+ dotnet tool install docfx -g --prerelease
+
+ - name: Run docfx commands for test
+ working-directory: samples/seed
+ run: |
+ docfx metadata
+ docfx build
+ docfx pdf
+
diff --git a/.github/workflows/reports.yml b/.github/workflows/reports.yml
index 88edd1c0b69..92281b63644 100644
--- a/.github/workflows/reports.yml
+++ b/.github/workflows/reports.yml
@@ -15,6 +15,7 @@ permissions:
jobs:
report:
runs-on: ubuntu-latest
+ timeout-minutes: 30
if: ${{ github.event.workflow_run.conclusion == 'success' || github.event.workflow_run.conclusion == 'failure' }}
steps:
- name: Create Test Report
diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml
index 4d383270736..6aa7d813f61 100644
--- a/.github/workflows/snapshot.yml
+++ b/.github/workflows/snapshot.yml
@@ -11,6 +11,7 @@ on:
jobs:
snapshot:
runs-on: ubuntu-latest
+ timeout-minutes: 30
environment: ci
strategy:
fail-fast: false
diff --git a/Directory.Build.props b/Directory.Build.props
index 9ec7dd187a7..c2c1f4bd877 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -2,7 +2,7 @@
true
net8.0;net9.0
- net8.0;net9.0
+ net8.0;net9.0
Preview
enable
true
@@ -19,9 +19,8 @@
warning NU1507: There are 2 package sources defined in your configuration.
warning NU5104: A stable release of a package should not have a prerelease dependency. Either modify the version spec of dependency "PdfPig [0.1.9-alpha-20240510-d86c2, )" or update the version field in the nuspec.
warning NU5111: The script file 'tools\.playwright\package\bin\install_media_pack.ps1' is not recognized by NuGet and hence will not be executed during installation of this package.
- warning CS0436: IgnoresAccessChecksTo redefinition due to InternalsVisibleTo
-->
- $(NoWarn);NU1507;NU5104;NU5111;CS0436
+ $(NoWarn);NU1507;NU5104;NU5111
@@ -30,8 +29,8 @@
true
true
snupkg
- true
-
+ true
+
.NET Foundation and Contributors
Copyright (c) .NET Foundation and Contributors
Technical documentation tool with markdown, API docs for .NET, REST API and more.
@@ -45,13 +44,6 @@
-
-
- all
- runtime; build; native; contentfiles; analyzers
-
-
-
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 2ca7cb4b913..78c7cbe693c 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -4,14 +4,12 @@
true
-
+
-
-
-
+
@@ -20,33 +18,25 @@
-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
+
diff --git a/Dockerfile b/Dockerfile
index d46998ee16a..ec5ca671b1c 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,34 +1,28 @@
-FROM mcr.microsoft.com/dotnet/sdk:8.0-bookworm-slim
+FROM mcr.microsoft.com/dotnet/sdk:8.0-noble
# Add dotnet tools to path.
ENV PATH="${PATH}:/root/.dotnet/tools"
+# Set Node.js path
+ENV PLAYWRIGHT_NODEJS_PATH="/usr/bin/node"
+
# Set target docfx version.
-ARG DOCFX_VERSION=2.77.0
+ARG DOCFX_VERSION=2.78.2
# Install DocFX as a dotnet tool.
RUN dotnet tool install docfx -g --version ${DOCFX_VERSION} && \
docfx --version && \
rm -f /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/docfx.nupkg && \
rm -f /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/docfx.${DOCFX_VERSION}.nupkg && \
- rm -rf /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/tools/net6.0
-
-# Install Node.js and dependences for chromium PDF.
-RUN apt-get update -qq && \
- apt-get install -y -qq --no-install-recommends \
- nodejs \
- libglib2.0-0 libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 \
- libdbus-1-3 libxcb1 libxkbcommon0 libatspi2.0-0 libx11-6 libxcomposite1 libxdamage1 \
- libxext6 libxfixes3 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2 && \
- rm -rf /var/lib/apt/lists/* /tmp/*
+ rm -rf /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/tools/net9.0
-# Install Chromium.
-RUN PLAYWRIGHT_NODEJS_PATH="/usr/bin/node" && \
- ln -s /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/tools/.playwright /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/tools/net8.0/any/.playwright && \
- pwsh -File /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/tools/net8.0/any/playwright.ps1 install chromium && \
- unlink /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/tools/net8.0/any/.playwright
+# Install Node.js and browser(chromium) with dependencies
+RUN apt-get install -y -qq --update --no-install-recommends nodejs && \
+ pwsh -File /root/.dotnet/tools/.store/docfx/${DOCFX_VERSION}/docfx/${DOCFX_VERSION}/tools/net8.0/any/playwright.ps1 install --with-deps chromium && \
+ rm -rf /var/lib/apt/lists/* && \
+ rm -rf /tmp/*
WORKDIR /opt/prj
VOLUME [ "/opt/prj" ]
-ENTRYPOINT [ "docfx" ]
\ No newline at end of file
+ENTRYPOINT [ "docfx" ]
diff --git a/docfx.sln b/docfx.sln
index 9e732c85f0f..a5974afe119 100644
--- a/docfx.sln
+++ b/docfx.sln
@@ -15,6 +15,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{926A0726-B806-4215-82EF-AF8E22D0FACF}"
ProjectSection(SolutionItems) = preProject
test\Directory.Build.props = test\Directory.Build.props
+ test\Directory.Packages.props = test\Directory.Packages.props
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "docfx", "src\docfx\docfx.csproj", "{EF53214F-BA98-4026-BEED-CF771865C312}"
@@ -97,6 +98,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Docfx.Build.OverwriteDocume
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Docfx.Build.OverwriteDocuments.Tests", "test\Docfx.Build.OverwriteDocuments.Tests\Docfx.Build.OverwriteDocuments.Tests.csproj", "{CAECA6C3-3317-4E6E-8927-9186857B23E8}"
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}"
+ ProjectSection(SolutionItems) = preProject
+ .editorconfig = .editorconfig
+ Directory.Build.props = Directory.Build.props
+ Directory.Packages.props = Directory.Packages.props
+ EndProjectSection
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
diff --git a/docs/docs/links-and-cross-references.md b/docs/docs/links-and-cross-references.md
index 9afad763ae4..eb7b0f5cee5 100644
--- a/docs/docs/links-and-cross-references.md
+++ b/docs/docs/links-and-cross-references.md
@@ -178,6 +178,8 @@ You can create a cross link with following options:
- `displayProperty`: the property of display text when the cross reference is has resolved correctly.
e.g.: `` will be resolved as .
+
+ e.g.: `` will be resolved as .
- `altProperty`: the property of display text when the cross reference does not have a `href` property.
e.g.: ```` will be resolved as .
diff --git a/docs/index.md b/docs/index.md
index ee497ffed05..0ea52aeee8d 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -9,7 +9,7 @@ In this section we will build a simple documentation site on your local machine.
> Prerequisites
> - Familiarity with the command line
> - Install [.NET SDK](https://dotnet.microsoft.com/en-us/download) 8.0 or higher
-> - Install [Node.js](https://nodejs.org/) v20 or higher
+> - Install [Node.js](https://nodejs.org/) v20 or higher (Optional: It's required when using [Create PDF Files](https://filzrev.github.io/docfx/docs/pdf.html))
Make sure you have [.NET SDK](https://dotnet.microsoft.com/en-us/download) installed, then open a terminal and enter the following command to install the latest docfx:
@@ -114,6 +114,53 @@ await Docfx.Docset.Build("docfx.json");
See [API References](api/Docfx.yml) for additional APIs.
+## How to use prerelease version of docfx
+
+Docfx publishes nightly builds to [GitHub Packages](https://github.com/dotnet/docfx/pkgs/nuget/docfx).
+If you want to use prerelease version, you can install package with following steps.
+
+### Prerequisite
+
+1. Install [GitHub CLI](https://github.com/cli/cli) command.
+2. Install PowerShell 7.x or later.
+
+### Steps
+
+1. Open PowerShell on working directory.
+
+2. Login to GitHub with additional scope request
+
+ ```pwsh
+ gh auth login --scopes "read:packages" --host github.com
+ ```
+
+3. Follow the instructions and complete the login steps.
+
+4. Download docfx nuget package from GitHub Packages
+
+ ```pwsh
+ # Gets Access Token
+ $token = gh auth token
+
+ # Gets the version of latest nightly build
+ $version = gh api /orgs/dotnet/packages/nuget/docfx/versions --jq '.[0].name'
+
+ # Gets nupkg download URL.
+ $downloadUrl = "https://nuget.pkg.github.com/dotnet/download/docfx/${version}/${version}.nupkg"
+
+ # Download nupkg to current directory.
+ Write-Host ('Download nupkg from: {0}' -f $downloadUrl)
+ Invoke-RestMethod -Method Get -Uri $downloadUrl -OutFile "docfx.${version}.nupkg" -Headers @{
+ Authorization = "Bearer $token"
+ }
+ ```
+
+5. Install docfx as .NET Global Package from local source
+
+ ```pwsh
+ dotnet tool update docfx -g --prerelease --source ./
+ ```
+
## Next Steps
- [Write Articles](docs/markdown.md)
diff --git a/docs/reference/docfx-cli-reference/docfx-metadata.md b/docs/reference/docfx-cli-reference/docfx-metadata.md
index fc679ed5142..fcf55620fd2 100644
--- a/docs/reference/docfx-cli-reference/docfx-metadata.md
+++ b/docs/reference/docfx-cli-reference/docfx-metadata.md
@@ -77,6 +77,10 @@ Run `docfx metadata --help` or `docfx -h` to get a list of all available options
Disable the default API filter (default filter only generate public or protected APIs).
+- **--noRestore**
+
+ Do not run `dotnet restore` before building the projects.
+
- **--namespaceLayout**
Determines the namespace layout in table of contents.
diff --git a/samples/seed/docfx.json b/samples/seed/docfx.json
index 6dcf2b76192..3dfed8aca10 100644
--- a/samples/seed/docfx.json
+++ b/samples/seed/docfx.json
@@ -70,7 +70,7 @@
{ "files": [ "**" ], "src": "obj/md", "dest": "md" },
{ "files": [ "**" ], "src": "obj/apipage", "dest": "apipage" },
{ "files": [ "articles/**/*.{md,yml}", "*.md", "toc.yml", "restapi/**" ] },
- { "files": [ "pdf/**" ] }
+ { "files": [ "pdf/*.{md,yml}" ] }
],
"resource": [
{
diff --git a/samples/seed/dotnet/assembly/BuildFromAssembly.csproj b/samples/seed/dotnet/assembly/BuildFromAssembly.csproj
index b42d68e6ba4..1707423aa11 100644
--- a/samples/seed/dotnet/assembly/BuildFromAssembly.csproj
+++ b/samples/seed/dotnet/assembly/BuildFromAssembly.csproj
@@ -1,7 +1,7 @@
- net7.0
+ net8.0
enable
enable
true
diff --git a/src/Docfx.App/Config/BuildJsonConfig.cs b/src/Docfx.App/Config/BuildJsonConfig.cs
index c9dd2a4003a..ed4b395004f 100644
--- a/src/Docfx.App/Config/BuildJsonConfig.cs
+++ b/src/Docfx.App/Config/BuildJsonConfig.cs
@@ -72,7 +72,7 @@ internal class BuildJsonConfig
///
[JsonProperty("globalMetadataFiles")]
[JsonPropertyName("globalMetadataFiles")]
- public ListWithStringFallback GlobalMetadataFiles { get; set; } = new();
+ public ListWithStringFallback GlobalMetadataFiles { get; set; } = [];
///
/// Metadata that applies to some specific files.
@@ -99,7 +99,7 @@ internal class BuildJsonConfig
///
[JsonProperty("template")]
[JsonPropertyName("template")]
- public ListWithStringFallback Template { get; set; } = new();
+ public ListWithStringFallback Template { get; set; } = [];
///
/// The themes applied to the documentation.
@@ -123,7 +123,7 @@ internal class BuildJsonConfig
///
[JsonProperty("postProcessors")]
[JsonPropertyName("postProcessors")]
- public ListWithStringFallback PostProcessors { get; set; } = new();
+ public ListWithStringFallback PostProcessors { get; set; } = [];
///
/// Run in debug mode. With debug mode, raw model and view model will be exported
diff --git a/src/Docfx.App/Config/FileMetadataPairs.cs b/src/Docfx.App/Config/FileMetadataPairs.cs
index 7390e638ad1..b816e909576 100644
--- a/src/Docfx.App/Config/FileMetadataPairs.cs
+++ b/src/Docfx.App/Config/FileMetadataPairs.cs
@@ -39,7 +39,7 @@ public FileMetadataPairs(IEnumerable items)
///
public FileMetadataPairs(FileMetadataPairsItem item)
{
- _items = new List { item };
+ _items = [item];
}
///
diff --git a/src/Docfx.App/Config/FileMetadataPairsConverter.SystemTextJson.cs b/src/Docfx.App/Config/FileMetadataPairsConverter.SystemTextJson.cs
index 5d294a0e691..7756e581a4b 100644
--- a/src/Docfx.App/Config/FileMetadataPairsConverter.SystemTextJson.cs
+++ b/src/Docfx.App/Config/FileMetadataPairsConverter.SystemTextJson.cs
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using Docfx.Common;
diff --git a/src/Docfx.App/Config/FileMetadataPairsConverter.cs b/src/Docfx.App/Config/FileMetadataPairsConverter.cs
index 71dcc5f3458..a982a1a9c28 100644
--- a/src/Docfx.App/Config/FileMetadataPairsConverter.cs
+++ b/src/Docfx.App/Config/FileMetadataPairsConverter.cs
@@ -1,11 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Docfx.Common;
-
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
namespace Docfx;
///
diff --git a/src/Docfx.App/Config/GroupConfig.cs b/src/Docfx.App/Config/GroupConfig.cs
index c6346938de3..f443a717c1a 100644
--- a/src/Docfx.App/Config/GroupConfig.cs
+++ b/src/Docfx.App/Config/GroupConfig.cs
@@ -23,5 +23,5 @@ internal class GroupConfig
///
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.App/Config/ListWithStringFallbackConverter.SystemTextJson.cs b/src/Docfx.App/Config/ListWithStringFallbackConverter.SystemTextJson.cs
index 219ec035958..1c1ef94d29a 100644
--- a/src/Docfx.App/Config/ListWithStringFallbackConverter.SystemTextJson.cs
+++ b/src/Docfx.App/Config/ListWithStringFallbackConverter.SystemTextJson.cs
@@ -1,10 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
-using YamlDotNet.Serialization;
namespace Docfx;
@@ -35,7 +33,7 @@ public override ListWithStringFallback Read(ref Utf8JsonReader reader, Type type
{
using var document = JsonDocument.ParseValue(ref reader);
JsonElement root = document.RootElement;
- var values = root.EnumerateObject().Select(x=>x.ToString());
+ var values = root.EnumerateObject().Select(x => x.ToString());
return new ListWithStringFallback(values);
}
default:
diff --git a/src/Docfx.App/Config/ListWithStringFallbackConverter.cs b/src/Docfx.App/Config/ListWithStringFallbackConverter.cs
index 12188991a86..ea91f6aa239 100644
--- a/src/Docfx.App/Config/ListWithStringFallbackConverter.cs
+++ b/src/Docfx.App/Config/ListWithStringFallbackConverter.cs
@@ -1,9 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
namespace Docfx;
diff --git a/src/Docfx.App/Config/MergeJsonConfigConverter.NewtonsoftJson.cs b/src/Docfx.App/Config/MergeJsonConfigConverter.NewtonsoftJson.cs
index 344c352c61f..2c72f7efef4 100644
--- a/src/Docfx.App/Config/MergeJsonConfigConverter.NewtonsoftJson.cs
+++ b/src/Docfx.App/Config/MergeJsonConfigConverter.NewtonsoftJson.cs
@@ -65,4 +65,4 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s
serializer.Serialize(writer, ((MergeJsonConfig)value).ToArray());
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Docfx.App/Config/MergeJsonConfigConverter.SystemTextJson.cs b/src/Docfx.App/Config/MergeJsonConfigConverter.SystemTextJson.cs
index 90ebe522bd1..fcb0825a71a 100644
--- a/src/Docfx.App/Config/MergeJsonConfigConverter.SystemTextJson.cs
+++ b/src/Docfx.App/Config/MergeJsonConfigConverter.SystemTextJson.cs
@@ -3,7 +3,6 @@
using System.Text.Json;
using System.Text.Json.Serialization;
-using YamlDotNet.Serialization;
namespace Docfx;
diff --git a/src/Docfx.App/Config/MergeJsonConfigConverter.cs b/src/Docfx.App/Config/MergeJsonConfigConverter.cs
index 64d4e815013..03c9836af2f 100644
--- a/src/Docfx.App/Config/MergeJsonConfigConverter.cs
+++ b/src/Docfx.App/Config/MergeJsonConfigConverter.cs
@@ -1,9 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
namespace Docfx;
///
diff --git a/src/Docfx.App/Docfx.App.csproj b/src/Docfx.App/Docfx.App.csproj
index 12db285be2e..e4d0f5d7804 100644
--- a/src/Docfx.App/Docfx.App.csproj
+++ b/src/Docfx.App/Docfx.App.csproj
@@ -18,11 +18,6 @@
-
-
-
-
-
diff --git a/src/Docfx.App/Helpers/DocumentBuilderWrapper.cs b/src/Docfx.App/Helpers/DocumentBuilderWrapper.cs
index 2bafb81bef6..c9324530912 100644
--- a/src/Docfx.App/Helpers/DocumentBuilderWrapper.cs
+++ b/src/Docfx.App/Helpers/DocumentBuilderWrapper.cs
@@ -263,7 +263,7 @@ private static FileMetadata GetFileMetadata(string baseDirectory, BuildJsonConfi
{
foreach (var (key, value) in config.FileMetadata)
{
- var list = result.TryGetValue(key, out var items) ? items : result[key] = new();
+ var list = result.TryGetValue(key, out var items) ? items : result[key] = [];
foreach (var pair in value.Items)
{
list.Add(new FileMetadataItem(pair.Glob, key, pair.Value));
@@ -277,7 +277,7 @@ private static FileMetadata GetFileMetadata(string baseDirectory, BuildJsonConfi
{
foreach (var (key, value) in JsonUtility.Deserialize>(path))
{
- var list = result.TryGetValue(key, out var items) ? items : result[key] = new();
+ var list = result.TryGetValue(key, out var items) ? items : result[key] = [];
foreach (var pair in value.Items)
{
list.Add(new FileMetadataItem(pair.Glob, key, pair.Value));
diff --git a/src/Docfx.App/Helpers/MetadataMerger.cs b/src/Docfx.App/Helpers/MetadataMerger.cs
index 2dee2e496f3..c4b80118d2f 100644
--- a/src/Docfx.App/Helpers/MetadataMerger.cs
+++ b/src/Docfx.App/Helpers/MetadataMerger.cs
@@ -14,8 +14,8 @@ namespace Docfx;
internal class MetadataMerger
{
- private readonly Dictionary> _metaTable = new();
- private readonly Dictionary> _propTable = new();
+ private readonly Dictionary> _metaTable = [];
+ private readonly Dictionary> _propTable = [];
public void Merge(MetadataMergeParameters parameters)
{
diff --git a/src/Docfx.App/Helpers/PdfPigTypeExtensions.cs b/src/Docfx.App/Helpers/PdfPigTypeExtensions.cs
new file mode 100644
index 00000000000..8b0391424c0
--- /dev/null
+++ b/src/Docfx.App/Helpers/PdfPigTypeExtensions.cs
@@ -0,0 +1,27 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Runtime.CompilerServices;
+using UglyToad.PdfPig.Content;
+using UglyToad.PdfPig.Outline.Destinations;
+
+#nullable enable
+
+namespace Docfx;
+
+internal static class PdfPigTypeExtensions
+{
+ public static NamedDestinations GetNamedDestinations(this Catalog catalog)
+ => GetNamedDestinationsProperty(catalog);
+
+ public static bool TryGet(this NamedDestinations namedDestinations, string name, out ExplicitDestination dest)
+ => TryGetNamedDestinations(namedDestinations, name, out dest);
+
+ // Gets property value of catalog.NamedDestination.
+ [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "get_NamedDestinations")]
+ private static extern NamedDestinations GetNamedDestinationsProperty(Catalog value);
+
+ [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "TryGet")]
+ private static extern bool TryGetNamedDestinations(NamedDestinations namedDestinations, string name, out ExplicitDestination dest);
+}
+
diff --git a/src/Docfx.App/PdfBuilder.cs b/src/Docfx.App/PdfBuilder.cs
index fdb1312dc36..c5a40cf603c 100644
--- a/src/Docfx.App/PdfBuilder.cs
+++ b/src/Docfx.App/PdfBuilder.cs
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Reflection;
@@ -32,6 +33,8 @@ namespace Docfx.Pdf;
static class PdfBuilder
{
+ private static readonly SearchValues InvalidPathChars = SearchValues.Create(Path.GetInvalidPathChars());
+
class Outline
{
public string name { get; init; } = "";
@@ -48,11 +51,6 @@ class Outline
public string? pdfFooterTemplate { get; init; }
}
- static PdfBuilder()
- {
- PlaywrightHelper.EnsurePlaywrightNodeJsPath();
- }
-
public static Task Run(BuildJsonConfig config, string configDirectory, string? outputDirectory = null)
{
var outputFolder = Path.GetFullPath(Path.Combine(
@@ -70,7 +68,9 @@ public static async Task CreatePdf(string outputFolder)
if (pdfTocs.Count == 0)
return;
- Program.Main(["install", "chromium"]);
+ PlaywrightHelper.EnsurePlaywrightNodeJsPath();
+
+ Program.Main(["install", "chromium", "--only-shell"]);
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
@@ -97,7 +97,8 @@ public static async Task CreatePdf(string outputFolder)
using var pageLimiter = new SemaphoreSlim(Environment.ProcessorCount, Environment.ProcessorCount);
var pagePool = new ConcurrentBag();
- var headerFooterCache = new ConcurrentDictionary<(string, string), Task>();
+ var headerFooterTemplateCache = new ConcurrentDictionary();
+ var headerFooterPageCache = new ConcurrentDictionary<(string, string), Task>();
await AnsiConsole.Progress().StartAsync(async progress =>
{
@@ -109,7 +110,7 @@ await Parallel.ForEachAsync(pdfTocs, async (item, _) =>
var outputPath = Path.Combine(outputFolder, outputName);
await CreatePdf(
- PrintPdf, PrintHeaderFooter, task, new(baseUrl, url), toc, outputPath,
+ PrintPdf, PrintHeaderFooter, task, new(baseUrl, url), toc, outputFolder, outputPath,
pageNumbers => pdfPageNumbers[url] = pageNumbers);
task.Value = task.MaxValue;
@@ -190,7 +191,7 @@ Task PrintHeaderFooter(Outline toc, int pageNumber, int totalPages, Page
var headerTemplate = ExpandTemplate(GetHeaderFooter(toc.pdfHeaderTemplate), pageNumber, totalPages);
var footerTemplate = ExpandTemplate(GetHeaderFooter(toc.pdfFooterTemplate) ?? DefaultFooterTemplate, pageNumber, totalPages);
- return headerFooterCache.GetOrAdd((headerTemplate, footerTemplate), _ => PrintHeaderFooterCore());
+ return headerFooterPageCache.GetOrAdd((headerTemplate, footerTemplate), _ => PrintHeaderFooterCore());
async Task PrintHeaderFooterCore()
{
@@ -244,26 +245,36 @@ static string ExpandTemplate(string? pdfTemplate, int pageNumber, int totalPages
if (string.IsNullOrEmpty(template))
return template;
- try
- {
- var path = Path.Combine(outputFolder, template);
- return File.Exists(path) ? File.ReadAllText(path) : template;
- }
- catch
- {
+ // Check path chars. If it's contains HTML chars. Skip access to file content to optimmize performance
+ if (template.AsSpan().ContainsAny(InvalidPathChars))
return template;
- }
+
+ return headerFooterTemplateCache.GetOrAdd(template, (_) =>
+ {
+ // Note: This valueFactory might be called multiple times.
+ try
+ {
+ var path = Path.GetFullPath(Path.Combine(outputFolder, template));
+ if (!File.Exists(path))
+ return template;
+
+ var templateContent = File.ReadAllText(path);
+ return templateContent;
+ }
+ catch
+ {
+ return template;
+ }
+ });
}
+
}
}
static async Task CreatePdf(
Func> printPdf, Func> printHeaderFooter, ProgressTask task,
- Uri outlineUrl, Outline outline, string outputPath, Action> updatePageNumbers)
+ Uri outlineUrl, Outline outline, string outputFolder, string outputPath, Action> updatePageNumbers)
{
- var tempDirectory = Path.Combine(Path.GetTempPath(), ".docfx", "pdf", "pages");
- Directory.CreateDirectory(tempDirectory);
-
var pages = GetPages(outline).ToArray();
if (pages.Length == 0)
return;
@@ -300,8 +311,8 @@ await Parallel.ForEachAsync(pages, async (item, _) =>
var key = CleanUrl(url);
if (!pagesByUrl.TryGetValue(key, out var dests))
- pagesByUrl[key] = dests = new();
- dests.Add((node, document.Structure.Catalog.NamedDestinations));
+ pagesByUrl[key] = dests = [];
+ dests.Add((node, document.Structure.Catalog.GetNamedDestinations()));
pageBytes[node] = bytes;
pageNumbers[node] = numberOfPages + 1;
@@ -360,6 +371,8 @@ async Task MergePdf()
if (!pageBytes.TryGetValue(node, out var bytes))
continue;
+ var isCoverPage = IsCoverPage(url, outputFolder, outline.pdfCoverPage);
+
var isTocPage = IsTocPage(url);
if (isTocPage)
{
@@ -378,6 +391,9 @@ async Task MergePdf()
var pageBuilder = builder.AddPage(document, i, x => CopyLink(node, x));
+ if (isCoverPage)
+ continue;
+
if (isTocPage)
continue;
@@ -438,6 +454,19 @@ PdfAction HandleUriAction(UriAction url)
static Uri CleanUrl(Uri url) => new UriBuilder(url) { Query = null, Fragment = null }.Uri;
+ static bool IsCoverPage(Uri pageUri, string baseFolder, string? pdfCoverPage)
+ {
+ Debug.Assert(Path.IsPathFullyQualified(baseFolder));
+
+ if (string.IsNullOrEmpty(pdfCoverPage))
+ return false;
+
+ string pagePath = pageUri.AbsolutePath.TrimStart('/');
+ string covePagePath = PathUtility.MakeRelativePath(baseFolder, Path.GetFullPath(Path.Combine(baseFolder, pdfCoverPage)));
+
+ return pagePath.Equals(covePagePath, GetStringComparison());
+ }
+
static bool IsTocPage(Uri url) => url.AbsolutePath.StartsWith("/_pdftoc/");
Bookmarks CreateBookmarks(Outline[]? items)
@@ -618,4 +647,12 @@ static string getMillimeter(double pt)
return $"{Math.Round(pt * MillimeterPerInch / Dpi)}mm";
}
}
+
+ // Gets StringComparison instance for path string.
+ private static StringComparison GetStringComparison()
+ {
+ return PathUtility.IsPathCaseInsensitive()
+ ? StringComparison.OrdinalIgnoreCase
+ : StringComparison.Ordinal;
+ }
}
diff --git a/src/Docfx.App/RunBuild.cs b/src/Docfx.App/RunBuild.cs
index 5501ae9e856..0549827bfd3 100644
--- a/src/Docfx.App/RunBuild.cs
+++ b/src/Docfx.App/RunBuild.cs
@@ -21,7 +21,7 @@ public static string Exec(BuildJsonConfig config, BuildOptions options, string c
var stopwatch = Stopwatch.StartNew();
if (config.Template == null || config.Template.Count == 0)
{
- config.Template = new ListWithStringFallback { "default" };
+ config.Template = ["default"];
}
var baseDirectory = Path.GetFullPath(string.IsNullOrEmpty(configDirectory) ? Directory.GetCurrentDirectory() : configDirectory);
diff --git a/src/Docfx.App/RunMerge.cs b/src/Docfx.App/RunMerge.cs
index 76df5b5ed51..1b6ed57744a 100644
--- a/src/Docfx.App/RunMerge.cs
+++ b/src/Docfx.App/RunMerge.cs
@@ -56,7 +56,7 @@ private static MetadataMergeParameters ConfigToParameter(MergeJsonItemConfig con
OutputBaseDir = outputDirectory,
Metadata = config.GlobalMetadata?.ToImmutableDictionary() ?? ImmutableDictionary.Empty,
FileMetadata = ConvertToFileMetadataItem(baseDirectory, config.FileMetadata),
- TocMetadata = config.TocMetadata?.ToImmutableList() ?? ImmutableList.Empty,
+ TocMetadata = config.TocMetadata?.ToImmutableList() ?? [],
Files = GetFileCollectionFromFileMapping(
baseDirectory,
DocumentType.Article,
diff --git a/src/Docfx.Build.Common/MarkdownReader.cs b/src/Docfx.Build.Common/MarkdownReader.cs
index 1aae2b1eaf8..66e9a40fc33 100644
--- a/src/Docfx.Build.Common/MarkdownReader.cs
+++ b/src/Docfx.Build.Common/MarkdownReader.cs
@@ -13,7 +13,7 @@ namespace Docfx.Build.Common;
public class MarkdownReader
{
- private static readonly ImmutableList RequiredProperties = ImmutableList.Create(Constants.PropertyName.Uid);
+ private static readonly ImmutableList RequiredProperties = [Constants.PropertyName.Uid];
public static IEnumerable ReadMarkdownAsOverwrite(IHostService host, FileAndType ft)
{
diff --git a/src/Docfx.Build.Common/ModelAttributeHandlers/HandleModelAttributesContext.cs b/src/Docfx.Build.Common/ModelAttributeHandlers/HandleModelAttributesContext.cs
index 10f37bc5c1c..87a6811be05 100644
--- a/src/Docfx.Build.Common/ModelAttributeHandlers/HandleModelAttributesContext.cs
+++ b/src/Docfx.Build.Common/ModelAttributeHandlers/HandleModelAttributesContext.cs
@@ -14,11 +14,11 @@ public class HandleModelAttributesContext
public bool EnableContentPlaceholder { get; set; }
public string PlaceholderContent { get; set; }
public bool ContainsPlaceholder { get; set; }
- public HashSet Dependency { get; set; } = new();
+ public HashSet Dependency { get; set; } = [];
public FileAndType FileAndType { get; set; }
public HashSet LinkToFiles { get; set; } = new(FilePathComparer.OSPlatformSensitiveStringComparer);
- public HashSet LinkToUids { get; set; } = new();
- public List Uids { get; set; } = new();
- public Dictionary> UidLinkSources { get; set; } = new();
- public Dictionary> FileLinkSources { get; set; } = new();
+ public HashSet LinkToUids { get; set; } = [];
+ public List Uids { get; set; } = [];
+ public Dictionary> UidLinkSources { get; set; } = [];
+ public Dictionary> FileLinkSources { get; set; } = [];
}
diff --git a/src/Docfx.Build.Common/ModelAttributeHandlers/Handlers/BaseModelAttributeHandler.cs b/src/Docfx.Build.Common/ModelAttributeHandlers/Handlers/BaseModelAttributeHandler.cs
index 1178c9062bf..50ca4526e80 100644
--- a/src/Docfx.Build.Common/ModelAttributeHandlers/Handlers/BaseModelAttributeHandler.cs
+++ b/src/Docfx.Build.Common/ModelAttributeHandlers/Handlers/BaseModelAttributeHandler.cs
@@ -78,7 +78,7 @@ public object Handle(object obj, HandleModelAttributesContext context)
protected virtual bool ShouldHandle(object currentObj, object declaringObject, PropInfo currentPropInfo, HandleModelAttributesContext context)
{
- return currentPropInfo is {Attr: not null};
+ return currentPropInfo is { Attr: not null };
}
///
diff --git a/src/Docfx.Build.Common/ModelAttributeHandlers/Handlers/UrlContentHandler.cs b/src/Docfx.Build.Common/ModelAttributeHandlers/Handlers/UrlContentHandler.cs
index 369a59e41f3..9cd182da3fa 100644
--- a/src/Docfx.Build.Common/ModelAttributeHandlers/Handlers/UrlContentHandler.cs
+++ b/src/Docfx.Build.Common/ModelAttributeHandlers/Handlers/UrlContentHandler.cs
@@ -98,7 +98,7 @@ private static string GetHrefFromRoot(string originalHref, HandleModelAttributes
if (!context.FileLinkSources.TryGetValue(file, out List sources))
{
- sources = new List();
+ sources = [];
context.FileLinkSources[file] = sources;
}
sources.Add(new LinkSourceInfo
diff --git a/src/Docfx.Build.Common/Reference/OverwriteDocumentModel.cs b/src/Docfx.Build.Common/Reference/OverwriteDocumentModel.cs
index 8ac8f568cbb..90d9118ba0c 100644
--- a/src/Docfx.Build.Common/Reference/OverwriteDocumentModel.cs
+++ b/src/Docfx.Build.Common/Reference/OverwriteDocumentModel.cs
@@ -17,7 +17,7 @@ public class OverwriteDocumentModel
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
///
/// The uid for this overwrite document, as defined in YAML header
@@ -49,7 +49,7 @@ public class OverwriteDocumentModel
[YamlIgnore]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public HashSet LinkToFiles { get; set; } = new();
+ public HashSet LinkToFiles { get; set; } = [];
///
/// Links to other Uids
@@ -57,7 +57,7 @@ public class OverwriteDocumentModel
[YamlIgnore]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public HashSet LinkToUids { get; set; } = new();
+ public HashSet LinkToUids { get; set; } = [];
///
/// Link sources information for file
@@ -65,7 +65,7 @@ public class OverwriteDocumentModel
[YamlIgnore]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public Dictionary> FileLinkSources { get; set; } = new();
+ public Dictionary> FileLinkSources { get; set; } = [];
///
/// Link sources information for Uid
@@ -73,7 +73,7 @@ public class OverwriteDocumentModel
[YamlIgnore]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public Dictionary> UidLinkSources { get; set; } = new();
+ public Dictionary> UidLinkSources { get; set; } = [];
///
/// Dependencies extracted from the markdown content
diff --git a/src/Docfx.Build.ManagedReference/ApplyPlatformVersion.cs b/src/Docfx.Build.ManagedReference/ApplyPlatformVersion.cs
index 9135d8c370a..87da14659f5 100644
--- a/src/Docfx.Build.ManagedReference/ApplyPlatformVersion.cs
+++ b/src/Docfx.Build.ManagedReference/ApplyPlatformVersion.cs
@@ -60,7 +60,7 @@ private static List GetPlatformVersionFromMetadata(object value)
{
if (value is string text)
{
- return new List { text };
+ return [text];
}
if (value is IEnumerable
- internal sealed class TopicTocParseRule : ParseRule
+ internal sealed partial class TopicTocParseRule : ParseRule
{
- private static readonly Regex UidRegex = new(@"^\s*(?:xref:|@)(\s*?\S+?[\s\S]*?)\s*$", RegexOptions.Compiled);
- public static readonly Regex TocRegex =
- new(@"^(?#+)(( |\t)*)\[(?.+)\]\((?(?!http[s]?://).*?)(\)| ""(?.*)""\))(?:( |\t)+#*)?( |\t)*(\n|$)", RegexOptions.Compiled);
+ [GeneratedRegex(@"^\s*(?:xref:|@)(\s*?\S+?[\s\S]*?)\s*$")]
+ private static partial Regex UidRegex();
- public override Match Match(string text) => TocRegex.Match(text);
+ [GeneratedRegex(@"^(?#+)(( |\t)*)\[(?.+)\]\((?(?!http[s]?://).*?)(\)| ""(?.*)""\))(?:( |\t)+#*)?( |\t)*(\n|$)")]
+ private static partial Regex TocRegex();
+
+ public override Match Match(string text) => TocRegex().Match(text);
public override ParseState Apply(ParseState state, Match match)
{
var tocLink = match.Groups["tocLink"].Value;
var tocTitle = match.Groups["tocTitle"].Value;
var headerLevel = match.Groups["headerLevel"].Value.Length;
- var uidMatch = UidRegex.Match(tocLink);
+ var uidMatch = UidRegex().Match(tocLink);
string tocDisplayTitle = null;
var displayGrp = match.Groups["displayText"];
@@ -202,19 +204,20 @@ public override ParseState Apply(ParseState state, Match match)
/// 1.
/// 2.
///
- internal sealed class TopicXrefAutoLinkTocParseRule : ParseRule
+ internal sealed partial class TopicXrefAutoLinkTocParseRule : ParseRule
{
- public static readonly Regex XrefAutoLinkTocRegex =
- new($@"^(#+)(?: |\t)*{XrefAutoLinkRegexString}( |\t)*#*( |\t)*(\n|$)", RegexOptions.Compiled);
- public static readonly Regex XrefAutoLinkWithQuoteTocRegex =
- new($@"^(#+)(?: |\t)*{XrefAutoLinkRegexWithQuoteString}( |\t)*#*( |\t)*(\n|$)", RegexOptions.Compiled);
+ [GeneratedRegex($@"^(#+)(?: |\t)*{XrefAutoLinkRegexString}( |\t)*#*( |\t)*(\n|$)")]
+ private static partial Regex XrefAutoLinkTocRegex();
+
+ [GeneratedRegex($@"^(#+)(?: |\t)*{XrefAutoLinkRegexWithQuoteString}( |\t)*#*( |\t)*(\n|$)")]
+ private static partial Regex XrefAutoLinkWithQuoteTocRegex();
public override Match Match(string text)
{
- var match = XrefAutoLinkWithQuoteTocRegex.Match(text);
+ var match = XrefAutoLinkWithQuoteTocRegex().Match(text);
if (match.Length == 0)
{
- match = XrefAutoLinkTocRegex.Match(text);
+ match = XrefAutoLinkTocRegex().Match(text);
}
return match;
@@ -226,19 +229,20 @@ public override ParseState Apply(ParseState state, Match match)
}
}
- internal sealed class TopicXrefShortcutTocParseRule : ParseRule
+ internal sealed partial class TopicXrefShortcutTocParseRule : ParseRule
{
- public static readonly Regex XrefShortcutTocRegex =
- new($@"^(#+)(?: |\t)*{XrefShortcutRegexString}( |\t)*#*( |\t)*(\n|$)", RegexOptions.Compiled);
- public static readonly Regex XrefShortcutTocWithQuoteTocRegex =
- new($@"^(#+)(?: |\t)*{XrefShortcutRegexWithQuoteString}( |\t)*#*( |\t)*(\n|$)", RegexOptions.Compiled);
+ [GeneratedRegex($@"^(#+)(?: |\t)*{XrefShortcutRegexString}( |\t)*#*( |\t)*(\n|$)")]
+ private static partial Regex XrefShortcutTocRegex();
+
+ [GeneratedRegex($@"^(#+)(?: |\t)*{XrefShortcutRegexWithQuoteString}( |\t)*#*( |\t)*(\n|$)")]
+ private static partial Regex XrefShortcutTocWithQuoteTocRegex();
public override Match Match(string text)
{
- var match = XrefShortcutTocWithQuoteTocRegex.Match(text);
+ var match = XrefShortcutTocWithQuoteTocRegex().Match(text);
if (match.Length == 0)
{
- match = XrefShortcutTocRegex.Match(text);
+ match = XrefShortcutTocRegex().Match(text);
}
return match;
@@ -250,12 +254,12 @@ public override ParseState Apply(ParseState state, Match match)
}
}
- internal sealed class ExternalLinkTocParseRule : ParseRule
+ internal sealed partial class ExternalLinkTocParseRule : ParseRule
{
- public static readonly Regex TocRegex =
- new(@"^(?#+)(( |\t)*)\[(?.+?)\]\((?(http[s]?://).*?)\)(?:( |\t)+#*)?( |\t)*(\n|$)", RegexOptions.Compiled);
+ [GeneratedRegex(@"^(?#+)(( |\t)*)\[(?.+?)\]\((?(http[s]?://).*?)\)(?:( |\t)+#*)?( |\t)*(\n|$)")]
+ private static partial Regex TocRegex();
- public override Match Match(string text) => TocRegex.Match(text);
+ public override Match Match(string text) => TocRegex().Match(text);
public override ParseState Apply(ParseState state, Match match)
{
@@ -263,12 +267,12 @@ public override ParseState Apply(ParseState state, Match match)
}
}
- internal sealed class ContainerParseRule : ParseRule
+ internal sealed partial class ContainerParseRule : ParseRule
{
- public static readonly Regex ContainerRegex =
- new(@"^(?#+)(( |\t)*)(?.+?)(?:( |\t)+#*)?( |\t)*(\n|$)", RegexOptions.Compiled);
+ [GeneratedRegex(@"^(?#+)(( |\t)*)(?.+?)(?:( |\t)+#*)?( |\t)*(\n|$)")]
+ private static partial Regex ContainerRegex();
- public override Match Match(string text) => ContainerRegex.Match(text);
+ public override Match Match(string text) => ContainerRegex().Match(text);
public override ParseState Apply(ParseState state, Match match)
{
@@ -276,22 +280,22 @@ public override ParseState Apply(ParseState state, Match match)
}
}
- internal sealed class CommentParseRule : ParseRule
+ internal sealed partial class CommentParseRule : ParseRule
{
- public static readonly Regex CommentRegex =
- new(@"^\s*\s*(\n|$)", RegexOptions.Compiled);
+ [GeneratedRegex(@"^\s*\s*(\n|$)")]
+ private static partial Regex CommentRegex();
- public override Match Match(string text) => CommentRegex.Match(text);
+ public override Match Match(string text) => CommentRegex().Match(text);
public override ParseState Apply(ParseState state, Match match) => state;
}
- internal sealed class WhitespaceParseRule : ParseRule
+ internal sealed partial class WhitespaceParseRule : ParseRule
{
- public static readonly Regex WhitespaceRegex =
- new(@"^\s*(\n|$)", RegexOptions.Compiled);
+ [GeneratedRegex(@"^\s*(\n|$)")]
+ private static partial Regex WhitespaceRegex();
- public override Match Match(string text) => WhitespaceRegex.Match(text);
+ public override Match Match(string text) => WhitespaceRegex().Match(text);
public override ParseState Apply(ParseState state, Match match) => state;
}
diff --git a/src/Docfx.Build/TableOfContents/TocDocumentProcessor.cs b/src/Docfx.Build/TableOfContents/TocDocumentProcessor.cs
index 79172edce58..cc8d371c1d0 100644
--- a/src/Docfx.Build/TableOfContents/TocDocumentProcessor.cs
+++ b/src/Docfx.Build/TableOfContents/TocDocumentProcessor.cs
@@ -91,7 +91,7 @@ private void UpdateTocItemHref(TocItemViewModel toc, FileModel model, IDocumentB
toc.OriginalTopicHref = null;
includedFrom = toc.IncludedFrom ?? includedFrom;
- if (toc.Items is {Count: > 0})
+ if (toc.Items is { Count: > 0 })
{
foreach (var item in toc.Items)
{
diff --git a/src/Docfx.Build/TableOfContents/TocResolver.cs b/src/Docfx.Build/TableOfContents/TocResolver.cs
index 6ea34f31a3b..9c2f43e4944 100644
--- a/src/Docfx.Build/TableOfContents/TocResolver.cs
+++ b/src/Docfx.Build/TableOfContents/TocResolver.cs
@@ -11,7 +11,7 @@ namespace Docfx.Build.TableOfContents;
class TocResolver
{
private readonly Dictionary _collection;
- private readonly Dictionary _notInProjectTocCache = new();
+ private readonly Dictionary _notInProjectTocCache = [];
public TocResolver(Dictionary collection)
{
@@ -122,7 +122,7 @@ private TocItemInfo ResolveItemCore(TocItemInfo wrapper, Stack stac
{
case HrefType.AbsolutePath:
case HrefType.RelativeFile:
- if (item.Items is {Count: > 0})
+ if (item.Items is { Count: > 0 })
{
item.Items = new List(from i in item.Items
select ResolveItem(new TocItemInfo(file, i), stack) into r
diff --git a/src/Docfx.Build/TableOfContents/TocRestructureUtility.cs b/src/Docfx.Build/TableOfContents/TocRestructureUtility.cs
index ead7255750e..464b9ea8f67 100644
--- a/src/Docfx.Build/TableOfContents/TocRestructureUtility.cs
+++ b/src/Docfx.Build/TableOfContents/TocRestructureUtility.cs
@@ -15,7 +15,7 @@ public static void Restructure(TocItemViewModel toc, IList
{
return;
}
- RestructureCore(toc, new(), restructures);
+ RestructureCore(toc, [], restructures);
}
private static void RestructureCore(TocItemViewModel item, List items, IList restructures)
@@ -28,7 +28,7 @@ private static void RestructureCore(TocItemViewModel item, List 0})
+ if (item.Items is { Count: > 0 })
{
var parentItems = new List(item.Items);
foreach (var i in item.Items)
@@ -91,7 +91,7 @@ private static void RestructureItem(TocItemViewModel item, List GetTemplateDirectories(IEnumerable names)
public void ProcessTheme(string outputDirectory, bool overwrite)
{
- if (_themes is {Count: > 0})
+ if (_themes is { Count: > 0 })
{
TryExportResourceFiles(_themes, outputDirectory, overwrite);
Logger.LogInfo($"Theme(s) {_themes.ToDelimitedString()} applied.");
@@ -124,7 +124,7 @@ private static void Copy(Action streamHandler, string filePath, bool ove
try
{
var subfolder = Path.GetDirectoryName(filePath);
- if (!string.IsNullOrEmpty(subfolder) && !Directory.Exists(subfolder))
+ if (!string.IsNullOrEmpty(subfolder))
{
Directory.CreateDirectory(subfolder);
}
diff --git a/src/Docfx.Build/TemplateProcessors/TemplateModelTransformer.cs b/src/Docfx.Build/TemplateProcessors/TemplateModelTransformer.cs
index 57483f41930..59050dce421 100644
--- a/src/Docfx.Build/TemplateProcessors/TemplateModelTransformer.cs
+++ b/src/Docfx.Build/TemplateProcessors/TemplateModelTransformer.cs
@@ -5,7 +5,6 @@
using Docfx.Common;
using Docfx.Plugins;
using HtmlAgilityPack;
-using Newtonsoft.Json;
namespace Docfx.Build.Engine;
@@ -265,7 +264,7 @@ private static string ExportModel(object model, string modelFileRelativePath, Ex
private void TransformDocument(string result, string extension, IDocumentBuildContext context, string destFilePath, ManifestItem manifestItem, out List unresolvedXRefs)
{
- unresolvedXRefs = new List();
+ unresolvedXRefs = [];
using (var stream = EnvironmentContext.FileAbstractLayer.Create(destFilePath))
{
using var sw = new StreamWriter(stream);
@@ -293,7 +292,7 @@ private void TransformHtml(IDocumentBuildContext context, string html, string so
HtmlDocument document = new();
document.LoadHtml(html);
- unresolvedXRefs = new List();
+ unresolvedXRefs = [];
TransformXrefInHtml(context, sourceFilePath, destFilePath, document.DocumentNode, unresolvedXRefs);
TransformLinkInHtml(context, sourceFilePath, destFilePath, document.DocumentNode);
diff --git a/src/Docfx.Build/TemplateProcessors/ViewRenderers/MustacheTemplateRenderer.cs b/src/Docfx.Build/TemplateProcessors/ViewRenderers/MustacheTemplateRenderer.cs
index 2d70a24fcde..758fe10a602 100644
--- a/src/Docfx.Build/TemplateProcessors/ViewRenderers/MustacheTemplateRenderer.cs
+++ b/src/Docfx.Build/TemplateProcessors/ViewRenderers/MustacheTemplateRenderer.cs
@@ -7,13 +7,18 @@
namespace Docfx.Build.Engine;
-internal class MustacheTemplateRenderer : ITemplateRenderer
+internal partial class MustacheTemplateRenderer : ITemplateRenderer
{
public const string Extension = ".tmpl";
- private static readonly Regex IncludeRegex = new(@"{{\s*!\s*include\s*\(:?(:?['""]?)\s*(?(.+?))\1\s*\)\s*}}", RegexOptions.Compiled | RegexOptions.IgnoreCase);
- private static readonly Regex MasterPageRegex = new(@"{{\s*!\s*master\s*\(:?(:?['""]?)\s*(?(.+?))\1\s*\)\s*}}\s*\n?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
- private static readonly Regex MasterPageBodyRegex = new(@"{{\s*!\s*body\s*}}\s*\n?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
+ [GeneratedRegex(@"{{\s*!\s*include\s*\(:?(:?['""]?)\s*(?(.+?))\1\s*\)\s*}}", RegexOptions.IgnoreCase | RegexOptions.Compiled, "en-AU")]
+ private static partial Regex IncludeRegex();
+
+ [GeneratedRegex(@"{{\s*!\s*master\s*\(:?(:?['""]?)\s*(?(.+?))\1\s*\)\s*}}\s*\n?", RegexOptions.IgnoreCase | RegexOptions.Compiled, "en-AU")]
+ private static partial Regex MasterPageRegex();
+
+ [GeneratedRegex(@"{{\s*!\s*body\s*}}\s*\n?", RegexOptions.IgnoreCase | RegexOptions.Compiled, "en-AU")]
+ private static partial Regex MasterPageBodyRegex();
private readonly ResourceFileReader _reader;
private readonly IStubbleRenderer _renderer;
@@ -37,7 +42,7 @@ public MustacheTemplateRenderer(ResourceFileReader reader, ResourceInfo info, st
})
.Build();
- var processedTemplate = ParseTemplateHelper.ExpandMasterPage(reader, info, MasterPageRegex, MasterPageBodyRegex);
+ var processedTemplate = ParseTemplateHelper.ExpandMasterPage(reader, info, MasterPageRegex(), MasterPageBodyRegex());
_template = processedTemplate;
@@ -63,7 +68,7 @@ public string Render(object model)
///
private IEnumerable ExtractDependencyResourceNames(string template)
{
- foreach (Match match in IncludeRegex.Matches(template))
+ foreach (Match match in IncludeRegex().Matches(template))
{
var filePath = match.Groups["file"].Value;
foreach (var name in ParseTemplateHelper.GetResourceName(filePath, Path, _reader))
diff --git a/src/Docfx.Build/TemplateProcessors/ViewRenderers/ParseTemplateHelper.cs b/src/Docfx.Build/TemplateProcessors/ViewRenderers/ParseTemplateHelper.cs
index a8585fef5a6..48330028fdd 100644
--- a/src/Docfx.Build/TemplateProcessors/ViewRenderers/ParseTemplateHelper.cs
+++ b/src/Docfx.Build/TemplateProcessors/ViewRenderers/ParseTemplateHelper.cs
@@ -7,9 +7,10 @@
namespace Docfx.Build.Engine;
-internal static class ParseTemplateHelper
+internal static partial class ParseTemplateHelper
{
- private static readonly Regex IsRegexPatternRegex = new(@"^\s*/(.*)/\s*$", RegexOptions.Compiled);
+ [GeneratedRegex(@"^\s*/(.*)/\s*$")]
+ private static partial Regex IsRegexPatternRegex();
public static string ExpandMasterPage(ResourceFileReader reader, ResourceInfo info, Regex masterRegex, Regex bodyRegex)
{
@@ -72,7 +73,7 @@ public static IEnumerable GetResourceName(string file, string templateNa
file = file.Substring(2);
}
- var regexPatternMatch = IsRegexPatternRegex.Match(file);
+ var regexPatternMatch = IsRegexPatternRegex().Match(file);
if (regexPatternMatch.Groups.Count > 1)
{
file = regexPatternMatch.Groups[1].Value;
diff --git a/src/Docfx.Build/XRefMaps/XRefArchive.cs b/src/Docfx.Build/XRefMaps/XRefArchive.cs
index 893dbae35aa..b63ad979c3c 100644
--- a/src/Docfx.Build/XRefMaps/XRefArchive.cs
+++ b/src/Docfx.Build/XRefMaps/XRefArchive.cs
@@ -71,7 +71,7 @@ public static XRefArchive Open(string file, XRefArchiveMode mode)
}
fs = File.Create(file);
archive = new ZipArchive(fs, ZipArchiveMode.Update);
- entries = new List();
+ entries = [];
break;
default:
throw new ArgumentOutOfRangeException(nameof(mode));
@@ -299,7 +299,7 @@ public void Dispose()
bool IXRefContainer.IsEmbeddedRedirections => true;
- IEnumerable IXRefContainer.GetRedirections() => Enumerable.Empty();
+ IEnumerable IXRefContainer.GetRedirections() => [];
public IXRefContainerReader GetReader()
{
diff --git a/src/Docfx.Build/XRefMaps/XRefArchiveBuilder.cs b/src/Docfx.Build/XRefMaps/XRefArchiveBuilder.cs
index 61d2f99d36e..354e90d6fcc 100644
--- a/src/Docfx.Build/XRefMaps/XRefArchiveBuilder.cs
+++ b/src/Docfx.Build/XRefMaps/XRefArchiveBuilder.cs
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.Threading;
using Docfx.Common;
namespace Docfx.Build.Engine;
@@ -53,7 +52,7 @@ private async Task DownloadCoreAsync(Uri uri, XRefArchive xa, Cancellati
// Sort is not needed if `map.Sorted == true`.
// But there are some xrefmap files that is not propery sorted by using InvariantCulture.
// (e.g. Unity xrefmap that maintained by community)
- if (map.References is {Count: > 0})
+ if (map.References is { Count: > 0 })
{
map.References.Sort(XRefSpecUidComparer.Instance);
map.Sorted = true;
diff --git a/src/Docfx.Build/XRefMaps/XRefCollection.cs b/src/Docfx.Build/XRefMaps/XRefCollection.cs
index 357a313bb99..b1c3eabf1df 100644
--- a/src/Docfx.Build/XRefMaps/XRefCollection.cs
+++ b/src/Docfx.Build/XRefMaps/XRefCollection.cs
@@ -29,8 +29,8 @@ public Task GetReaderAsync(string baseFolder, IReadOnlyLis
private sealed class ReaderCreator
{
private readonly ImmutableList _uris;
- private readonly HashSet _set = new();
- private readonly Dictionary, Uri> _processing = new();
+ private readonly HashSet _set = [];
+ private readonly Dictionary, Uri> _processing = [];
private readonly XRefMapDownloader _downloader;
public ReaderCreator(ImmutableList uris, int maxParallelism, string baseFolder, IReadOnlyList fallbackFolders)
diff --git a/src/Docfx.Build/XRefMaps/XRefMap.cs b/src/Docfx.Build/XRefMaps/XRefMap.cs
index f376109837a..1699465440f 100644
--- a/src/Docfx.Build/XRefMaps/XRefMap.cs
+++ b/src/Docfx.Build/XRefMaps/XRefMap.cs
@@ -61,7 +61,7 @@ public class XRefMap : IXRefContainer
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Others { get; set; } = new();
+ public Dictionary Others { get; set; } = [];
public void Sort()
{
diff --git a/src/Docfx.Build/XRefMaps/XRefMapDownloader.cs b/src/Docfx.Build/XRefMaps/XRefMapDownloader.cs
index 5a83901afd8..340df7e7729 100644
--- a/src/Docfx.Build/XRefMaps/XRefMapDownloader.cs
+++ b/src/Docfx.Build/XRefMaps/XRefMapDownloader.cs
@@ -1,8 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System;
-using System.Diagnostics;
using System.IO.Compression;
using System.Net;
using Docfx.Common;
@@ -134,7 +132,7 @@ private static async ValueTask ReadLocalFileAsync(string filePat
{
using var reader = new StreamReader(stream);
return YamlUtility.Deserialize(reader);
- };
+ }
}
}
@@ -147,8 +145,7 @@ private static async ValueTask ReadLocalFileAsync(string filePat
case ".yml":
default:
{
- using var sr = File.OpenText(filePath);
- return YamlUtility.Deserialize(sr);
+ return YamlUtility.Deserialize(filePath);
}
}
}
diff --git a/src/Docfx.Common/CompositeDictionary.cs b/src/Docfx.Common/CompositeDictionary.cs
index 5415854b216..01b967a6561 100644
--- a/src/Docfx.Common/CompositeDictionary.cs
+++ b/src/Docfx.Common/CompositeDictionary.cs
@@ -192,7 +192,7 @@ private sealed class Entry
public sealed class Builder
{
- private readonly List _entries = new();
+ private readonly List _entries = [];
internal Builder() { }
diff --git a/src/Docfx.Common/FileAbstractLayer/EmptyFileReader.cs b/src/Docfx.Common/FileAbstractLayer/EmptyFileReader.cs
index 07540ab2245..fe54c58038c 100644
--- a/src/Docfx.Common/FileAbstractLayer/EmptyFileReader.cs
+++ b/src/Docfx.Common/FileAbstractLayer/EmptyFileReader.cs
@@ -13,7 +13,7 @@ private EmptyFileReader()
public PathMapping? FindFile(RelativePath file) => null;
- public IEnumerable EnumerateFiles() => Enumerable.Empty();
+ public IEnumerable EnumerateFiles() => [];
public string GetExpectedPhysicalPath(RelativePath file) => null;
}
diff --git a/src/Docfx.Common/FileAbstractLayer/FileWriterBase.cs b/src/Docfx.Common/FileAbstractLayer/FileWriterBase.cs
index 48ec883686a..f68ccb4567a 100644
--- a/src/Docfx.Common/FileAbstractLayer/FileWriterBase.cs
+++ b/src/Docfx.Common/FileAbstractLayer/FileWriterBase.cs
@@ -28,9 +28,7 @@ protected internal static void EnsureFolder(string folder)
{
return;
}
- if (!Directory.Exists(folder))
- {
- Directory.CreateDirectory(folder);
- }
+
+ Directory.CreateDirectory(folder);
}
}
diff --git a/src/Docfx.Common/FileMapping.cs b/src/Docfx.Common/FileMapping.cs
index 451e2288289..9b89ecf8a7a 100644
--- a/src/Docfx.Common/FileMapping.cs
+++ b/src/Docfx.Common/FileMapping.cs
@@ -28,7 +28,7 @@ namespace Docfx;
[System.Text.Json.Serialization.JsonConverter(typeof(FileMappingConverter.SystemTextJsonConverter))]
public class FileMapping
{
- private readonly List _items = new();
+ private readonly List _items = [];
///
/// Flags to distinguish items are expanded or not.
diff --git a/src/Docfx.Common/Git/GitUtility.cs b/src/Docfx.Common/Git/GitUtility.cs
index dd3368e15ef..1901dab8e2e 100644
--- a/src/Docfx.Common/Git/GitUtility.cs
+++ b/src/Docfx.Common/Git/GitUtility.cs
@@ -48,7 +48,7 @@ record Repo(string path, string url, string branch);
};
}
- public static string? RawContentUrlToContentUrl(string rawUrl)
+ public static string RawContentUrlToContentUrl(string rawUrl)
{
// GitHub
var url = GitHubUserContentRegex().Replace(rawUrl, string.IsNullOrEmpty(s_branch) ? "https://github.com/$1/$2/blob/$3/$4" : $"https://github.com/$1/$2/blob/{s_branch}/$4");
diff --git a/src/Docfx.Common/Json/FileMappingConverter.SystemTextJson.cs b/src/Docfx.Common/Json/FileMappingConverter.SystemTextJson.cs
index 286cded2d1e..fb7da65e757 100644
--- a/src/Docfx.Common/Json/FileMappingConverter.SystemTextJson.cs
+++ b/src/Docfx.Common/Json/FileMappingConverter.SystemTextJson.cs
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -13,7 +12,7 @@ internal partial class FileMappingConverter
{
internal class SystemTextJsonConverter : JsonConverter
{
- public override FileMapping? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ public override FileMapping Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
diff --git a/src/Docfx.Common/Json/FileMappingConverter.cs b/src/Docfx.Common/Json/FileMappingConverter.cs
index 65a4cd2dbe8..d0e9d03e734 100644
--- a/src/Docfx.Common/Json/FileMappingConverter.cs
+++ b/src/Docfx.Common/Json/FileMappingConverter.cs
@@ -1,9 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
namespace Docfx;
internal partial class FileMappingConverter
diff --git a/src/Docfx.Common/Json/JsonUtility.cs b/src/Docfx.Common/Json/JsonUtility.cs
index b0c4d7ca1ac..de00f591944 100644
--- a/src/Docfx.Common/Json/JsonUtility.cs
+++ b/src/Docfx.Common/Json/JsonUtility.cs
@@ -1,13 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.Collections.Generic;
-using System.IO;
-using System.Reflection.PortableExecutable;
-using System.Text.RegularExpressions;
-using Docfx.Plugins;
using Newtonsoft.Json;
-using YamlDotNet.Serialization;
namespace Docfx.Common;
diff --git a/src/Docfx.Common/Json/NewtonsoftJson/ConvertToObjectHelper.cs b/src/Docfx.Common/Json/NewtonsoftJson/ConvertToObjectHelper.cs
index 7e05c239676..6605967af4a 100644
--- a/src/Docfx.Common/Json/NewtonsoftJson/ConvertToObjectHelper.cs
+++ b/src/Docfx.Common/Json/NewtonsoftJson/ConvertToObjectHelper.cs
@@ -76,12 +76,12 @@ public static object ConvertStrongTypeToJObject(object raw)
public static object ConvertExpandoObjectToObject(object raw)
{
- return ConvertExpandoObjectToObjectCore(raw, new Dictionary());
+ return ConvertExpandoObjectToObjectCore(raw, []);
}
public static object ConvertToDynamic(object obj)
{
- return ConvertToDynamicCore(obj, new Dictionary());
+ return ConvertToDynamicCore(obj, []);
}
private static object ConvertExpandoObjectToObjectCore(object obj, Dictionary cache)
diff --git a/src/Docfx.Common/Json/System.Text.Json/SystemTextJsonUtility.cs b/src/Docfx.Common/Json/System.Text.Json/SystemTextJsonUtility.cs
index e16fa005d79..1b3fd2d2aaa 100644
--- a/src/Docfx.Common/Json/System.Text.Json/SystemTextJsonUtility.cs
+++ b/src/Docfx.Common/Json/System.Text.Json/SystemTextJsonUtility.cs
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
diff --git a/src/Docfx.Common/Loggers/CompositeLogListener.cs b/src/Docfx.Common/Loggers/CompositeLogListener.cs
index 680c0618568..d6ed964219c 100644
--- a/src/Docfx.Common/Loggers/CompositeLogListener.cs
+++ b/src/Docfx.Common/Loggers/CompositeLogListener.cs
@@ -6,7 +6,7 @@ namespace Docfx.Common;
public class CompositeLogListener : ILoggerListener
{
private readonly object _sync = new();
- private readonly List _listeners = new();
+ private readonly List _listeners = [];
public CompositeLogListener()
{
diff --git a/src/Docfx.Common/Path/PathUtility.cs b/src/Docfx.Common/Path/PathUtility.cs
index 08437417e0a..e4673633f12 100644
--- a/src/Docfx.Common/Path/PathUtility.cs
+++ b/src/Docfx.Common/Path/PathUtility.cs
@@ -5,9 +5,11 @@
namespace Docfx.Common;
-public static class PathUtility
+public static partial class PathUtility
{
- private static readonly Regex UriWithProtocol = new(@"^\w{2,}\:", RegexOptions.Compiled);
+
+ [GeneratedRegex(@"^\w{2,}\:")]
+ private static partial Regex UriWithProtocol();
private static readonly char[] AdditionalInvalidChars = ":*".ToArray();
public static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars().Concat(AdditionalInvalidChars).ToArray();
@@ -98,7 +100,7 @@ public static bool IsRelativePath(string path)
return false;
}
- if (UriWithProtocol.IsMatch(path))
+ if (UriWithProtocol().IsMatch(path))
{
return false;
}
diff --git a/src/Docfx.Common/Path/RelativePath.cs b/src/Docfx.Common/Path/RelativePath.cs
index be23480f3a3..e1961551f48 100644
--- a/src/Docfx.Common/Path/RelativePath.cs
+++ b/src/Docfx.Common/Path/RelativePath.cs
@@ -54,7 +54,7 @@ public static RelativePath FromUrl(string path)
public static bool IsRelativePath(string path)
{
// TODO : to merge with the PathUtility one
- return path is {Length: > 0} &&
+ return path is { Length: > 0 } &&
path[0] != '/' &&
path[0] != '\\' &&
path.IndexOfAny(PathUtility.InvalidPathChars) == -1;
diff --git a/src/Docfx.Common/ResourcePools/ResourcePoolManager.cs b/src/Docfx.Common/ResourcePools/ResourcePoolManager.cs
index 7c4a7ef68cf..d435b6a8cda 100644
--- a/src/Docfx.Common/ResourcePools/ResourcePoolManager.cs
+++ b/src/Docfx.Common/ResourcePools/ResourcePoolManager.cs
@@ -8,7 +8,7 @@ public class ResourcePoolManager
where TResource : class
{
private readonly object _syncRoot = new();
- private readonly List _resources = new();
+ private readonly List _resources = [];
private readonly Stack _stack = new();
private readonly Func _creator;
private readonly int _maxResourceCount;
diff --git a/src/Docfx.DataContracts.Common/ExternalReferences/ExternalReferencePackageReader.cs b/src/Docfx.DataContracts.Common/ExternalReferences/ExternalReferencePackageReader.cs
index d1e0f1ebdac..a5443e00417 100644
--- a/src/Docfx.DataContracts.Common/ExternalReferences/ExternalReferencePackageReader.cs
+++ b/src/Docfx.DataContracts.Common/ExternalReferences/ExternalReferencePackageReader.cs
@@ -74,7 +74,7 @@ private static Dictionary> GetUidEntryMap(ZipArchive zip)
{
if (!uidEntryMap.TryGetValue(entry.Uid, out List list))
{
- list = new List();
+ list = [];
uidEntryMap[entry.Uid] = list;
}
list.Add(entry.FullName);
diff --git a/src/Docfx.DataContracts.Common/ReferenceViewModel.cs b/src/Docfx.DataContracts.Common/ReferenceViewModel.cs
index 7810640f850..96ca044f8de 100644
--- a/src/Docfx.DataContracts.Common/ReferenceViewModel.cs
+++ b/src/Docfx.DataContracts.Common/ReferenceViewModel.cs
@@ -50,7 +50,7 @@ public class ReferenceViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Name)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList NameInDevLangs { get; private set; } = new();
+ public SortedList NameInDevLangs { get; private set; } = [];
[YamlMember(Alias = Constants.PropertyName.NameWithType)]
[JsonProperty(Constants.PropertyName.NameWithType)]
@@ -60,7 +60,7 @@ public class ReferenceViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.NameWithType)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList NameWithTypeInDevLangs { get; private set; } = new();
+ public SortedList NameWithTypeInDevLangs { get; private set; } = [];
[YamlMember(Alias = Constants.PropertyName.FullName)]
[JsonProperty(Constants.PropertyName.FullName)]
@@ -70,17 +70,17 @@ public class ReferenceViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.FullName)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList FullNameInDevLangs { get; private set; } = new();
+ public SortedList FullNameInDevLangs { get; private set; } = [];
[ExtensibleMember(Constants.ExtensionMemberPrefix.Spec)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> Specs { get; private set; } = new();
+ public SortedList> Specs { get; private set; } = [];
[ExtensibleMember]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public Dictionary Additional { get; private set; } = new();
+ public Dictionary Additional { get; private set; } = [];
[EditorBrowsable(EditorBrowsableState.Never)]
[YamlIgnore]
diff --git a/src/Docfx.DataContracts.Common/TocItemViewModel.cs b/src/Docfx.DataContracts.Common/TocItemViewModel.cs
index 81937c34265..3611d348b48 100644
--- a/src/Docfx.DataContracts.Common/TocItemViewModel.cs
+++ b/src/Docfx.DataContracts.Common/TocItemViewModel.cs
@@ -116,7 +116,7 @@ public class TocItemViewModel
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
[System.Text.Json.Serialization.JsonPropertyName("__metadata__")]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
[EditorBrowsable(EditorBrowsableState.Never)]
[YamlIgnore]
diff --git a/src/Docfx.DataContracts.RestApi/RestApiItemViewModelBase.cs b/src/Docfx.DataContracts.RestApi/RestApiItemViewModelBase.cs
index 71ebce5c825..2b1900799e2 100644
--- a/src/Docfx.DataContracts.RestApi/RestApiItemViewModelBase.cs
+++ b/src/Docfx.DataContracts.RestApi/RestApiItemViewModelBase.cs
@@ -58,5 +58,5 @@ public class RestApiItemViewModelBase : IOverwriteDocumentViewModel
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.RestApi/RestApiParameterViewModel.cs b/src/Docfx.DataContracts.RestApi/RestApiParameterViewModel.cs
index 2211bbc46fc..2407dad082a 100644
--- a/src/Docfx.DataContracts.RestApi/RestApiParameterViewModel.cs
+++ b/src/Docfx.DataContracts.RestApi/RestApiParameterViewModel.cs
@@ -25,5 +25,5 @@ public class RestApiParameterViewModel
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.RestApi/RestApiResponseViewModel.cs b/src/Docfx.DataContracts.RestApi/RestApiResponseViewModel.cs
index a2fe4118d8e..b8823d01ef9 100644
--- a/src/Docfx.DataContracts.RestApi/RestApiResponseViewModel.cs
+++ b/src/Docfx.DataContracts.RestApi/RestApiResponseViewModel.cs
@@ -35,5 +35,5 @@ public class RestApiResponseViewModel
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.RestApi/RestApiTagViewModel.cs b/src/Docfx.DataContracts.RestApi/RestApiTagViewModel.cs
index 5d095f314a6..b76ebe77298 100644
--- a/src/Docfx.DataContracts.RestApi/RestApiTagViewModel.cs
+++ b/src/Docfx.DataContracts.RestApi/RestApiTagViewModel.cs
@@ -48,5 +48,5 @@ public class RestApiTagViewModel : IOverwriteDocumentViewModel
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.UniversalReference/ApiParameter.cs b/src/Docfx.DataContracts.UniversalReference/ApiParameter.cs
index 2f367ac46ca..ec59c309591 100644
--- a/src/Docfx.DataContracts.UniversalReference/ApiParameter.cs
+++ b/src/Docfx.DataContracts.UniversalReference/ApiParameter.cs
@@ -48,5 +48,5 @@ public class ApiParameter
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.UniversalReference/ArgumentInfo.cs b/src/Docfx.DataContracts.UniversalReference/ArgumentInfo.cs
index 09f70d2c4b0..29389305a71 100644
--- a/src/Docfx.DataContracts.UniversalReference/ArgumentInfo.cs
+++ b/src/Docfx.DataContracts.UniversalReference/ArgumentInfo.cs
@@ -26,5 +26,5 @@ public class ArgumentInfo
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.UniversalReference/AttributeInfo.cs b/src/Docfx.DataContracts.UniversalReference/AttributeInfo.cs
index 073941c6215..faf7f48f60d 100644
--- a/src/Docfx.DataContracts.UniversalReference/AttributeInfo.cs
+++ b/src/Docfx.DataContracts.UniversalReference/AttributeInfo.cs
@@ -36,5 +36,5 @@ public class AttributeInfo
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.UniversalReference/ExceptionInfo.cs b/src/Docfx.DataContracts.UniversalReference/ExceptionInfo.cs
index c7fad174904..ca82920f156 100644
--- a/src/Docfx.DataContracts.UniversalReference/ExceptionInfo.cs
+++ b/src/Docfx.DataContracts.UniversalReference/ExceptionInfo.cs
@@ -29,5 +29,5 @@ public class ExceptionInfo
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.UniversalReference/InheritanceTree.cs b/src/Docfx.DataContracts.UniversalReference/InheritanceTree.cs
index 6d4cfc1fa15..467782f95af 100644
--- a/src/Docfx.DataContracts.UniversalReference/InheritanceTree.cs
+++ b/src/Docfx.DataContracts.UniversalReference/InheritanceTree.cs
@@ -32,5 +32,5 @@ public class InheritanceTree
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.UniversalReference/ItemViewModel.cs b/src/Docfx.DataContracts.UniversalReference/ItemViewModel.cs
index 7e81cbf246f..eb27364d38c 100644
--- a/src/Docfx.DataContracts.UniversalReference/ItemViewModel.cs
+++ b/src/Docfx.DataContracts.UniversalReference/ItemViewModel.cs
@@ -46,7 +46,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Parent)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList ParentInDevLangs { get; set; } = new();
+ public SortedList ParentInDevLangs { get; set; } = [];
[YamlMember(Alias = "package")]
[JsonProperty("package")]
@@ -57,7 +57,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember("package" + Constants.PrefixSeparator)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList PackageInDevLangs { get; set; } = new();
+ public SortedList PackageInDevLangs { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.Children)]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
@@ -69,7 +69,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Children)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> ChildrenInDevLangs { get; set; } = new();
+ public SortedList> ChildrenInDevLangs { get; set; } = [];
///
/// item's link URL
@@ -93,7 +93,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Name)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList Names { get; set; } = new();
+ public SortedList Names { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.NameWithType)]
[JsonProperty(Constants.PropertyName.NameWithType)]
@@ -103,7 +103,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.NameWithType)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList NamesWithType { get; set; } = new();
+ public SortedList NamesWithType { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.FullName)]
[JsonProperty(Constants.PropertyName.FullName)]
@@ -113,7 +113,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.FullName)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList FullNames { get; set; } = new();
+ public SortedList FullNames { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.Type)]
[JsonProperty(Constants.PropertyName.Type)]
@@ -131,7 +131,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Source)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList SourceInDevLangs { get; set; } = new();
+ public SortedList SourceInDevLangs { get; set; } = [];
///
/// item's documentation's source detail
@@ -151,7 +151,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Assemblies)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> AssemblyNameListInDevLangs { get; set; } = new();
+ public SortedList> AssemblyNameListInDevLangs { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.Namespace)]
[JsonProperty(Constants.PropertyName.Namespace)]
@@ -162,7 +162,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Namespace)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList NamespaceNameInDevLangs { get; set; } = new();
+ public SortedList NamespaceNameInDevLangs { get; set; } = [];
///
/// item's summary
@@ -213,7 +213,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Overridden)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList OverriddenInDevLangs { get; set; } = new();
+ public SortedList OverriddenInDevLangs { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.Overload)]
[JsonProperty(Constants.PropertyName.Overload)]
@@ -224,7 +224,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Overload)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList OverloadInDevLangs { get; set; } = new();
+ public SortedList OverloadInDevLangs { get; set; } = [];
[YamlMember(Alias = "exceptions")]
[JsonProperty("exceptions")]
@@ -234,7 +234,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Exceptions)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> ExceptionsInDevLangs { get; set; } = new();
+ public SortedList> ExceptionsInDevLangs { get; set; } = [];
[YamlMember(Alias = "seealso")]
[JsonProperty("seealso")]
@@ -278,12 +278,12 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
[UniqueIdentityReference]
- public List InheritanceUidReference => GetInheritanceUidReference(Inheritance)?.ToList() ?? new List();
+ public List InheritanceUidReference => GetInheritanceUidReference(Inheritance)?.ToList() ?? [];
[ExtensibleMember(Constants.ExtensionMemberPrefix.Inheritance)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> InheritanceInDevLangs { get; set; } = new();
+ public SortedList> InheritanceInDevLangs { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.DerivedClasses)]
[MergeOption(MergeOption.Ignore)]
@@ -295,7 +295,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.DerivedClasses)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> DerivedClassesInDevLangs { get; set; } = new();
+ public SortedList> DerivedClassesInDevLangs { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.Implements)]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
@@ -307,7 +307,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Implements)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> ImplementsInDevLangs { get; set; } = new();
+ public SortedList> ImplementsInDevLangs { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.InheritedMembers)]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
@@ -319,7 +319,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.InheritedMembers)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> InheritedMembersInDevLangs { get; set; } = new();
+ public SortedList> InheritedMembersInDevLangs { get; set; } = [];
[YamlMember(Alias = Constants.PropertyName.ExtensionMethods)]
[MergeOption(MergeOption.Ignore)] // todo : merge more children
@@ -331,7 +331,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.ExtensionMethods)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> ExtensionMethodsInDevLangs { get; set; } = new();
+ public SortedList> ExtensionMethodsInDevLangs { get; set; } = [];
///
/// item's conceptual
@@ -352,13 +352,13 @@ public class ItemViewModel : IOverwriteDocumentViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Platform)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList> PlatformInDevLangs { get; set; } = new();
+ public SortedList> PlatformInDevLangs { get; set; } = [];
[ExtensibleMember]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
[System.Text.Json.Serialization.JsonPropertyName("__metadata__")]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
[EditorBrowsable(EditorBrowsableState.Never)]
[YamlIgnore]
diff --git a/src/Docfx.DataContracts.UniversalReference/LinkInfo.cs b/src/Docfx.DataContracts.UniversalReference/LinkInfo.cs
index 7a18c78acfb..a5ad351e19a 100644
--- a/src/Docfx.DataContracts.UniversalReference/LinkInfo.cs
+++ b/src/Docfx.DataContracts.UniversalReference/LinkInfo.cs
@@ -39,7 +39,7 @@ public class LinkInfo
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
public enum LinkType
diff --git a/src/Docfx.DataContracts.UniversalReference/NamedArgumentInfo.cs b/src/Docfx.DataContracts.UniversalReference/NamedArgumentInfo.cs
index 112111323d2..ae2f0b8eed2 100644
--- a/src/Docfx.DataContracts.UniversalReference/NamedArgumentInfo.cs
+++ b/src/Docfx.DataContracts.UniversalReference/NamedArgumentInfo.cs
@@ -31,5 +31,5 @@ public class NamedArgumentInfo
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.UniversalReference/PageViewModel.cs b/src/Docfx.DataContracts.UniversalReference/PageViewModel.cs
index dbe7b09c8d1..efb67ce29c6 100644
--- a/src/Docfx.DataContracts.UniversalReference/PageViewModel.cs
+++ b/src/Docfx.DataContracts.UniversalReference/PageViewModel.cs
@@ -15,14 +15,14 @@ public class PageViewModel
[YamlMember(Alias = "items")]
[JsonProperty("items")]
[JsonPropertyName("items")]
- public List Items { get; set; } = new();
+ public List Items { get; set; } = [];
[YamlMember(Alias = "references")]
[JsonProperty("references")]
[JsonPropertyName("references")]
[UniqueIdentityReferenceIgnore]
[MarkdownContentIgnore]
- public List References { get; set; } = new();
+ public List References { get; set; } = [];
[YamlMember(Alias = "shouldSkipMarkup")]
[JsonProperty("shouldSkipMarkup")]
@@ -32,5 +32,5 @@ public class PageViewModel
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.DataContracts.UniversalReference/SyntaxDetailViewModel.cs b/src/Docfx.DataContracts.UniversalReference/SyntaxDetailViewModel.cs
index 34c11f2770b..6ddde79102f 100644
--- a/src/Docfx.DataContracts.UniversalReference/SyntaxDetailViewModel.cs
+++ b/src/Docfx.DataContracts.UniversalReference/SyntaxDetailViewModel.cs
@@ -47,13 +47,13 @@ public class SyntaxDetailViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Return)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList ReturnInDevLangs { get; set; } = new();
+ public SortedList ReturnInDevLangs { get; set; } = [];
[ExtensibleMember]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
[System.Text.Json.Serialization.JsonPropertyName("__metadata__")]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
[EditorBrowsable(EditorBrowsableState.Never)]
[YamlIgnore]
diff --git a/src/Docfx.Dotnet/Docfx.Dotnet.csproj b/src/Docfx.Dotnet/Docfx.Dotnet.csproj
index 9dbc6ec171a..d28ca0fb4ae 100644
--- a/src/Docfx.Dotnet/Docfx.Dotnet.csproj
+++ b/src/Docfx.Dotnet/Docfx.Dotnet.csproj
@@ -16,10 +16,6 @@
-
-
-
-
@@ -32,7 +28,6 @@
-
diff --git a/src/Docfx.Dotnet/DotnetApiCatalog.ApiPage.cs b/src/Docfx.Dotnet/DotnetApiCatalog.ApiPage.cs
index 7540da20dc2..bf5e65f2c45 100644
--- a/src/Docfx.Dotnet/DotnetApiCatalog.ApiPage.cs
+++ b/src/Docfx.Dotnet/DotnetApiCatalog.ApiPage.cs
@@ -10,7 +10,6 @@
using Docfx.Plugins;
using HtmlAgilityPack;
using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Shared.Extensions;
using OneOf;
#nullable enable
@@ -86,7 +85,7 @@ _ when SymbolHelper.IsConstructor(method) => "Constructor",
_ when SymbolHelper.IsOperator(method) => "Operator",
_ when SymbolHelper.IsMember(method) => "Method",
_ => throw new NotSupportedException($"Unknown method type {method.MethodKind}"),
- }); ;
+ });
foreach (var (s, c) in symbols)
Method((IMethodSymbol)s, c, 2);
break;
@@ -731,7 +730,7 @@ Span Link(string text, string? url)
return string.IsNullOrEmpty(url) ? text : new LinkSpan { text = text, url = url };
}
- XmlComment? Comment(ISymbol symbol, Compilation compilation)
+ XmlComment Comment(ISymbol symbol, Compilation compilation)
{
// Cache XML comment to avoid duplicated parsing and warnings
return commentCache.GetOrAdd(symbol, symbol =>
diff --git a/src/Docfx.Dotnet/DotnetApiCatalog.Compile.cs b/src/Docfx.Dotnet/DotnetApiCatalog.Compile.cs
index 480849fcfcb..e94c3a1a01a 100644
--- a/src/Docfx.Dotnet/DotnetApiCatalog.Compile.cs
+++ b/src/Docfx.Dotnet/DotnetApiCatalog.Compile.cs
@@ -20,9 +20,9 @@ partial class DotnetApiCatalog
{
var files = config.Files?.Select(s => new FileInformation(s))
.GroupBy(f => f.Type)
- .ToDictionary(s => s.Key, s => s.Distinct().ToList()) ?? new();
+ .ToDictionary(s => s.Key, s => s.Distinct().ToList()) ?? [];
- var msbuildProperties = config.MSBuildProperties ?? new Dictionary();
+ var msbuildProperties = config.MSBuildProperties ?? [];
msbuildProperties.TryAdd("Configuration", "Release");
// NOTE:
@@ -122,7 +122,7 @@ await LoadCompilationFromProject(project.AbsolutePath) is { } compilation)
if (hasCompilationError)
{
- return new();
+ return [];
}
if (assemblies.Count <= 0)
diff --git a/src/Docfx.Dotnet/DotnetApiCatalog.ManagedReference.cs b/src/Docfx.Dotnet/DotnetApiCatalog.ManagedReference.cs
index 3612add070e..001182f02b3 100644
--- a/src/Docfx.Dotnet/DotnetApiCatalog.ManagedReference.cs
+++ b/src/Docfx.Dotnet/DotnetApiCatalog.ManagedReference.cs
@@ -66,7 +66,7 @@ void ResolveAndExportYamlMetadata(
YamlUtility.Serialize(tocFilePath, tocViewModel, YamlMime.TableOfContent);
outputFileNames.Add(tocFilePath, 1);
- ApiReferenceViewModel indexer = new();
+ ApiReferenceViewModel indexer = [];
// generate each item's yaml
var members = model.Members;
@@ -142,7 +142,7 @@ bool MergeNode(MetadataItem node)
{
if (node.Type is MemberType.Assembly)
{
- foreach (var item in node.Items ?? new())
+ foreach (var item in node.Items ?? [])
{
MergeNode(item);
}
@@ -152,7 +152,7 @@ bool MergeNode(MetadataItem node)
if (!result.TryGetValue(node.Name, out var existingNode))
{
result.Add(node.Name, node);
- foreach (var item in node.Items ?? new())
+ foreach (var item in node.Items ?? [])
{
MergeNode(item);
}
@@ -161,11 +161,11 @@ bool MergeNode(MetadataItem node)
if (node.Type is MemberType.Namespace or MemberType.Class)
{
- foreach (var item in node.Items ?? new())
+ foreach (var item in node.Items ?? [])
{
if (MergeNode(item))
{
- existingNode.Items ??= new();
+ existingNode.Items ??= [];
existingNode.Items.Add(item);
}
}
diff --git a/src/Docfx.Dotnet/DotnetApiCatalog.Toc.cs b/src/Docfx.Dotnet/DotnetApiCatalog.Toc.cs
index 788da38ef94..d148421e458 100644
--- a/src/Docfx.Dotnet/DotnetApiCatalog.Toc.cs
+++ b/src/Docfx.Dotnet/DotnetApiCatalog.Toc.cs
@@ -37,7 +37,7 @@ class TocNode
internal TocNodeType type;
internal string? id;
internal bool containsLeafNodes;
- internal List<(ISymbol symbol, Compilation compilation)> symbols = new();
+ internal List<(ISymbol symbol, Compilation compilation)> symbols = [];
}
private static List CreateToc(List<(IAssemblySymbol symbol, Compilation compilation)> assemblies, ExtractMetadataConfig config, DotnetApiOptions options)
@@ -61,7 +61,7 @@ IEnumerable CreateToc(ISymbol symbol, Compilation compilation)
switch (symbol)
{
- case INamespaceSymbol {IsGlobalNamespace: true} ns:
+ case INamespaceSymbol { IsGlobalNamespace: true } ns:
foreach (var child in ns.GetNamespaceMembers())
foreach (var item in CreateToc(child, compilation))
yield return item;
@@ -104,7 +104,7 @@ IEnumerable CreateNamespaceToc(INamespaceSymbol ns)
var existingNodeHasNoLeafNode = idExists && !node.containsLeafNodes;
- node.items ??= new();
+ node.items ??= [];
node.symbols.Add((symbol, compilation));
foreach (var child in ns.GetNamespaceMembers())
@@ -164,7 +164,7 @@ IEnumerable CreateNamedTypeToc(INamedTypeSymbol type)
if (config.MemberLayout is MemberLayout.SeparatePages && type.TypeKind is TypeKind.Class or TypeKind.Interface or TypeKind.Struct)
{
- node.items ??= new();
+ node.items ??= [];
foreach (var member in type.GetMembers())
node.items.AddRange(CreateToc(member, compilation));
}
@@ -248,7 +248,7 @@ void InsertCategory(TocNodeType type, string name)
case CategoryLayout.Nested:
{
// Skip when parent node is category node.
- if (parentTocNode is {type: TocNodeType.None})
+ if (parentTocNode is { type: TocNodeType.None })
return;
// If items contains specified type node. Create new TocNode for category. and move related node to child node.
diff --git a/src/Docfx.Dotnet/ExtensionMethods/ISymbolExtensions.cs b/src/Docfx.Dotnet/ExtensionMethods/ISymbolExtensions.cs
new file mode 100644
index 00000000000..5a91077fa80
--- /dev/null
+++ b/src/Docfx.Dotnet/ExtensionMethods/ISymbolExtensions.cs
@@ -0,0 +1,114 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Collections.Immutable;
+using System.Globalization;
+using System.Reflection;
+using System.Reflection.Emit;
+using Microsoft.CodeAnalysis;
+
+#nullable enable
+
+namespace Docfx.Dotnet;
+
+internal static class ISymbolExtensions
+{
+ public static ImmutableArray GetParameters(this ISymbol? symbol)
+ {
+ return symbol switch
+ {
+ IMethodSymbol m => m.Parameters,
+ IPropertySymbol nt => nt.Parameters,
+ _ => [],
+ };
+ }
+
+ public static ImmutableArray GetTypeParameters(this ISymbol? symbol)
+ {
+ return symbol switch
+ {
+ IMethodSymbol m => m.TypeParameters,
+ INamedTypeSymbol nt => nt.TypeParameters,
+ _ => [],
+ };
+ }
+
+ public static DocumentationComment GetDocumentationComment(this ISymbol symbol, Compilation compilation, CultureInfo? preferredCulture = null, bool expandIncludes = false, bool expandInheritdoc = false, CancellationToken cancellationToken = default)
+ {
+ // Gets FullXmlFragment by calling `symbol.DocumentationComment(...).FullXmlFragment`
+ string fullXmlFragment = Helpers.GetFullXmlFragment(symbol, compilation, preferredCulture, expandIncludes, expandInheritdoc, cancellationToken);
+
+ return new DocumentationComment
+ {
+ FullXmlFragment = fullXmlFragment,
+ };
+ }
+
+ internal class DocumentationComment
+ {
+ public required string FullXmlFragment { get; init; }
+ }
+
+ private static class Helpers
+ {
+ ///
+ /// Gets result of `symbol.GetDocumentationComment(args).FullXmlFragment`
+ ///
+ public static string GetFullXmlFragment(ISymbol symbol, Compilation compilation, CultureInfo? preferredCulture = null, bool expandIncludes = false, bool expandInheritdoc = false, CancellationToken cancellationToken = default)
+ => CachedDelegate(symbol, compilation, preferredCulture, expandIncludes, expandInheritdoc, cancellationToken);
+
+ static Helpers()
+ {
+ CachedDelegate = GetDelegate();
+ }
+
+ private delegate string GetFullXmlFragmentDelegate(ISymbol symbol, Compilation compilation, CultureInfo? preferredCulture, bool expandIncludes, bool expandInheritdoc, CancellationToken cancellationToken);
+ private static readonly GetFullXmlFragmentDelegate CachedDelegate;
+
+ private static GetFullXmlFragmentDelegate GetDelegate()
+ {
+ // Gets Microsoft.CodeAnalysis.Workspaces assembly
+ var workspaceAssembly = typeof(Workspace).Assembly;
+
+ // Gets MethodInfo for GetDocumentationComment
+ var type = workspaceAssembly.GetType("Microsoft.CodeAnalysis.Shared.Extensions.ISymbolExtensions", throwOnError: true)!;
+ var methodInfo = type.GetMethod("GetDocumentationComment", BindingFlags.Public | BindingFlags.Static);
+
+ // Gets PropertyInfo for DocumentationComment.
+ var docCommentType = workspaceAssembly.GetType("Microsoft.CodeAnalysis.Shared.Utilities.DocumentationComment", throwOnError: true)!;
+ var propertyInfo = docCommentType.GetProperty("FullXmlFragment", BindingFlags.Instance | BindingFlags.Public)!;
+
+ // Reflection may fail when updating the Microsoft.CodeAnalysis.Workspaces.Common package..
+ if (methodInfo == null || propertyInfo == null)
+ throw new InvalidOperationException("Failed to get required MethodInfo/PropertyInfo via reflection.");
+
+ var dm = new DynamicMethod(string.Empty, returnType: typeof(string), parameterTypes: [
+ typeof(ISymbol),
+ typeof(Compilation),
+ typeof(CultureInfo), // preferredCulture
+ typeof(bool), // expandIncludes
+ typeof(bool), // expandInheritdoc
+ typeof(CancellationToken),
+ ]);
+
+ ILGenerator il = dm.GetILGenerator();
+
+ // call Microsoft.CodeAnalysis.Shared.Extensions.ISymbolExtensions::GetDocumentationComment(args)
+ il.Emit(OpCodes.Ldarg_0); // symbol
+ il.Emit(OpCodes.Ldarg_1); // compilation
+ il.Emit(OpCodes.Ldarg_2); // preferredCulture
+ il.Emit(OpCodes.Ldarg_3); // expandIncludes
+ il.Emit(OpCodes.Ldarg_S, 4); // expandInheritdoc
+ il.Emit(OpCodes.Ldarg_S, 5); // cancellationToken
+ il.EmitCall(OpCodes.Call, methodInfo, null);
+
+ // callvirt DocumentationComment::get_FullXmlFragment()
+ il.EmitCall(OpCodes.Callvirt, propertyInfo.GetMethod!, null);
+
+ // return FullXmlFragment
+ il.Emit(OpCodes.Ret);
+
+ return dm.CreateDelegate();
+ }
+ }
+}
diff --git a/src/Docfx.Dotnet/Filters/AttributeFilterInfo.cs b/src/Docfx.Dotnet/Filters/AttributeFilterInfo.cs
index 63b3ddb6737..20aef537058 100644
--- a/src/Docfx.Dotnet/Filters/AttributeFilterInfo.cs
+++ b/src/Docfx.Dotnet/Filters/AttributeFilterInfo.cs
@@ -14,7 +14,7 @@ internal class AttributeFilterInfo
public List ConstructorArguments { get; set; }
[YamlMember(Alias = "ctorNamedArguments")]
- public Dictionary ConstructorNamedArguments { get; set; } = new();
+ public Dictionary ConstructorNamedArguments { get; set; } = [];
public bool ContainedIn(SymbolFilterData symbol)
{
diff --git a/src/Docfx.Dotnet/Filters/ConfigFilterRule.cs b/src/Docfx.Dotnet/Filters/ConfigFilterRule.cs
index e07f033e7ef..0e12bc07c39 100644
--- a/src/Docfx.Dotnet/Filters/ConfigFilterRule.cs
+++ b/src/Docfx.Dotnet/Filters/ConfigFilterRule.cs
@@ -10,10 +10,10 @@ namespace Docfx.Dotnet;
internal class ConfigFilterRule
{
[YamlMember(Alias = "apiRules")]
- public List ApiRules { get; set; } = new();
+ public List ApiRules { get; set; } = [];
[YamlMember(Alias = "attributeRules")]
- public List AttributeRules { get; set; } = new();
+ public List AttributeRules { get; set; } = [];
public bool CanVisitApi(SymbolFilterData symbol)
{
diff --git a/src/Docfx.Dotnet/Filters/ConfigFilterRuleItemUnion.cs b/src/Docfx.Dotnet/Filters/ConfigFilterRuleItemUnion.cs
index acb2cc10a92..27b4df73f1b 100644
--- a/src/Docfx.Dotnet/Filters/ConfigFilterRuleItemUnion.cs
+++ b/src/Docfx.Dotnet/Filters/ConfigFilterRuleItemUnion.cs
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.Text.Json.Serialization;
using YamlDotNet.Serialization;
namespace Docfx.Dotnet;
diff --git a/src/Docfx.Dotnet/ManagedReference/Models/ItemViewModel.cs b/src/Docfx.Dotnet/ManagedReference/Models/ItemViewModel.cs
index 406d47e1aaa..5ac4b6b9b68 100644
--- a/src/Docfx.Dotnet/ManagedReference/Models/ItemViewModel.cs
+++ b/src/Docfx.Dotnet/ManagedReference/Models/ItemViewModel.cs
@@ -72,7 +72,7 @@ public class ItemViewModel : IOverwriteDocumentViewModel, IItemWithMetadata
[ExtensibleMember(Constants.ExtensionMemberPrefix.Name)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList Names { get; set; } = new();
+ public SortedList Names { get; set; } = [];
[YamlIgnore]
[Newtonsoft.Json.JsonIgnore]
@@ -128,7 +128,7 @@ public string NameForVB
[ExtensibleMember(Constants.ExtensionMemberPrefix.NameWithType)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList NamesWithType { get; set; } = new();
+ public SortedList NamesWithType { get; set; } = [];
[YamlIgnore]
[Newtonsoft.Json.JsonIgnore]
@@ -184,7 +184,7 @@ public string NameWithTypeForVB
[ExtensibleMember(Constants.ExtensionMemberPrefix.FullName)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList FullNames { get; set; } = new();
+ public SortedList FullNames { get; set; } = [];
[YamlIgnore]
[Newtonsoft.Json.JsonIgnore]
@@ -373,7 +373,7 @@ public string FullNameForVB
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
[System.Text.Json.Serialization.JsonPropertyName("__metadata__")]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
[EditorBrowsable(EditorBrowsableState.Never)]
[YamlIgnore]
diff --git a/src/Docfx.Dotnet/ManagedReference/Models/PageViewModel.cs b/src/Docfx.Dotnet/ManagedReference/Models/PageViewModel.cs
index dfe564a80da..a872eacb0de 100644
--- a/src/Docfx.Dotnet/ManagedReference/Models/PageViewModel.cs
+++ b/src/Docfx.Dotnet/ManagedReference/Models/PageViewModel.cs
@@ -14,14 +14,14 @@ public class PageViewModel
[YamlMember(Alias = "items")]
[JsonProperty("items")]
[JsonPropertyName("items")]
- public List Items { get; set; } = new();
+ public List Items { get; set; } = [];
[YamlMember(Alias = "references")]
[JsonProperty("references")]
[JsonPropertyName("references")]
[UniqueIdentityReferenceIgnore]
[MarkdownContentIgnore]
- public List References { get; set; } = new();
+ public List References { get; set; } = [];
[YamlMember(Alias = "shouldSkipMarkup")]
[JsonProperty("shouldSkipMarkup")]
@@ -36,5 +36,5 @@ public class PageViewModel
[ExtensibleMember]
[Newtonsoft.Json.JsonExtensionData]
[System.Text.Json.Serialization.JsonExtensionData]
- public Dictionary Metadata { get; set; } = new();
+ public Dictionary Metadata { get; set; } = [];
}
diff --git a/src/Docfx.Dotnet/ManagedReference/Models/SyntaxDetailViewModel.cs b/src/Docfx.Dotnet/ManagedReference/Models/SyntaxDetailViewModel.cs
index 8aa49b39a22..57d78edeb93 100644
--- a/src/Docfx.Dotnet/ManagedReference/Models/SyntaxDetailViewModel.cs
+++ b/src/Docfx.Dotnet/ManagedReference/Models/SyntaxDetailViewModel.cs
@@ -22,7 +22,7 @@ public class SyntaxDetailViewModel
[ExtensibleMember(Constants.ExtensionMemberPrefix.Content)]
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
- public SortedList Contents { get; set; } = new();
+ public SortedList Contents { get; set; } = [];
[YamlIgnore]
[Newtonsoft.Json.JsonIgnore]
diff --git a/src/Docfx.Dotnet/ManagedReference/Resolvers/NormalizeSyntax.cs b/src/Docfx.Dotnet/ManagedReference/Resolvers/NormalizeSyntax.cs
index 61794226839..3c2a0f5948c 100644
--- a/src/Docfx.Dotnet/ManagedReference/Resolvers/NormalizeSyntax.cs
+++ b/src/Docfx.Dotnet/ManagedReference/Resolvers/NormalizeSyntax.cs
@@ -17,7 +17,7 @@ public void Run(MetadataModel yaml, ResolverContext context)
(member, parent) =>
{
// get all the possible places where link is possible
- if (member.Syntax is {Content: not null})
+ if (member.Syntax is { Content: not null })
{
SyntaxLanguage[] keys = new SyntaxLanguage[member.Syntax.Content.Count];
member.Syntax.Content.Keys.CopyTo(keys, 0);
diff --git a/src/Docfx.Dotnet/ManagedReference/Resolvers/ResolveReference.cs b/src/Docfx.Dotnet/ManagedReference/Resolvers/ResolveReference.cs
index 1b59b26ee8c..f946b36b8df 100644
--- a/src/Docfx.Dotnet/ManagedReference/Resolvers/ResolveReference.cs
+++ b/src/Docfx.Dotnet/ManagedReference/Resolvers/ResolveReference.cs
@@ -20,14 +20,14 @@ public void Run(MetadataModel yaml, ResolverContext context)
if (current.Type.IsPageLevel())
{
page = current;
- current.References = new Dictionary();
+ current.References = [];
}
else
{
page = parent;
current.References = null;
}
- if (documentReferences is {Count: > 0})
+ if (documentReferences is { Count: > 0 })
{
foreach (var key in documentReferences.Keys)
{
diff --git a/src/Docfx.Dotnet/ManagedReference/Resolvers/SetDerivedClass.cs b/src/Docfx.Dotnet/ManagedReference/Resolvers/SetDerivedClass.cs
index c812f1a6e0d..cb23287b342 100644
--- a/src/Docfx.Dotnet/ManagedReference/Resolvers/SetDerivedClass.cs
+++ b/src/Docfx.Dotnet/ManagedReference/Resolvers/SetDerivedClass.cs
@@ -7,11 +7,11 @@ namespace Docfx.Dotnet;
internal class SetDerivedClass : IResolverPipeline
{
- private readonly Dictionary> _derivedClassMapping = new();
+ private readonly Dictionary> _derivedClassMapping = [];
public void Run(MetadataModel yaml, ResolverContext context)
{
- if (yaml.Members is {Count: > 0})
+ if (yaml.Members is { Count: > 0 })
{
UpdateDerivedClassMapping(yaml.Members, context.References);
AppendDerivedClass(yaml.Members);
@@ -23,7 +23,7 @@ private void UpdateDerivedClassMapping(List items, Dictionary