From 14debbfe2c0bb499be872fcd85da02e1ca61415b Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 09:14:53 -0500 Subject: [PATCH 01/10] - upgrades tooling to net 8 --- .azure-pipelines/ci-build.yml | 8 ++--- .github/workflows/codeql-analysis.yml | 2 +- .github/workflows/dotnet.yml | 4 +-- .github/workflows/idempotency-tests.yml | 2 +- .github/workflows/integration-tests.yml | 4 +-- .github/workflows/sonarcloud.yml | 10 +++--- .vscode/launch.json | 34 +++++++++---------- CHANGELOG.md | 1 + Dockerfile | 6 ++-- it/compare-generation.ps1 | 2 +- it/csharp/basic/basic.csproj | 2 +- it/csharp/dotnet.csproj | 2 +- it/generate-code.ps1 | 2 +- src/Kiota.Builder/Kiota.Builder.csproj | 7 ++-- src/kiota/kiota.csproj | 10 +++--- .../Kiota.Builder.IntegrationTests.csproj | 2 +- .../Kiota.Builder.Tests.csproj | 4 +-- tests/Kiota.Tests/Kiota.Tests.csproj | 4 +-- 18 files changed, 54 insertions(+), 52 deletions(-) diff --git a/.azure-pipelines/ci-build.yml b/.azure-pipelines/ci-build.yml index 8684e84c56..0907c3ab4d 100644 --- a/.azure-pipelines/ci-build.yml +++ b/.azure-pipelines/ci-build.yml @@ -84,9 +84,9 @@ stages: version: 6.x - task: UseDotNet@2 - displayName: "Use .NET 7" + displayName: "Use .NET 8" inputs: - version: 7.x + version: 8.x - task: PoliCheck@2 displayName: 'Run PoliCheck "/src"' @@ -328,9 +328,9 @@ stages: inputs: version: 6.x - task: UseDotNet@2 - displayName: "Use .NET 7" + displayName: "Use .NET 8" inputs: - version: 7.x + version: 8.x - task: DownloadPipelineArtifact@2 inputs: diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index a9ecaeef68..e780ee61cc 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -60,7 +60,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v3 with: - dotnet-version: 7.0.x + dotnet-version: 8.x # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 716f769c29..b2ef402fe8 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -35,7 +35,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v3 with: - dotnet-version: 7.0.x + dotnet-version: 8.x - name: Restore dependencies run: dotnet restore kiota.sln - name: Check formatting @@ -64,7 +64,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v3 with: - dotnet-version: 7.0.x + dotnet-version: 8.x - name: Restore dependencies run: dotnet restore kiota.sln - name: Publish ${{ matrix.os }} diff --git a/.github/workflows/idempotency-tests.yml b/.github/workflows/idempotency-tests.yml index b30b99ae29..abedf77f13 100644 --- a/.github/workflows/idempotency-tests.yml +++ b/.github/workflows/idempotency-tests.yml @@ -39,7 +39,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v3 with: - dotnet-version: 7.0.x + dotnet-version: 8.x - name: Restore dependencies run: dotnet restore kiota.sln - name: Build diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index 6b911d178c..fe81222bdb 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -39,7 +39,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v3 with: - dotnet-version: 7.0.x + dotnet-version: 8.x - name: Restore dependencies run: dotnet restore kiota.sln - name: Build @@ -94,7 +94,7 @@ jobs: if: matrix.language == 'csharp' uses: actions/setup-dotnet@v3 with: - dotnet-version: 7.0.x + dotnet-version: 8.x - name: Setup Go if: matrix.language == 'go' uses: actions/setup-go@v4 diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 27e0584550..278a6e5b79 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -52,14 +52,12 @@ jobs: with: distribution: "adopt" java-version: 17 - - name: Setup .NET 5 # At the moment the scanner requires dotnet 5 https://www.nuget.org/packages/dotnet-sonarscanner - uses: actions/setup-dotnet@v3 - with: - dotnet-version: 5.0.x - name: Setup .NET uses: actions/setup-dotnet@v3 - with: - dotnet-version: 7.0.x + with: # At the moment the scanner requires dotnet 5 https://www.nuget.org/packages/dotnet-sonarscanner + dotnet-version: | + 5.x + 8.x - uses: actions/checkout@v4 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis diff --git a/.vscode/launch.json b/.vscode/launch.json index d860197f5b..36465ec859 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,7 +6,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -27,7 +27,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -48,7 +48,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -69,7 +69,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -90,7 +90,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -111,7 +111,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -132,7 +132,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -154,7 +154,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -175,7 +175,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "generate", "--openapi", @@ -195,7 +195,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": ["search", "microsoft"], "cwd": "${workspaceFolder}/src/kiota", "console": "internalConsole", @@ -206,7 +206,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": ["search", "test"], "cwd": "${workspaceFolder}/src/kiota", "console": "internalConsole", @@ -217,7 +217,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "show", "-d", @@ -232,12 +232,12 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": [ "download", "msgraph::microsoft-graph", "-o", - "${workspaceFolder}/src/kiota/bin/Debug/net7.0/graphv1.yml" + "${workspaceFolder}/src/kiota/bin/Debug/net8.0/graphv1.yml" ], "cwd": "${workspaceFolder}/src/kiota", "console": "internalConsole", @@ -248,7 +248,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": ["info", "-l", "CSharp"], "cwd": "${workspaceFolder}/src/kiota", "console": "internalConsole", @@ -259,7 +259,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": ["update", "-o", "${workspaceFolder}/samples"], "cwd": "${workspaceFolder}/src/kiota", "console": "internalConsole", @@ -270,7 +270,7 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build", - "program": "${workspaceFolder}/src/kiota/bin/Debug/net7.0/kiota.dll", + "program": "${workspaceFolder}/src/kiota/bin/Debug/net8.0/kiota.dll", "args": ["login", "github", "device"], "cwd": "${workspaceFolder}/src/kiota", "console": "internalConsole", diff --git a/CHANGELOG.md b/CHANGELOG.md index 70bd8892db..ab33964e36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- Moved from net7 to net8. - Fixes bug where import statements for additionalDataHolder and enumSet are missing when BackingStore is enabled in java. [#3643](https://github.com/microsoft/kiota/pull/3643) - Fixes bug where getBackingStore method body was malformed for java. [#3643](https://github.com/microsoft/kiota/pull/3643) - Fixes bug where serialize method will not write additional data when backingStore is enabled for java. [#3643](https://github.com/microsoft/kiota/pull/3643) diff --git a/Dockerfile b/Dockerfile index 4db1a49da8..5a8b78ccbd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:7.0 AS build-env +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env ARG version_suffix WORKDIR /app @@ -10,10 +10,10 @@ RUN if [ -z "$version_suffix" ]; then \ dotnet publish ./src/kiota/kiota.csproj -c Release -p:TreatWarningsAsErrors=false --version-suffix $version_suffix; \ fi -FROM mcr.microsoft.com/dotnet/runtime:7.0 AS runtime +FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime WORKDIR /app -COPY --from=build-env /app/kiota/src/kiota/bin/Release/net7.0 ./ +COPY --from=build-env /app/kiota/src/kiota/bin/Release/net8.0 ./ VOLUME /app/output VOLUME /app/openapi.yml diff --git a/it/compare-generation.ps1 b/it/compare-generation.ps1 index 58753b89c1..b85798abb5 100755 --- a/it/compare-generation.ps1 +++ b/it/compare-generation.ps1 @@ -34,7 +34,7 @@ if ($IsWindows) { switch ($dev) { $true { Write-Warning "Using kiota in dev mode" - $kiotaExec = Join-Path -Path $rootPath -ChildPath "src" -AdditionalChildPath "kiota", "bin", "Debug", "net7.0", $executableName + $kiotaExec = Join-Path -Path $rootPath -ChildPath "src" -AdditionalChildPath "kiota", "bin", "Debug", "net8.0", $executableName break } default { diff --git a/it/csharp/basic/basic.csproj b/it/csharp/basic/basic.csproj index 32e85c26bc..fc64e6859c 100644 --- a/it/csharp/basic/basic.csproj +++ b/it/csharp/basic/basic.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable diff --git a/it/csharp/dotnet.csproj b/it/csharp/dotnet.csproj index 8bf3a265a4..4cfbfab9ee 100644 --- a/it/csharp/dotnet.csproj +++ b/it/csharp/dotnet.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 enable enable App diff --git a/it/generate-code.ps1 b/it/generate-code.ps1 index da73e36fc4..241f9f1234 100755 --- a/it/generate-code.ps1 +++ b/it/generate-code.ps1 @@ -29,7 +29,7 @@ if ($IsWindows) { switch ($dev) { $true { Write-Warning "Using kiota in dev mode" - $kiotaExec = Join-Path -Path $rootPath -ChildPath "src" -AdditionalChildPath "kiota", "bin", "Debug", "net7.0", $executableName + $kiotaExec = Join-Path -Path $rootPath -ChildPath "src" -AdditionalChildPath "kiota", "bin", "Debug", "net8.0", $executableName break } default { diff --git a/src/Kiota.Builder/Kiota.Builder.csproj b/src/Kiota.Builder/Kiota.Builder.csproj index b3f642f64c..0de5f09c1c 100644 --- a/src/Kiota.Builder/Kiota.Builder.csproj +++ b/src/Kiota.Builder/Kiota.Builder.csproj @@ -3,7 +3,7 @@ Latest enable true - net7.0 + net8.0 true http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/microsoft/kiota @@ -49,7 +49,8 @@ - + @@ -57,4 +58,4 @@ - + \ No newline at end of file diff --git a/src/kiota/kiota.csproj b/src/kiota/kiota.csproj index dabe288610..e8c0b57d65 100644 --- a/src/kiota/kiota.csproj +++ b/src/kiota/kiota.csproj @@ -2,7 +2,7 @@ Exe Latest - net7.0 + net8.0 true http://go.microsoft.com/fwlink/?LinkID=288890 https://github.com/microsoft/kiota @@ -40,7 +40,8 @@ - + @@ -50,7 +51,8 @@ - + @@ -60,4 +62,4 @@ PreserveNewest - + \ No newline at end of file diff --git a/tests/Kiota.Builder.IntegrationTests/Kiota.Builder.IntegrationTests.csproj b/tests/Kiota.Builder.IntegrationTests/Kiota.Builder.IntegrationTests.csproj index 5d7367b351..9dff09164b 100644 --- a/tests/Kiota.Builder.IntegrationTests/Kiota.Builder.IntegrationTests.csproj +++ b/tests/Kiota.Builder.IntegrationTests/Kiota.Builder.IntegrationTests.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 false diff --git a/tests/Kiota.Builder.Tests/Kiota.Builder.Tests.csproj b/tests/Kiota.Builder.Tests/Kiota.Builder.Tests.csproj index bd1b14524e..4557fdb57c 100644 --- a/tests/Kiota.Builder.Tests/Kiota.Builder.Tests.csproj +++ b/tests/Kiota.Builder.Tests/Kiota.Builder.Tests.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 false true @@ -30,4 +30,4 @@ - + \ No newline at end of file diff --git a/tests/Kiota.Tests/Kiota.Tests.csproj b/tests/Kiota.Tests/Kiota.Tests.csproj index f298d832a4..b0e2a8b87a 100644 --- a/tests/Kiota.Tests/Kiota.Tests.csproj +++ b/tests/Kiota.Tests/Kiota.Tests.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 false @@ -27,4 +27,4 @@ - + \ No newline at end of file From 9be9c67900e4f945163ba29da675e977381aa7e9 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 09:41:01 -0500 Subject: [PATCH 02/10] - code linting any method replacements Signed-off-by: Vincent Biret --- src/Kiota.Builder/CodeDOM/CodeBlock.cs | 6 ++-- src/Kiota.Builder/CodeDOM/CodeClass.cs | 10 +++---- src/Kiota.Builder/CodeDOM/CodeFile.cs | 2 +- src/Kiota.Builder/CodeDOM/CodeMethod.cs | 6 ++-- src/Kiota.Builder/CodeDOM/CodeNamespace.cs | 10 +++---- .../CodeDOM/DiscriminatorInformation.cs | 2 +- .../CodeDOM/ProprietableBlock.cs | 6 ++-- .../Configuration/GenerationConfiguration.cs | 2 +- .../Extensions/OpenApiDocumentExtensions.cs | 2 +- .../Extensions/OpenApiOperationExtensions.cs | 4 +-- .../Extensions/OpenApiSchemaExtensions.cs | 2 +- .../OpenApiUrlTreeNodeExtensions.cs | 2 +- .../Extensions/StringExtensions.cs | 2 +- src/Kiota.Builder/KiotaBuilder.cs | 30 +++++++++---------- .../PathSegmenters/CommonPathSegmenter.cs | 2 +- .../Refiners/CommonLanguageRefiner.cs | 12 ++++---- src/Kiota.Builder/Refiners/GoRefiner.cs | 2 +- src/Kiota.Builder/Refiners/JavaRefiner.cs | 2 +- src/Kiota.Builder/Refiners/PhpRefiner.cs | 4 +-- src/Kiota.Builder/Refiners/RubyRefiner.cs | 2 +- .../Refiners/TypeScriptRefiner.cs | 5 ++-- .../GitHub/GitHubSearchProvider.cs | 2 +- .../Writers/CLI/CliCodeMethodWriter.cs | 4 +-- .../Writers/CSharp/CSharpConventionService.cs | 6 ++-- .../CSharp/CodeClassDeclarationWriter.cs | 2 +- .../Writers/CSharp/CodeMethodWriter.cs | 6 ++-- .../Writers/CodeClassExtensions.cs | 4 +-- .../Writers/Go/CodeFileDeclarationWriter.cs | 2 +- .../Writers/Go/CodeMethodWriter.cs | 24 +++++++-------- .../CodeProprietableBlockDeclarationWriter.cs | 2 +- .../Writers/Go/GoConventionService.cs | 2 +- .../Writers/Java/CodeEnumWriter.cs | 3 +- .../Writers/Java/CodeMethodWriter.cs | 28 ++++++++--------- .../Writers/Java/JavaConventionService.cs | 4 +-- .../Writers/NamespaceClassNamesProvider.cs | 2 +- .../Writers/Php/CodeMethodWriter.cs | 24 +++++++-------- .../Writers/Php/PhpConventionService.cs | 8 ++--- .../Writers/Python/CodeMethodWriter.cs | 10 +++---- .../Writers/Python/CodeUsingWriter.cs | 6 ++-- .../Writers/Python/PythonConventionService.cs | 4 +-- .../Python/PythonRelativeImportManager.cs | 2 +- .../Writers/RelativeImportManager.cs | 2 +- .../Writers/Ruby/CodeMethodWriter.cs | 4 +-- .../Swift/CodeClassDeclarationWriter.cs | 2 +- .../CodeProprietableBlockDeclarationWriter.cs | 2 +- .../Writers/TypeScript/CodeMethodWriter.cs | 2 +- .../TypeScript/TypeScriptConventionService.cs | 6 ++-- .../Handlers/KiotaGenerationCommandHandler.cs | 12 ++++---- src/kiota/KiotaConfigurationExtensions.cs | 4 +-- src/kiota/Rpc/Server.cs | 14 ++++----- 50 files changed, 153 insertions(+), 155 deletions(-) diff --git a/src/Kiota.Builder/CodeDOM/CodeBlock.cs b/src/Kiota.Builder/CodeDOM/CodeBlock.cs index 230131c4ef..b1ac03a283 100644 --- a/src/Kiota.Builder/CodeDOM/CodeBlock.cs +++ b/src/Kiota.Builder/CodeDOM/CodeBlock.cs @@ -95,7 +95,7 @@ returnedValue is CodeProperty cProp && .Any()) { // allows for methods overload - var methodOverloadNameSuffix = currentMethodParameterNames.Any() ? currentMethodParameterNames.OrderBy(static x => x).Aggregate(static (x, y) => x + y) : "1"; + var methodOverloadNameSuffix = currentMethodParameterNames.Count != 0 ? currentMethodParameterNames.OrderBy(static x => x).Aggregate(static (x, y) => x + y) : "1"; if (InnerChildElements.GetOrAdd($"{element.Name}-{methodOverloadNameSuffix}", element) is T result2) return result2; } @@ -121,7 +121,7 @@ public IEnumerable FindChildrenByName(string childName) where T : ICodeEle { ArgumentException.ThrowIfNullOrEmpty(childName); - if (InnerChildElements.Any()) + if (!InnerChildElements.IsEmpty) { var result = new List(); var immediateResult = this.FindChildByName(childName, false); @@ -148,7 +148,7 @@ public IEnumerable FindChildrenByName(string childName) where T : ICodeEle { ArgumentException.ThrowIfNullOrEmpty(childName); - if (!InnerChildElements.Any()) + if (InnerChildElements.IsEmpty) return default; if (InnerChildElements.TryGetValue(childName, out var result) && result is T castResult) diff --git a/src/Kiota.Builder/CodeDOM/CodeClass.cs b/src/Kiota.Builder/CodeDOM/CodeClass.cs index 5ad49b2aef..a46e5c1b79 100644 --- a/src/Kiota.Builder/CodeDOM/CodeClass.cs +++ b/src/Kiota.Builder/CodeDOM/CodeClass.cs @@ -50,7 +50,7 @@ public void AddIndexer(params CodeIndexer[] indexers) { if (indexers == null || Array.Exists(indexers, static x => x == null)) throw new ArgumentNullException(nameof(indexers)); - if (!indexers.Any()) + if (indexers.Length == 0) throw new ArgumentOutOfRangeException(nameof(indexers)); foreach (var value in indexers) @@ -74,7 +74,7 @@ public override IEnumerable AddProperty(params CodeProperty[] prop { if (properties == null || properties.Any(static x => x == null)) throw new ArgumentNullException(nameof(properties)); - if (!properties.Any()) + if (properties.Length == 0) throw new ArgumentOutOfRangeException(nameof(properties)); return properties.Select(property => @@ -185,15 +185,15 @@ public IEnumerable AddInnerClass(params CodeClass[] codeClasses) { if (codeClasses == null || codeClasses.Any(static x => x == null)) throw new ArgumentNullException(nameof(codeClasses)); - if (!codeClasses.Any()) + if (codeClasses.Length == 0) throw new ArgumentOutOfRangeException(nameof(codeClasses)); return AddRange(codeClasses); } public IEnumerable AddInnerInterface(params CodeInterface[] codeInterfaces) { - if (codeInterfaces == null || codeInterfaces.Any(x => x == null)) + if (codeInterfaces == null || codeInterfaces.Any(static x => x == null)) throw new ArgumentNullException(nameof(codeInterfaces)); - if (!codeInterfaces.Any()) + if (codeInterfaces.Length == 0) throw new ArgumentOutOfRangeException(nameof(codeInterfaces)); return AddRange(codeInterfaces); } diff --git a/src/Kiota.Builder/CodeDOM/CodeFile.cs b/src/Kiota.Builder/CodeDOM/CodeFile.cs index 0efd93fb0a..b987c2ad01 100644 --- a/src/Kiota.Builder/CodeDOM/CodeFile.cs +++ b/src/Kiota.Builder/CodeDOM/CodeFile.cs @@ -12,7 +12,7 @@ public IEnumerable AddElements(params T[] elements) where T : CodeElement { if (elements == null || elements.Any(static x => x == null)) throw new ArgumentNullException(nameof(elements)); - if (!elements.Any()) + if (elements.Length == 0) throw new ArgumentOutOfRangeException(nameof(elements)); return AddRange(elements); diff --git a/src/Kiota.Builder/CodeDOM/CodeMethod.cs b/src/Kiota.Builder/CodeDOM/CodeMethod.cs index d41be2b74d..a1cc5dc3c5 100644 --- a/src/Kiota.Builder/CodeDOM/CodeMethod.cs +++ b/src/Kiota.Builder/CodeDOM/CodeMethod.cs @@ -188,7 +188,7 @@ public IEnumerable PathQueryAndHeaderParameters private readonly Dictionary pathQueryAndHeaderParameters = new(StringComparer.OrdinalIgnoreCase); public void AddPathQueryOrHeaderParameter(params CodeParameter[] parameters) { - if (parameters == null || !parameters.Any()) return; + if (parameters == null || parameters.Length == 0) return; foreach (var parameter in parameters.OrderByDescending(static x => x.Kind)) //guarantees that path parameters are added first and other are deduplicated { EnsureElementsAreChildren(parameter); @@ -321,9 +321,9 @@ public object Clone() public void AddParameter(params CodeParameter[] methodParameters) { - if (methodParameters == null || methodParameters.Any(x => x == null)) + if (methodParameters == null || methodParameters.Any(static x => x == null)) throw new ArgumentNullException(nameof(methodParameters)); - if (!methodParameters.Any()) + if (methodParameters.Length == 0) throw new ArgumentOutOfRangeException(nameof(methodParameters)); EnsureElementsAreChildren(methodParameters); methodParameters.ToList().ForEach(x => parameters.TryAdd(x.Name, x)); diff --git a/src/Kiota.Builder/CodeDOM/CodeNamespace.cs b/src/Kiota.Builder/CodeDOM/CodeNamespace.cs index 221f51a197..7e2ab2bc2e 100644 --- a/src/Kiota.Builder/CodeDOM/CodeNamespace.cs +++ b/src/Kiota.Builder/CodeDOM/CodeNamespace.cs @@ -55,7 +55,7 @@ public IEnumerable AddClass(params CodeClass[] codeClasses) { if (codeClasses == null || Array.Exists(codeClasses, static x => x == null)) throw new ArgumentNullException(nameof(codeClasses)); - if (!codeClasses.Any()) + if (codeClasses.Length == 0) throw new ArgumentOutOfRangeException(nameof(codeClasses)); return AddRange(codeClasses); } @@ -135,7 +135,7 @@ public IEnumerable AddEnum(params CodeEnum[] enumDeclarations) { if (enumDeclarations == null || Array.Exists(enumDeclarations, static x => x == null)) throw new ArgumentNullException(nameof(enumDeclarations)); - if (!enumDeclarations.Any()) + if (enumDeclarations.Length == 0) throw new ArgumentOutOfRangeException(nameof(enumDeclarations)); return AddRange(enumDeclarations); } @@ -152,7 +152,7 @@ public IEnumerable AddFunction(params CodeFunction[] globalFunctio { if (globalFunctions == null || Array.Exists(globalFunctions, static x => x == null)) throw new ArgumentNullException(nameof(globalFunctions)); - if (!globalFunctions.Any()) + if (globalFunctions.Length == 0) throw new ArgumentOutOfRangeException(nameof(globalFunctions)); return AddRange(globalFunctions); } @@ -160,7 +160,7 @@ public IEnumerable AddInterface(params CodeInterface[] interfaces { if (interfaces == null || Array.Exists(interfaces, static x => x == null)) throw new ArgumentNullException(nameof(interfaces)); - if (!interfaces.Any()) + if (interfaces.Length == 0) throw new ArgumentOutOfRangeException(nameof(interfaces)); return AddRange(interfaces); } @@ -197,7 +197,7 @@ internal IEnumerable AddConstant(params CodeConstant[] codeConstan { if (codeConstants == null || Array.Exists(codeConstants, static x => x == null)) throw new ArgumentNullException(nameof(codeConstants)); - if (!codeConstants.Any()) + if (codeConstants.Length == 0) throw new ArgumentOutOfRangeException(nameof(codeConstants)); return AddRange(codeConstants); } diff --git a/src/Kiota.Builder/CodeDOM/DiscriminatorInformation.cs b/src/Kiota.Builder/CodeDOM/DiscriminatorInformation.cs index d85a7362f5..69a6c7f8cd 100644 --- a/src/Kiota.Builder/CodeDOM/DiscriminatorInformation.cs +++ b/src/Kiota.Builder/CodeDOM/DiscriminatorInformation.cs @@ -69,7 +69,7 @@ public object Clone() Name = Name, }; } - public bool HasBasicDiscriminatorInformation => !string.IsNullOrEmpty(DiscriminatorPropertyName) && discriminatorMappings.Any(); + public bool HasBasicDiscriminatorInformation => !string.IsNullOrEmpty(DiscriminatorPropertyName) && !discriminatorMappings.IsEmpty; public bool ShouldWriteDiscriminatorForInheritedType => HasBasicDiscriminatorInformation && IsComplexType; public bool ShouldWriteDiscriminatorForUnionType => IsUnionType; // if union of scalar types, then we don't always get discriminator information public bool ShouldWriteDiscriminatorForIntersectionType => IsIntersectionType; // if intersection of scalar types, then we don't always get discriminator information diff --git a/src/Kiota.Builder/CodeDOM/ProprietableBlock.cs b/src/Kiota.Builder/CodeDOM/ProprietableBlock.cs index a9e182bd6b..35a833febc 100644 --- a/src/Kiota.Builder/CodeDOM/ProprietableBlock.cs +++ b/src/Kiota.Builder/CodeDOM/ProprietableBlock.cs @@ -35,13 +35,13 @@ public virtual IEnumerable AddProperty(params CodeProperty[] prope { if (properties == null || properties.Any(static x => x == null)) throw new ArgumentNullException(nameof(properties)); - if (!properties.Any()) + if (properties.Length == 0) throw new ArgumentOutOfRangeException(nameof(properties)); return AddRange(properties); } public void RemovePropertiesOfKind(params CodePropertyKind[] kind) { - if (kind == null || !kind.Any()) + if (kind == null || kind.Length == 0) throw new ArgumentNullException(nameof(kind)); var propertiesToRemove = Properties.Where(x => x.IsOfKind(kind)).ToList(); foreach (var property in propertiesToRemove) @@ -79,7 +79,7 @@ public IEnumerable AddMethod(params CodeMethod[] methods) { if (methods == null || methods.Any(static x => x == null)) throw new ArgumentNullException(nameof(methods)); - if (!methods.Any()) + if (methods.Length == 0) throw new ArgumentOutOfRangeException(nameof(methods)); return AddRange(methods); } diff --git a/src/Kiota.Builder/Configuration/GenerationConfiguration.cs b/src/Kiota.Builder/Configuration/GenerationConfiguration.cs index 1254f4d2c7..4cfd635d50 100644 --- a/src/Kiota.Builder/Configuration/GenerationConfiguration.cs +++ b/src/Kiota.Builder/Configuration/GenerationConfiguration.cs @@ -161,7 +161,7 @@ internal void UpdateConfigurationFromLanguagesInformation(LanguagesInformation l ClientNamespaceName.Equals(defaultConfiguration.ClientNamespaceName, StringComparison.Ordinal) && !ClientNamespaceName.Equals(languageInfo.ClientNamespaceName, StringComparison.Ordinal)) ClientNamespaceName = languageInfo.ClientNamespaceName; - if (languageInfo.StructuredMimeTypes.Any() && + if (languageInfo.StructuredMimeTypes.Count != 0 && comparer.Equals(StructuredMimeTypes, defaultConfiguration.StructuredMimeTypes) && !comparer.Equals(languageInfo.StructuredMimeTypes, StructuredMimeTypes)) StructuredMimeTypes = new(languageInfo.StructuredMimeTypes); diff --git a/src/Kiota.Builder/Extensions/OpenApiDocumentExtensions.cs b/src/Kiota.Builder/Extensions/OpenApiDocumentExtensions.cs index f5c7a12248..e0abc3cb94 100644 --- a/src/Kiota.Builder/Extensions/OpenApiDocumentExtensions.cs +++ b/src/Kiota.Builder/Extensions/OpenApiDocumentExtensions.cs @@ -12,7 +12,7 @@ internal static void InitializeInheritanceIndex(this OpenApiDocument openApiDocu { ArgumentNullException.ThrowIfNull(inheritanceIndex); ArgumentNullException.ThrowIfNull(openApiDocument); - if (!inheritanceIndex.Any() && openApiDocument.Components?.Schemas != null) + if (inheritanceIndex.IsEmpty && openApiDocument.Components?.Schemas != null) { Parallel.ForEach(openApiDocument.Components.Schemas, entry => { diff --git a/src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs b/src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs index 1a67303f37..390986267b 100644 --- a/src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs +++ b/src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs @@ -41,11 +41,11 @@ internal static bool IsMultipartFormDataSchema(this IDictionary GetValidSchemas(this IDictionary source, StructuredMimeTypesCollection structuredMimeTypes) { - if (!(structuredMimeTypes?.Any() ?? false)) + if (structuredMimeTypes.Count == 0) throw new ArgumentNullException(nameof(structuredMimeTypes)); return source? .Where(static c => !string.IsNullOrEmpty(c.Key)) - .Select(static c => (Key: c.Key.Split(';', StringSplitOptions.RemoveEmptyEntries).First(), c.Value)) + .Select(static c => (Key: c.Key.Split(';', StringSplitOptions.RemoveEmptyEntries)[0], c.Value)) .Where(c => structuredMimeTypes.Contains(c.Key) || structuredMimeTypes.Contains(vendorSpecificCleanup.Replace(c.Key, string.Empty))) .Select(static co => co.Value.Schema) .Where(static s => s is not null) ?? diff --git a/src/Kiota.Builder/Extensions/OpenApiSchemaExtensions.cs b/src/Kiota.Builder/Extensions/OpenApiSchemaExtensions.cs index 25c9074324..c5756793a8 100644 --- a/src/Kiota.Builder/Extensions/OpenApiSchemaExtensions.cs +++ b/src/Kiota.Builder/Extensions/OpenApiSchemaExtensions.cs @@ -152,7 +152,7 @@ public static IEnumerable GetSchemaReferenceIds(this OpenApiSchema schem .Union(schema.OneOf ?? Enumerable.Empty()) .SelectMany(x => x.GetSchemaReferenceIds(visitedSchemas)) .ToList();// this to list is important otherwise the any marks the schemas as visited and add range doesn't find anything - if (subSchemaReferences.Any()) + if (subSchemaReferences.Count != 0) result.AddRange(subSchemaReferences); return result.Distinct(); } diff --git a/src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs b/src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs index c3913ef313..3282ccba7a 100644 --- a/src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs +++ b/src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs @@ -189,7 +189,7 @@ public static string GetUrlTemplate(this OpenApiUrlTreeNode currentNode) .Where(static x => x.In == ParameterLocation.Query)) .DistinctBy(static x => x.Name) .ToArray(); - if (parameters.Any()) + if (parameters.Length != 0) queryStringParameters = "{?" + parameters.Select(static x => x.Name.SanitizeParameterNameForUrlTemplate() + diff --git a/src/Kiota.Builder/Extensions/StringExtensions.cs b/src/Kiota.Builder/Extensions/StringExtensions.cs index e903d3fe03..acc95d5a85 100644 --- a/src/Kiota.Builder/Extensions/StringExtensions.cs +++ b/src/Kiota.Builder/Extensions/StringExtensions.cs @@ -162,7 +162,7 @@ public static string CleanupSymbolName(this string? original) x.Groups[CleanupGroupName].Value.ToFirstCharacterUpperCase() : string.Empty); //strip out any invalid characters, and replace any following one by its uppercase version - if (result.Any() && int.TryParse(result.AsSpan(0, 1), out var _)) // in most languages a number or starting with a number is not a valid symbol name + if (result.Length != 0 && int.TryParse(result.AsSpan(0, 1), out var _)) // in most languages a number or starting with a number is not a valid symbol name result = NumbersSpellingRegex.Replace(result, static x => x.Groups["number"] .Value .Select(static x => SpelledOutNumbers[x]) diff --git a/src/Kiota.Builder/KiotaBuilder.cs b/src/Kiota.Builder/KiotaBuilder.cs index 4d22de7978..a19d8ed4c7 100644 --- a/src/Kiota.Builder/KiotaBuilder.cs +++ b/src/Kiota.Builder/KiotaBuilder.cs @@ -146,7 +146,7 @@ private static string NormalizeApiManifestPath(Request request, string? baseUrl) if (manifestDetails is not null) { inputPath = manifestDetails.Item1; - if (!config.IncludePatterns.Any()) + if (config.IncludePatterns.Count == 0) config.IncludePatterns = manifestDetails.Item2.ToHashSet(StringComparer.OrdinalIgnoreCase); } StopLogAndReset(sw, $"step {++stepId} - getting the manifest - took"); @@ -326,28 +326,28 @@ internal void FilterPathsByPatterns(OpenApiDocument doc) { var includePatterns = GetFilterPatternsFromConfiguration(config.IncludePatterns); var excludePatterns = GetFilterPatternsFromConfiguration(config.ExcludePatterns); - if (!includePatterns.Any() && !excludePatterns.Any()) return; + if (includePatterns.Count == 0 && excludePatterns.Count == 0) return; - var nonOperationIncludePatterns = includePatterns.Where(static x => !x.Value.Any()).Select(static x => x.Key).ToList(); - var nonOperationExcludePatterns = excludePatterns.Where(static x => !x.Value.Any()).Select(static x => x.Key).ToList(); - var operationIncludePatterns = includePatterns.Where(static x => x.Value.Any()).ToList(); + var nonOperationIncludePatterns = includePatterns.Where(static x => x.Value.Count == 0).Select(static x => x.Key).ToList(); + var nonOperationExcludePatterns = excludePatterns.Where(static x => x.Value.Count == 0).Select(static x => x.Key).ToList(); + var operationIncludePatterns = includePatterns.Where(static x => x.Value.Count != 0).ToList(); - if (nonOperationIncludePatterns.Any() || nonOperationExcludePatterns.Any()) - doc.Paths.Keys.Where(x => (nonOperationIncludePatterns.Any() && !nonOperationIncludePatterns.Any(y => y.IsMatch(x)) || - nonOperationExcludePatterns.Any() && nonOperationExcludePatterns.Any(y => y.IsMatch(x))) && + if (nonOperationIncludePatterns.Count != 0 || nonOperationExcludePatterns.Count != 0) + doc.Paths.Keys.Where(x => (nonOperationIncludePatterns.Count != 0 && !nonOperationIncludePatterns.Any(y => y.IsMatch(x)) || + nonOperationExcludePatterns.Count != 0 && nonOperationExcludePatterns.Any(y => y.IsMatch(x))) && !operationIncludePatterns.Any(y => y.Key.IsMatch(x))) // so we don't trim paths that are going to be filtered by operation .ToList() .ForEach(x => doc.Paths.Remove(x)); - var operationExcludePatterns = excludePatterns.Where(static x => x.Value.Any()).ToList(); + var operationExcludePatterns = excludePatterns.Where(static x => x.Value.Count != 0).ToList(); - if (operationIncludePatterns.Any() || operationExcludePatterns.Any()) + if (operationIncludePatterns.Count != 0 || operationExcludePatterns.Count != 0) { foreach (var path in doc.Paths.Where(x => !nonOperationIncludePatterns.Any(y => y.IsMatch(x.Key)))) { var pathString = path.Key; - path.Value.Operations.Keys.Where(x => operationIncludePatterns.Any() && !operationIncludePatterns.Any(y => y.Key.IsMatch(pathString) && y.Value.Contains(x)) || - operationExcludePatterns.Any() && operationExcludePatterns.Any(y => y.Key.IsMatch(pathString) && y.Value.Contains(x))) + path.Value.Operations.Keys.Where(x => operationIncludePatterns.Count != 0 && !operationIncludePatterns.Any(y => y.Key.IsMatch(pathString) && y.Value.Contains(x)) || + operationExcludePatterns.Count != 0 && operationExcludePatterns.Any(y => y.Key.IsMatch(pathString) && y.Value.Contains(x))) .ToList() .ForEach(x => path.Value.Operations.Remove(x)); } @@ -2168,7 +2168,7 @@ internal static void AddDiscriminatorMethod(CodeClass newClass, string discrimin } private void CreatePropertiesForModelClass(OpenApiUrlTreeNode currentNode, OpenApiSchema schema, CodeNamespace ns, CodeClass model) { - if (CollectAllProperties(schema) is var properties && properties.Any()) + if (CollectAllProperties(schema) is var properties && properties.Count != 0) { var propertiesToAdd = properties .Select(x => @@ -2188,7 +2188,7 @@ private void CreatePropertiesForModelClass(OpenApiUrlTreeNode currentNode, OpenA }) .OfType() .ToArray(); - if (propertiesToAdd.Any()) + if (propertiesToAdd.Length != 0) model.AddProperty(propertiesToAdd); } } @@ -2327,7 +2327,7 @@ internal static void AddSerializationMembers(CodeClass model, bool includeAdditi private CodeClass? CreateOperationParameterClass(OpenApiUrlTreeNode node, OperationType operationType, OpenApiOperation operation, CodeClass parentClass) { var parameters = node.PathItems[Constants.DefaultOpenApiLabel].Parameters.Union(operation.Parameters).Where(static p => p.In == ParameterLocation.Query).ToArray(); - if (parameters.Any()) + if (parameters.Length != 0) { var parameterClass = parentClass.AddInnerClass(new CodeClass { diff --git a/src/Kiota.Builder/PathSegmenters/CommonPathSegmenter.cs b/src/Kiota.Builder/PathSegmenters/CommonPathSegmenter.cs index 731b72bc46..910a1cb8b5 100644 --- a/src/Kiota.Builder/PathSegmenters/CommonPathSegmenter.cs +++ b/src/Kiota.Builder/PathSegmenters/CommonPathSegmenter.cs @@ -44,7 +44,7 @@ public string GetPath(CodeNamespace currentNamespace, CodeElement currentElement namespacePathSegments = namespacePathSegments.Where(x => !string.IsNullOrEmpty(x)) .Select(NormalizeNamespaceSegment) .ToList(); - var targetPath = Path.Combine(RootPath, namespacePathSegments.Any() ? namespacePathSegments + var targetPath = Path.Combine(RootPath, namespacePathSegments.Count != 0 ? namespacePathSegments .Aggregate(static (x, y) => $"{x}{Path.DirectorySeparatorChar}{y}") : string.Empty, fileName + FileSuffix); if (shouldNormalizePath) diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index 8efe004841..e60d139a0d 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -136,7 +136,7 @@ protected static void CorrectNames(CodeElement current, Func ref protected static void ReplacePropertyNames(CodeElement current, HashSet propertyKindsToReplace, Func refineAccessorName) { ArgumentNullException.ThrowIfNull(refineAccessorName); - if (!(propertyKindsToReplace?.Any() ?? true)) return; + if (propertyKindsToReplace is null || propertyKindsToReplace.Count == 0) return; if (current is CodeProperty currentProperty && !currentProperty.ExistsInBaseType && propertyKindsToReplace!.Contains(currentProperty.Kind) && @@ -160,7 +160,7 @@ current.Parent is CodeClass parentClass && protected static void AddGetterAndSetterMethods(CodeElement current, HashSet propertyKindsToAddAccessors, Func refineAccessorName, bool removeProperty, bool parameterAsOptional, string getterPrefix, string setterPrefix, string fieldPrefix = "_") { ArgumentNullException.ThrowIfNull(refineAccessorName); - if (!(propertyKindsToAddAccessors?.Any() ?? true)) return; + if (propertyKindsToAddAccessors is null || propertyKindsToAddAccessors.Count == 0) return; if (current is CodeProperty currentProperty && !currentProperty.ExistsInBaseType && propertyKindsToAddAccessors!.Contains(currentProperty.Kind) && @@ -399,7 +399,7 @@ protected static void AddDefaultImports(CodeElement current, IEnumerable x.CodeElementEvaluator.Invoke(current)) .SelectMany(usingSelector) .ToArray(); - if (usingsToAdd.Any()) + if (usingsToAdd.Length != 0) { var parentBlock = current.GetImmediateParentOfType(); var targetBlock = parentBlock.Parent is CodeClass parentClassParent ? parentClassParent : parentBlock; @@ -763,7 +763,7 @@ currentClass.StartBlock is ClassDeclaration currentClassDeclaration && .ToArray(); - if (usingsToAdd.Any()) + if (usingsToAdd.Length != 0) (currentClass.Parent is CodeClass parentClass ? parentClass : currentClass).AddUsing(usingsToAdd); //lots of languages do not support imports on nested classes } CrawlTree(current, x => AddPropertiesAndMethodTypesImports(x, includeParentNamespaces, includeCurrentNamespace, compareOnDeclaration, codeTypeFilter)); @@ -1377,7 +1377,7 @@ mappingClass.Parent is CodeNamespace mappingNamespace && mappingClass.StartBlock.InheritsFrom(currentClass)) .Select(x => x.Key) .ToArray(); - if (keysToRemove.Any()) + if (keysToRemove.Length != 0) currentClass.DiscriminatorInformation.RemoveDiscriminatorMapping(keysToRemove); } CrawlTree(currentElement, RemoveDiscriminatorMappingsTargetingSubNamespaces); @@ -1441,7 +1441,7 @@ protected static void RemoveRequestConfigurationClasses(CodeElement currentEleme .Where(x => x.IsOfKind(CodeParameterKind.RequestConfiguration) && x.Type is CodeType type && type.TypeDefinition == currentClass) .ToArray(); var genericTypeParamValue = currentClass.Properties.FirstOrDefaultOfKind(CodePropertyKind.QueryParameters)?.Type as CodeType ?? defaultValueForGenericTypeParam; - if (configurationParameterTypeUsing != null && genericTypeParamValue != null && configurationParameters.Any()) + if (configurationParameterTypeUsing != null && genericTypeParamValue != null && configurationParameters.Length != 0) { parentClass.AddUsing(configurationParameterTypeUsing); if (usingForDefaultGenericParameter != null) diff --git a/src/Kiota.Builder/Refiners/GoRefiner.cs b/src/Kiota.Builder/Refiners/GoRefiner.cs index 3cfa6cdcc2..8bc0ae4089 100644 --- a/src/Kiota.Builder/Refiners/GoRefiner.cs +++ b/src/Kiota.Builder/Refiners/GoRefiner.cs @@ -470,7 +470,7 @@ x.Type is CodeType pType && pType.TypeDefinition != null && currentNamespace.IsParentOf(pType.TypeDefinition.GetImmediateParentOfType())) .ToArray(); - if (propertiesToRemove.Any()) + if (propertiesToRemove.Length != 0) { currentClass.RemoveChildElement(propertiesToRemove); var propertiesToRemoveHashSet = propertiesToRemove.ToHashSet(); diff --git a/src/Kiota.Builder/Refiners/JavaRefiner.cs b/src/Kiota.Builder/Refiners/JavaRefiner.cs index efce98738d..722fc4a8df 100644 --- a/src/Kiota.Builder/Refiners/JavaRefiner.cs +++ b/src/Kiota.Builder/Refiners/JavaRefiner.cs @@ -419,7 +419,7 @@ private void InsertOverrideMethodForRequestExecutorsAndBuildersAndConstructors(C .Select(static x => GetMethodClone(x, CodeParameterKind.RequestConfiguration)) .OfType() .ToArray(); - if (executorMethodsToAdd.Any() || generatorMethodsToAdd.Any()) + if (executorMethodsToAdd.Length != 0 || generatorMethodsToAdd.Length != 0) currentClass.AddMethod(executorMethodsToAdd .Union(generatorMethodsToAdd) .ToArray()); diff --git a/src/Kiota.Builder/Refiners/PhpRefiner.cs b/src/Kiota.Builder/Refiners/PhpRefiner.cs index 1d12aef87d..9fb27f7430 100644 --- a/src/Kiota.Builder/Refiners/PhpRefiner.cs +++ b/src/Kiota.Builder/Refiners/PhpRefiner.cs @@ -391,7 +391,7 @@ private static void AddRequestConfigurationConstructors(CodeElement codeElement) Type = x.Type }) .ToArray(); - if (constructorParams.Any()) + if (constructorParams.Length != 0) { constructor.AddParameter(constructorParams); } @@ -431,7 +431,7 @@ private static void AddQueryParameterFactoryMethod(CodeElement codeElement) Optional = true, Type = (CodeTypeBase)x.Type.Clone() }).ToArray(); - if (properties.Any()) + if (properties.Length != 0) { queryParamFactoryMethod.AddParameter(properties); } diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 498857712f..7e0597e516 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -156,7 +156,7 @@ currentClass.Parent is CodeNamespace currentNamespace && } private static void UpdateReferencesToDisambiguatedClasses(CodeElement currentElement, HashSet classesToUpdate, string suffix) { - if (!classesToUpdate.Any()) return; + if (classesToUpdate.Count == 0) return; if (currentElement is CodeProperty currentProperty && currentProperty.Type is CodeType propertyType && propertyType.TypeDefinition is CodeClass propertyTypeClass && diff --git a/src/Kiota.Builder/Refiners/TypeScriptRefiner.cs b/src/Kiota.Builder/Refiners/TypeScriptRefiner.cs index d5e409b490..2fc73fcb1c 100644 --- a/src/Kiota.Builder/Refiners/TypeScriptRefiner.cs +++ b/src/Kiota.Builder/Refiners/TypeScriptRefiner.cs @@ -212,9 +212,8 @@ private static void GenerateModelCodeFile(CodeInterface codeInterface, CodeNames } } - if (!functions.Any()) + if (functions.Count == 0) return; - functions.Insert(0, codeInterface); codeNamespace.TryAddCodeFile(codeInterface.Name, functions.ToArray()); } @@ -231,7 +230,7 @@ private static void GenerateRequestBuilderCodeFile(CodeClass codeClass, CodeName .OfType() .ToArray(); - if (!elementNames.Any()) + if (elementNames.Length == 0) return; var queryParamClasses = codeNamespace.FindChildrenByName(elementNames, false) diff --git a/src/Kiota.Builder/SearchProviders/GitHub/GitHubSearchProvider.cs b/src/Kiota.Builder/SearchProviders/GitHub/GitHubSearchProvider.cs index d861af8be1..00a8a8b542 100644 --- a/src/Kiota.Builder/SearchProviders/GitHub/GitHubSearchProvider.cs +++ b/src/Kiota.Builder/SearchProviders/GitHub/GitHubSearchProvider.cs @@ -84,7 +84,7 @@ private async Task> SearchAsyncInternal(string var keyResults = GetDictionaryResultFromMultipleSources(await Task.WhenAll(_indexFileInfos.Select(x => GetSearchResultsFromRepo(gitHubClient, owner, repo, x.Key, x.Value, cancellationToken))).ConfigureAwait(false)); if (parts.Length > 2 && keyResults.TryGetValue(term, out var result)) return new Dictionary(StringComparer.OrdinalIgnoreCase) { { term, result } }; - else if (keyResults.Any()) + else if (keyResults.Count != 0) return keyResults; } } diff --git a/src/Kiota.Builder/Writers/CLI/CliCodeMethodWriter.cs b/src/Kiota.Builder/Writers/CLI/CliCodeMethodWriter.cs index a4ed7c1ffd..d295521366 100644 --- a/src/Kiota.Builder/Writers/CLI/CliCodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/CLI/CliCodeMethodWriter.cs @@ -558,7 +558,7 @@ private void WriteIndexerBuildCommand(CodeIndexer indexer, CodeMethod codeElemen var builderMethods = (td.Methods .Where(m => m.IsOfKind(CodeMethodKind.CommandBuilder) && !parentMethodNames.Contains(m.SimpleName))) .ToArray(); - if (!builderMethods.Any()) + if (builderMethods.Length == 0) { writer.WriteLine($"return new(new(0), new(0));"); return; @@ -764,7 +764,7 @@ private static void AddCommands(LanguageWriter writer, IEnumerable b var methods = new List(); methods.AddRange(builderMethods); methods.AddRange(includedSubCommands); - if (!methods.Any()) return; + if (methods.Count == 0) return; var executablesCount = methods.Count(static m => m.OriginalMethod?.HttpMethod is not null); if (executablesCount > 0) diff --git a/src/Kiota.Builder/Writers/CSharp/CSharpConventionService.cs b/src/Kiota.Builder/Writers/CSharp/CSharpConventionService.cs index 5a71dc0af2..cbb4497fc4 100644 --- a/src/Kiota.Builder/Writers/CSharp/CSharpConventionService.cs +++ b/src/Kiota.Builder/Writers/CSharp/CSharpConventionService.cs @@ -85,7 +85,7 @@ internal void AddParametersAssignment(LanguageWriter writer, CodeTypeBase pathPa varName = TempDictionaryVarName; writer.WriteLine($"var {varName} = new {pathParametersType.Name}({pathParametersReference});"); } - if (parameters.Any()) + if (parameters.Length != 0) { writer.WriteLines(parameters.Select(p => { @@ -111,7 +111,7 @@ private static bool ShouldTypeHaveNullableMarker(CodeTypeBase propType, string p private readonly object _namespaceSegmentsNamesLock = new(); private HashSet GetNamesInUseByNamespaceSegments(CodeElement currentElement) { - if (!_namespaceSegmentsNames.Any()) + if (_namespaceSegmentsNames.Count == 0) { lock (_namespaceSegmentsNamesLock) { @@ -155,7 +155,7 @@ public string GetTypeString(CodeTypeBase code, CodeElement targetElement, bool i CodeTypeCollectionKind.Array when includeCollectionInformation => "[]", _ => string.Empty, }; - var genericParameters = currentType.GenericTypeParameterValues.Any() ? + var genericParameters = currentType.GenericTypeParameterValues.Count != 0 ? $"<{string.Join(", ", currentType.GenericTypeParameterValues.Select(x => GetTypeString(x, targetElement, includeCollectionInformation)))}>" : string.Empty; if (currentType.ActionOf && includeActionInformation) diff --git a/src/Kiota.Builder/Writers/CSharp/CodeClassDeclarationWriter.cs b/src/Kiota.Builder/Writers/CSharp/CodeClassDeclarationWriter.cs index 94d6068d65..cf1c4d97da 100644 --- a/src/Kiota.Builder/Writers/CSharp/CodeClassDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/CSharp/CodeClassDeclarationWriter.cs @@ -34,7 +34,7 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit .OfType() .Select(static x => x.ToFirstCharacterUpperCase()) .ToArray(); - var derivation = derivedTypes.Any() ? ": " + derivedTypes.Aggregate(static (x, y) => $"{x}, {y}") + " " : string.Empty; + var derivation = derivedTypes.Length != 0 ? ": " + derivedTypes.Aggregate(static (x, y) => $"{x}, {y}") + " " : string.Empty; conventions.WriteLongDescription(parentClass.Documentation, writer); conventions.WriteDeprecationAttribute(parentClass, writer); writer.StartBlock($"public class {codeElement.Name.ToFirstCharacterUpperCase()} {derivation}{{"); diff --git a/src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs index d3a0254507..a63d0afe9f 100644 --- a/src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs @@ -173,7 +173,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, .Where(static x => x.Type is CodeType xType && xType.TypeDefinition is CodeClass && !xType.IsCollection) .Select(static x => new Tuple(x, (CodeType)x.Type)) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) { @@ -304,7 +304,7 @@ private void WriteDeserializerBodyForIntersectionModel(CodeClass parentClass, La var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { var propertiesNames = complexProperties .Select(static x => x.Name.ToFirstCharacterUpperCase()) @@ -498,7 +498,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeMethod method, CodeClas var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) { diff --git a/src/Kiota.Builder/Writers/CodeClassExtensions.cs b/src/Kiota.Builder/Writers/CodeClassExtensions.cs index 2079de9085..871ae1231b 100644 --- a/src/Kiota.Builder/Writers/CodeClassExtensions.cs +++ b/src/Kiota.Builder/Writers/CodeClassExtensions.cs @@ -12,7 +12,7 @@ public static IEnumerable GetPropertiesOfKind(this CodeClass paren { if (parentClass == null) return Enumerable.Empty(); - if (kinds == null || !kinds.Any()) + if (kinds == null || kinds.Length == 0) throw new ArgumentOutOfRangeException(nameof(kinds)); return parentClass.Properties .Where(x => x.IsOfKind(kinds)) @@ -26,7 +26,7 @@ public static IEnumerable GetMethodsOffKind(this CodeClass parentCla { if (parentClass == null) return Enumerable.Empty(); - if (kinds == null || !kinds.Any()) + if (kinds == null || kinds.Length == 0) throw new ArgumentOutOfRangeException(nameof(kinds)); return parentClass.Methods .Where(x => x.IsOfKind(kinds)) diff --git a/src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs b/src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs index 5f7a4bf4a0..5158bb1bd2 100644 --- a/src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs @@ -33,7 +33,7 @@ public override void WriteCodeElement(CodeFileDeclaration codeElement, LanguageW .OrderBy(static x => x.Item2.Count(static y => y == '/')) .ThenBy(static x => x) .ToList(); - if (importSegments.Any()) + if (importSegments.Count != 0) { writer.WriteLines(string.Empty, "import ("); writer.IncreaseIndent(); diff --git a/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs index 55f8b63c74..9e37aa82b3 100644 --- a/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs @@ -211,7 +211,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, .Where(static x => x.Type is CodeType xType && xType.TypeDefinition is CodeClass && !xType.IsCollection) .Select(static x => new Tuple(x, (CodeType)x.Type)) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) writer.StartBlock("} else {"); @@ -220,7 +220,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, if (includeElse) writer.CloseBlock(); } - else if (otherProps.Any()) + else if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } private const string ResultVarName = "result"; @@ -254,7 +254,7 @@ private void WriteFactoryMethodBodyForUnionModelForDiscriminatedTypes(CodeMethod if (!includeElse) includeElse = true; } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } private void WriteFactoryMethodBodyForUnionModelForUnDiscriminatedTypes(CodeClass parentClass, CodeParameter parseNodeParameter, LanguageWriter writer) @@ -284,7 +284,7 @@ private void WriteFactoryMethodBodyForUnionModelForUnDiscriminatedTypes(CodeClas if (!includeElse) includeElse = true; } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } @@ -361,7 +361,7 @@ private void WriteSerializerBodyForUnionModel(CodeClass parentClass, LanguageWri if (!includeElse) includeElse = true; } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, LanguageWriter writer) @@ -385,7 +385,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Lang var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) { @@ -403,7 +403,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Lang writer.CloseBlock(); } } - else if (otherProps.Any()) + else if (otherProps.Length != 0) { writer.CloseBlock(decreaseIndent: false); } @@ -622,7 +622,7 @@ private static void WriteDeserializerBodyForUnionModel(CodeMethod method, CodeCl if (!includeElse) includeElse = true; } - if (otherPropGetters.Any()) + if (otherPropGetters.Length != 0) writer.CloseBlock(decreaseIndent: false); writer.WriteLine($"return make({method.ReturnType.Name})"); } @@ -631,7 +631,7 @@ private void WriteDeserializerBodyForIntersectionModel(CodeMethod method, CodeCl var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { var propertiesNames = complexProperties .Where(static x => x.Getter != null) @@ -661,7 +661,7 @@ private void WriteDeserializerBodyForInheritedModel(CodeMethod codeElement, Code writer.WriteLine($"res := m.{parentClass.StartBlock.Inherits!.Name.ToFirstCharacterUpperCase()}.{codeElement.Name.ToFirstCharacterUpperCase()}()"); else writer.WriteLine($"res := make({codeElement.ReturnType.Name})"); - if (fieldToSerialize.Any()) + if (fieldToSerialize.Length != 0) { var parsableImportSymbol = GetConversionHelperMethodImport(parentClass, "ParseNode"); foreach (var field in fieldToSerialize) @@ -807,7 +807,7 @@ private static void WriteMethodCall(CodeMethod codeElement, RequestParams reques var skipIndex = requestParams.requestBody == null ? 1 : 0; requestInfoParameters.AddRange(paramsList.Where(static x => x == null).Skip(skipIndex).Select(static x => "nil")); - var paramsCall = requestInfoParameters.Any() ? requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}") : string.Empty; + var paramsCall = requestInfoParameters.Count != 0 ? requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}") : string.Empty; writer.WriteLine(template(generatorMethodName, paramsCall)); } @@ -910,7 +910,7 @@ private static void WriteReturnError(LanguageWriter writer, params string[] retu private static string GetNilsErrorPrefix(params string[] returnTypes) { var sanitizedTypes = returnTypes.Where(x => !string.IsNullOrEmpty(x)).ToArray(); - return !sanitizedTypes.Any() ? + return sanitizedTypes.Length == 0 ? string.Empty : sanitizedTypes.Select(static _ => "nil").Aggregate((x, y) => $"{x}, {y}") + ", "; } diff --git a/src/Kiota.Builder/Writers/Go/CodeProprietableBlockDeclarationWriter.cs b/src/Kiota.Builder/Writers/Go/CodeProprietableBlockDeclarationWriter.cs index 748f00cb3d..4bd8cc5e86 100644 --- a/src/Kiota.Builder/Writers/Go/CodeProprietableBlockDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Go/CodeProprietableBlockDeclarationWriter.cs @@ -33,7 +33,7 @@ public override void WriteCodeElement(T codeElement, LanguageWriter writer) .OrderBy(static x => x.Item2.Count(static y => y == '/')) .ThenBy(static x => x) .ToList(); - if (importSegments.Any()) + if (importSegments.Count != 0) { writer.WriteLines(string.Empty, "import ("); writer.IncreaseIndent(); diff --git a/src/Kiota.Builder/Writers/Go/GoConventionService.cs b/src/Kiota.Builder/Writers/Go/GoConventionService.cs index c2a156511d..2f76f5e831 100644 --- a/src/Kiota.Builder/Writers/Go/GoConventionService.cs +++ b/src/Kiota.Builder/Writers/Go/GoConventionService.cs @@ -69,7 +69,7 @@ currentType.TypeDefinition is not CodeInterface && CodeTypeBase.CodeTypeCollectionKind.Array or CodeTypeBase.CodeTypeCollectionKind.Complex when includeCollectionInformation => "[]", _ => string.Empty, }; - var genericTypeParameters = currentType.GenericTypeParameterValues.Any() ? + var genericTypeParameters = currentType.GenericTypeParameterValues.Count != 0 ? $"[{string.Join(",", currentType.GenericTypeParameterValues.Select(x => GetTypeString(x, targetElement, true, false, true)))}]" : string.Empty; if (currentType.ActionOf) diff --git a/src/Kiota.Builder/Writers/Java/CodeEnumWriter.cs b/src/Kiota.Builder/Writers/Java/CodeEnumWriter.cs index 68b3815149..f643363124 100644 --- a/src/Kiota.Builder/Writers/Java/CodeEnumWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeEnumWriter.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using Kiota.Builder.CodeDOM; -using Kiota.Builder.Extensions; namespace Kiota.Builder.Writers.Java; public class CodeEnumWriter : BaseElementWriter @@ -12,7 +11,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write ArgumentNullException.ThrowIfNull(codeElement); ArgumentNullException.ThrowIfNull(writer); var enumOptions = codeElement.Options.ToArray(); - if (!enumOptions.Any()) + if (enumOptions.Length == 0) return; var enumName = codeElement.Name; writer.WriteLines($"package {(codeElement.Parent as CodeNamespace)?.Name};", diff --git a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs index ab6f9e674f..67dac96b21 100644 --- a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs @@ -208,7 +208,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, .Where(static x => x.Type is CodeType xType && xType.TypeDefinition is CodeClass && !xType.IsCollection) .Select(static x => new Tuple(x, (CodeType)x.Type)) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) writer.StartBlock("} else {"); @@ -217,7 +217,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, if (includeElse) writer.CloseBlock(); } - else if (otherProps.Any()) + else if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } private const string DiscriminatorMappingVarName = "mappingValue"; @@ -246,7 +246,7 @@ private void WriteFactoryMethodBodyForUnionModelForDiscriminatedTypes(CodeMethod if (!includeElse) includeElse = true; } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } private void WriteFactoryMethodBodyForUnionModelForUnDiscriminatedTypes(CodeMethod currentElement, CodeClass parentClass, CodeParameter parseNodeParameter, LanguageWriter writer) @@ -269,7 +269,7 @@ private void WriteFactoryMethodBodyForUnionModelForUnDiscriminatedTypes(CodeMeth includeElse = true; } } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } private void WriteRequestBuilderBody(CodeClass parentClass, CodeMethod codeElement, LanguageWriter writer) @@ -286,7 +286,7 @@ private static void AddNullChecks(CodeMethod codeElement, LanguageWriter writer) private static void WriteRequestBuilderConstructorCall(CodeMethod codeElement, LanguageWriter writer) { var pathParameters = codeElement.Parameters.Where(static x => x.IsOfKind(CodeParameterKind.Path)).Select(static x => x.Name).ToArray(); - var pathParametersRef = pathParameters.Any() ? (", " + pathParameters.Aggregate((x, y) => $"{x}, {y}")) : string.Empty; + var pathParametersRef = pathParameters.Length != 0 ? (", " + pathParameters.Aggregate((x, y) => $"{x}, {y}")) : string.Empty; if (codeElement.Parameters.OfKind(CodeParameterKind.RequestAdapter) is CodeParameter requestAdapterParameter && codeElement.Parameters.OfKind(CodeParameterKind.PathParameters) is CodeParameter urlTemplateParamsParameter) writer.WriteLine($"this({urlTemplateParamsParameter.Name}, {requestAdapterParameter.Name}{pathParametersRef});"); @@ -361,7 +361,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho currentMethod.Parameters.OfKind(CodeParameterKind.PathParameters) is CodeParameter pathParametersParam) { var pathParameters = currentMethod.Parameters.Where(static x => x.IsOfKind(CodeParameterKind.Path)).ToArray(); - if (pathParameters.Any()) + if (pathParameters.Length != 0) conventions.AddParametersAssignment(writer, pathParametersParam.Type, pathParametersParam.Name, @@ -438,7 +438,7 @@ private static void WriteDeserializerBodyForUnionModel(CodeMethod method, CodeCl if (!includeElse) includeElse = true; } - if (otherPropGetters.Any()) + if (otherPropGetters.Length != 0) writer.CloseBlock(decreaseIndent: false); writer.WriteLine($"return new {DeserializerReturnType}();"); } @@ -447,7 +447,7 @@ private static void WriteDeserializerBodyForIntersectionModel(CodeClass parentCl var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { var propertiesNames = complexProperties .Where(static x => x.Getter != null) @@ -472,7 +472,7 @@ private void WriteDeserializerBodyForInheritedModel(CodeMethod method, CodeClass var fieldToSerialize = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom).ToArray(); writer.WriteLines( $"final {DeserializerReturnType} {DeserializerVarName} = new {DeserializerReturnType}({(inherits ? "super." + method.Name + "()" : fieldToSerialize.Length)});"); - if (fieldToSerialize.Any()) + if (fieldToSerialize.Length != 0) { fieldToSerialize .Where(static x => !x.ExistsInBaseType && x.Setter != null) @@ -538,7 +538,7 @@ private static void WriteGeneratorOrExecutorMethodCall(CodeMethod codeElement, R .ToList(); var skipIndex = requestParams.requestBody == null ? 1 : 0; requestInfoParameters.AddRange(paramsList.Where(static x => x == null).Skip(skipIndex).Select(static x => "null")); - var paramsCall = requestInfoParameters.Any() ? requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}") : string.Empty; + var paramsCall = requestInfoParameters.Count != 0 ? requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}") : string.Empty; writer.WriteLine($"{prefix}{methodName}({paramsCall});"); } private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams requestParams, CodeClass currentClass, LanguageWriter writer) @@ -608,7 +608,7 @@ private void WriteSerializerBodyForUnionModel(CodeClass parentClass, CodeMethod if (!includeElse) includeElse = true; } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, CodeMethod method, LanguageWriter writer) @@ -632,7 +632,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Code var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) { @@ -644,13 +644,13 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Code .Select(static x => $"this.{x.Getter!.Name}()") .OrderBy(static x => x) .Aggregate(static (x, y) => $"{x}, {y}"); - WriteSerializationMethodCall(complexProperties.First(), method, writer, "null", propertiesNames); + WriteSerializationMethodCall(complexProperties[0], method, writer, "null", propertiesNames); if (includeElse) { writer.CloseBlock(); } } - else if (otherProps.Any()) + else if (otherProps.Length != 0) { writer.CloseBlock(decreaseIndent: false); } diff --git a/src/Kiota.Builder/Writers/Java/JavaConventionService.cs b/src/Kiota.Builder/Writers/Java/JavaConventionService.cs index be639debcb..fb731ef008 100644 --- a/src/Kiota.Builder/Writers/Java/JavaConventionService.cs +++ b/src/Kiota.Builder/Writers/Java/JavaConventionService.cs @@ -106,7 +106,7 @@ public void WriteLongDescription(CodeElement element, LanguageWriter writer, IEn if (additionalRemarks == default) additionalRemarks = Enumerable.Empty(); var remarks = additionalRemarks.ToArray(); - if (documentation.DescriptionAvailable || documentation.ExternalDocumentationAvailable || remarks.Any()) + if (documentation.DescriptionAvailable || documentation.ExternalDocumentationAvailable || remarks.Length != 0) { writer.WriteLine(DocCommentStart); if (documentation.DescriptionAvailable) @@ -146,7 +146,7 @@ internal void AddParametersAssignment(LanguageWriter writer, CodeTypeBase pathPa varName = TempDictionaryVarName; writer.WriteLine($"final {mapTypeName} {varName} = new {mapTypeName}({pathParametersReference});"); } - if (parameters.Any()) + if (parameters.Length != 0) writer.WriteLines(parameters.Select(p => $"{varName}.put(\"{p.Item2}\", {p.Item3});" ).ToArray()); diff --git a/src/Kiota.Builder/Writers/NamespaceClassNamesProvider.cs b/src/Kiota.Builder/Writers/NamespaceClassNamesProvider.cs index 0313fe3902..0b7c754fd3 100644 --- a/src/Kiota.Builder/Writers/NamespaceClassNamesProvider.cs +++ b/src/Kiota.Builder/Writers/NamespaceClassNamesProvider.cs @@ -21,7 +21,7 @@ public static void WriteClassesInOrderOfInheritance(CodeNamespace codeNamespace, var inheritanceBranches = codeNamespace.Classes.Where(c => c.IsOfKind(CodeClassKind.Model)) .Select(static x => x.GetInheritanceTree(true)) .ToList(); - var maxDepth = inheritanceBranches.Any() ? inheritanceBranches.Max(static x => x.Count) : 0; + var maxDepth = inheritanceBranches.Count != 0 ? inheritanceBranches.Max(static x => x.Count) : 0; for (var depth = 0; depth < maxDepth; depth++) foreach (var name in inheritanceBranches .Where(x => x.Count > depth) diff --git a/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs index 47397d2fcf..77784f1f0f 100644 --- a/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs @@ -247,7 +247,7 @@ private static void AssignPropertyFromParameter(CodeClass parentClass, CodeMetho { var parameters = currentMethod.Parameters.Where(x => x.IsOfKind(parameterKind)).ToList(); var properties = parentClass.GetPropertiesOfKind(propertyKind).ToList(); - if (parameters.Any() && parameters.Count.Equals(properties.Count)) + if (parameters.Count != 0 && parameters.Count.Equals(properties.Count)) { for (var i = 0; i < parameters.Count; i++) { @@ -368,7 +368,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Lang .Where(static x => x.Getter != null) .Where(static x => x.Type is CodeType { TypeDefinition: CodeClass } && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) { @@ -384,7 +384,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Lang writer.CloseBlock(); } } - else if (otherProps.Any()) + else if (otherProps.Length != 0) { writer.CloseBlock(decreaseIndent: false); } @@ -407,7 +407,7 @@ private void WriteSerializerBodyForUnionModel(CodeClass parentClass, LanguageWri if (!includeElse) includeElse = true; } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } @@ -627,7 +627,7 @@ private void WriteDeserializerBodyForInheritedModel(CodeMethod method, CodeClass writer.WriteLines( $"return {((extendsModelClass) ? $"array_merge(parent::{method.Name.ToFirstCharacterLowerCase()}(), [" : " [")}"); writer.IncreaseIndent(); - if (codeProperties.Any()) + if (codeProperties.Length != 0) { codeProperties .Where(static x => !x.ExistsInBaseType && x.Setter != null) @@ -665,7 +665,7 @@ private static void WriteDeserializerBodyForIntersectionModel(CodeClass parentCl var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { var propertiesNames = complexProperties .Where(static x => x.Getter != null) @@ -704,7 +704,7 @@ private static void WriteDeserializerBodyForUnionModel(CodeMethod method, CodeCl if (!includeElse) includeElse = true; } - if (otherPropGetters.Any()) + if (otherPropGetters.Length != 0) writer.CloseBlock(decreaseIndent: false); writer.WriteLine($"return [];"); } @@ -731,7 +731,7 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, CodeClass parentCl .Select(conventions.GetParameterName) .ToArray(); var joinedParams = string.Empty; - if (requestInfoParameters.Any()) + if (requestInfoParameters.Length != 0) { joinedParams = string.Join(", ", requestInfoParameters); } @@ -901,7 +901,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, .Select(static x => new Tuple(x, (CodeType)x.Type)) .Where(static x => x.Item2.TypeDefinition is CodeClass && !x.Item2.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) writer.StartBlock("} else {"); @@ -910,7 +910,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, if (includeElse) writer.CloseBlock(); } - else if (otherProps.Any()) + else if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } @@ -941,7 +941,7 @@ private void WriteFactoryMethodBodyForUnionModelForDiscriminatedTypes(CodeMethod if (!includeElse) includeElse = true; } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } @@ -965,7 +965,7 @@ private void WriteFactoryMethodBodyForUnionModelForUnDiscriminatedTypes(CodeMeth if (!includeElse) includeElse = true; } - if (otherProps.Any()) + if (otherProps.Length != 0) writer.CloseBlock(decreaseIndent: false); } diff --git a/src/Kiota.Builder/Writers/Php/PhpConventionService.cs b/src/Kiota.Builder/Writers/Php/PhpConventionService.cs index edfb8f6246..cf02f48669 100644 --- a/src/Kiota.Builder/Writers/Php/PhpConventionService.cs +++ b/src/Kiota.Builder/Writers/Php/PhpConventionService.cs @@ -156,7 +156,7 @@ public void WriteLongDescription(CodeDocumentation codeDocumentation, LanguageWr var enumerableArray = additionalRemarks as string[] ?? additionalRemarks.ToArray(); if (codeDocumentation.DescriptionAvailable || codeDocumentation.ExternalDocumentationAvailable || - enumerableArray.Any()) + enumerableArray.Length != 0) { writer.WriteLine(DocCommentStart); if (codeDocumentation.DescriptionAvailable) @@ -175,7 +175,7 @@ public void AddRequestBuilderBody(string returnType, LanguageWriter writer, stri { ArgumentNullException.ThrowIfNull(writer); var joined = string.Empty; - if (pathParameters?.ToList() is { } codeParameters && codeParameters.Any()) + if (pathParameters?.ToList() is { } codeParameters && codeParameters.Count != 0) { joined = $", {string.Join(", ", codeParameters.Select(static x => $"${x.Name.ToFirstCharacterLowerCase()}"))}"; } @@ -240,7 +240,7 @@ public void WriteNamespaceAndImports(ClassDeclaration codeElement, LanguageWrite internal void AddRequestBuilderBody(CodeClass parentClass, string returnType, LanguageWriter writer, string? urlTemplateVarName = default, IEnumerable? pathParameters = default) { var codeParameters = pathParameters?.ToArray(); - var codePathParametersSuffix = !(codeParameters?.Any() ?? false) ? string.Empty : $", {string.Join(", ", codeParameters.Select(x => $"${x.Name.ToFirstCharacterLowerCase()}"))}"; + var codePathParametersSuffix = codeParameters?.Length > 0 ? $", {string.Join(", ", codeParameters.Select(x => $"${x.Name.ToFirstCharacterLowerCase()}"))}" : string.Empty; var urlTemplateParams = string.IsNullOrEmpty(urlTemplateVarName) && parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters) is CodeProperty pathParametersProperty ? $"$this->{pathParametersProperty.Name}" : urlTemplateVarName; @@ -251,7 +251,7 @@ internal void AddParametersAssignment(LanguageWriter writer, CodeTypeBase pathPa { if (pathParametersType == null) return; writer.WriteLine($"${TempDictionaryVarName} = {pathParametersReference};"); - if (parameters.Any()) + if (parameters.Length != 0) writer.WriteLines(parameters.Select(p => $"${TempDictionaryVarName}['{p.Item2}'] = {p.Item3};" )); diff --git a/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs index a694f10b85..295f2cb640 100644 --- a/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs @@ -185,7 +185,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, .Where(static x => x.Type is CodeType xType && xType.TypeDefinition is CodeClass && !xType.IsCollection) .Select(static x => new Tuple(x, (CodeType)x.Type)) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) { @@ -336,7 +336,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho .Where(static x => x.IsOfKind(CodeParameterKind.Path)) .Select(static x => (string.IsNullOrEmpty(x.SerializationName) ? x.Name : x.SerializationName, x.Name)) .ToArray(); - if (pathParameters.Any()) + if (pathParameters.Length != 0) { writer.StartBlock($"if isinstance({pathParametersParameter.Name}, dict):"); foreach (var parameter in pathParameters) @@ -517,7 +517,7 @@ private void WriteDeserializerBodyForIntersectionModel(CodeClass parentClass, La var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { var propertiesNames = complexProperties .Select(static x => x.Name) @@ -566,7 +566,7 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requ .OfType() .Select(static x => x.Name) .ToArray(); - if (requestInfoParameters.Any()) + if (requestInfoParameters.Length != 0) { writer.IncreaseIndent(); writer.WriteLine(requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}")); @@ -684,7 +684,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Lang var complexProperties = parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is CodeType propType && propType.TypeDefinition is CodeClass && !x.Type.IsCollection) .ToArray(); - if (complexProperties.Any()) + if (complexProperties.Length != 0) { if (includeElse) { diff --git a/src/Kiota.Builder/Writers/Python/CodeUsingWriter.cs b/src/Kiota.Builder/Writers/Python/CodeUsingWriter.cs index e16c9ab232..101b43ca5b 100644 --- a/src/Kiota.Builder/Writers/Python/CodeUsingWriter.cs +++ b/src/Kiota.Builder/Writers/Python/CodeUsingWriter.cs @@ -28,7 +28,7 @@ public void WriteExternalImports(ClassDeclaration codeElement, LanguageWriter wr .GroupBy(static x => x.Item3) .OrderBy(static x => x.Key) .ToArray(); - if (externalImportSymbolsAndPaths.Any()) + if (externalImportSymbolsAndPaths.Length != 0) { foreach (var codeUsing in externalImportSymbolsAndPaths) if (!string.IsNullOrWhiteSpace(codeUsing.Key)) @@ -100,7 +100,7 @@ public void WriteConditionalInternalImports(ClassDeclaration codeElement, Langua .Where(static x => !string.IsNullOrEmpty(x.Key)) .OrderBy(static x => x.Key, StringComparer.OrdinalIgnoreCase) .ToArray(); - if (internalImportSymbolsAndPaths.Any()) + if (internalImportSymbolsAndPaths.Length != 0) { writer.WriteLine("if TYPE_CHECKING:"); writer.IncreaseIndent(); @@ -136,7 +136,7 @@ public void WriteDeferredImport(CodeClass parentClass, string typeName, Language private static void WriteCodeUsings(IGrouping[] importSymbolsAndPaths, LanguageWriter writer) { - if (importSymbolsAndPaths.Any()) + if (importSymbolsAndPaths.Length != 0) { foreach (var codeUsing in importSymbolsAndPaths) writer.WriteLine($"from {codeUsing.Key} import {codeUsing.Select(x => GetAliasedSymbol(x.Item1, x.Item2)).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).Aggregate(static (x, y) => x + ", " + y)}"); diff --git a/src/Kiota.Builder/Writers/Python/PythonConventionService.cs b/src/Kiota.Builder/Writers/Python/PythonConventionService.cs index bccd06ddd5..bb2ace2a76 100644 --- a/src/Kiota.Builder/Writers/Python/PythonConventionService.cs +++ b/src/Kiota.Builder/Writers/Python/PythonConventionService.cs @@ -33,7 +33,7 @@ internal void AddParametersAssignment(LanguageWriter writer, CodeTypeBase? pathP { if (pathParametersType == null) return; writer.WriteLine($"{TempDictionaryVarName} = get_path_parameters({pathParametersReference})"); - if (parameters.Any()) + if (parameters.Length != 0) writer.WriteLines(parameters.Select(p => $"{TempDictionaryVarName}[\"{p.Item2}\"] = {p.Item3}" )); @@ -169,7 +169,7 @@ public void WriteLongDescription(CodeDocumentation documentation, LanguageWriter if (additionalRemarks == default) additionalRemarks = Enumerable.Empty(); var additionalRemarksArray = additionalRemarks.ToArray(); - if (documentation.DescriptionAvailable || documentation.ExternalDocumentationAvailable || additionalRemarksArray.Any()) + if (documentation.DescriptionAvailable || documentation.ExternalDocumentationAvailable || additionalRemarksArray.Length != 0) { writer.WriteLine(DocCommentStart); if (documentation.DescriptionAvailable) diff --git a/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs b/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs index cbc7a6c5f2..7996ba6944 100644 --- a/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs +++ b/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs @@ -54,7 +54,7 @@ public override (string, string, string) GetRelativeImportPathForUsing(CodeUsing protected static new string GetRemainingImportPath(IEnumerable remainingSegments) { var segments = remainingSegments.Select(static x => x.ToSnakeCase()).ToArray(); - if (segments.Any()) + if (segments.Length != 0) return segments.Aggregate(static (x, y) => $"{x}.{y}") + '.'; return string.Empty; } diff --git a/src/Kiota.Builder/Writers/RelativeImportManager.cs b/src/Kiota.Builder/Writers/RelativeImportManager.cs index cc814c0ba8..4c1921b875 100644 --- a/src/Kiota.Builder/Writers/RelativeImportManager.cs +++ b/src/Kiota.Builder/Writers/RelativeImportManager.cs @@ -70,7 +70,7 @@ protected string GetImportRelativePathFromNamespaces(CodeNamespace currentNamesp protected static string GetRemainingImportPath(IEnumerable remainingSegments) { var segments = remainingSegments.Select(x => x.ToFirstCharacterLowerCase()).ToArray(); - if (segments.Any()) + if (segments.Length != 0) return segments.Aggregate(static (x, y) => $"{x}/{y}") + '/'; return string.Empty; } diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index 7773f543c7..e07578e0d7 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -255,7 +255,7 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requ .OfType() .Select(static x => x.Name.ToSnakeCase()) .ToArray(); - if (requestInfoParameters.Any()) + if (requestInfoParameters.Length != 0) { writer.IncreaseIndent(); writer.WriteLine(requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}")); @@ -360,7 +360,7 @@ private void WriteMethodDocumentation(CodeMethod code, LanguageWriter writer) { var isDescriptionPresent = !string.IsNullOrEmpty(code.Documentation.Description); var parametersWithDescription = code.Parameters.Where(x => !string.IsNullOrEmpty(code.Documentation.Description)).OrderBy(static x => x.Name, StringComparer.OrdinalIgnoreCase).ToArray(); - if (isDescriptionPresent || parametersWithDescription.Any()) + if (isDescriptionPresent || parametersWithDescription.Length != 0) { writer.WriteLine(conventions.DocCommentStart); if (isDescriptionPresent) diff --git a/src/Kiota.Builder/Writers/Swift/CodeClassDeclarationWriter.cs b/src/Kiota.Builder/Writers/Swift/CodeClassDeclarationWriter.cs index e8ae562167..ae106e1cfd 100644 --- a/src/Kiota.Builder/Writers/Swift/CodeClassDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Swift/CodeClassDeclarationWriter.cs @@ -17,7 +17,7 @@ protected override void WriteTypeDeclaration(ClassDeclaration codeElement, Langu .Union(codeElement.Implements.Select(static x => x.Name)) .Where(static x => x != null) .ToArray(); - var derivation = derivedTypes.Any() ? ": " + derivedTypes.Select(x => x.ToFirstCharacterUpperCase()).Aggregate(static (x, y) => $"{x}, {y}") + " " : string.Empty; + var derivation = derivedTypes.Length != 0 ? ": " + derivedTypes.Select(x => x.ToFirstCharacterUpperCase()).Aggregate(static (x, y) => $"{x}, {y}") + " " : string.Empty; if (codeElement.Parent is CodeClass parentClass) conventions.WriteShortDescription(parentClass.Documentation.Description, writer); writer.WriteLine($"public class {codeElement.Name.ToFirstCharacterUpperCase()} {derivation}{{"); diff --git a/src/Kiota.Builder/Writers/Swift/CodeProprietableBlockDeclarationWriter.cs b/src/Kiota.Builder/Writers/Swift/CodeProprietableBlockDeclarationWriter.cs index 32a41a1133..a4c5df7a60 100644 --- a/src/Kiota.Builder/Writers/Swift/CodeProprietableBlockDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Swift/CodeProprietableBlockDeclarationWriter.cs @@ -22,7 +22,7 @@ public override void WriteCodeElement(T codeElement, LanguageWriter writer) .OrderBy(static x => x.Count(static y => y == '.')) .ThenBy(x => x) .ToList(); - if (importSegments.Any()) + if (importSegments.Count != 0) { importSegments.ForEach(x => writer.WriteLine($"import {x}")); writer.WriteLine(string.Empty); diff --git a/src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs index 8f312d9115..2720f0a800 100644 --- a/src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/TypeScript/CodeMethodWriter.cs @@ -301,7 +301,7 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, CodeClass parentCl .OfType() .Select(static x => x.Name) .ToArray(); - if (requestInfoParameters.Any()) + if (requestInfoParameters.Length != 0) { writer.IncreaseIndent(); writer.WriteLine(requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}")); diff --git a/src/Kiota.Builder/Writers/TypeScript/TypeScriptConventionService.cs b/src/Kiota.Builder/Writers/TypeScript/TypeScriptConventionService.cs index ea417df307..64b283769b 100644 --- a/src/Kiota.Builder/Writers/TypeScript/TypeScriptConventionService.cs +++ b/src/Kiota.Builder/Writers/TypeScript/TypeScriptConventionService.cs @@ -48,7 +48,7 @@ internal void AddParametersAssignment(LanguageWriter writer, CodeTypeBase pathPa varName = TempDictionaryVarName; writer.WriteLine($"const {varName} = getPathParameters({pathParametersReference});"); } - if (parameters.Any()) + if (parameters.Length != 0) writer.WriteLines(parameters.Select(p => $"{varName}[\"{p.Item2}\"] = {p.Item3}" ).ToArray()); @@ -81,7 +81,7 @@ public override string GetTypeString(CodeTypeBase code, CodeElement targetElemen if (code is CodeType currentType) { var typeName = GetTypeAlias(currentType, targetElement) is string alias && !string.IsNullOrEmpty(alias) ? alias : TranslateType(currentType); - var genericParameters = currentType.GenericTypeParameterValues.Any() ? + var genericParameters = currentType.GenericTypeParameterValues.Count != 0 ? $"<{string.Join(", ", currentType.GenericTypeParameterValues.Select(x => GetTypeString(x, targetElement, includeCollectionInformation)))}>" : string.Empty; return $"{typeName}{collectionSuffix}{genericParameters}"; @@ -148,7 +148,7 @@ public void WriteLongDescription(IDocumentedElement documentedElement, LanguageW if (additionalRemarks == default) additionalRemarks = Enumerable.Empty(); var remarks = additionalRemarks.Where(static x => !string.IsNullOrEmpty(x)).ToArray(); - if (documentedElement.Documentation.DescriptionAvailable || documentedElement.Documentation.ExternalDocumentationAvailable || remarks.Any()) + if (documentedElement.Documentation.DescriptionAvailable || documentedElement.Documentation.ExternalDocumentationAvailable || remarks.Length != 0) { writer.WriteLine(DocCommentStart); if (documentedElement.Documentation.DescriptionAvailable) diff --git a/src/kiota/Handlers/KiotaGenerationCommandHandler.cs b/src/kiota/Handlers/KiotaGenerationCommandHandler.cs index bb95aec6d4..9981e0e3f8 100644 --- a/src/kiota/Handlers/KiotaGenerationCommandHandler.cs +++ b/src/kiota/Handlers/KiotaGenerationCommandHandler.cs @@ -93,20 +93,20 @@ public override async Task InvokeAsync(InvocationContext context) Configuration.Generation.ExcludeBackwardCompatible = excludeBackwardCompatible; Configuration.Generation.IncludeAdditionalData = includeAdditionalData; Configuration.Generation.Language = language; - if (serializer.Any()) + if (serializer.Count != 0) Configuration.Generation.Serializers = serializer.Select(static x => x.TrimQuotes()).ToHashSet(StringComparer.OrdinalIgnoreCase); - if (deserializer.Any()) + if (deserializer.Count != 0) Configuration.Generation.Deserializers = deserializer.Select(static x => x.TrimQuotes()).ToHashSet(StringComparer.OrdinalIgnoreCase); - if (includePatterns.Any()) + if (includePatterns.Count != 0) Configuration.Generation.IncludePatterns = includePatterns.Select(static x => x.TrimQuotes()).ToHashSet(StringComparer.OrdinalIgnoreCase); - if (excludePatterns.Any()) + if (excludePatterns.Count != 0) Configuration.Generation.ExcludePatterns = excludePatterns.Select(static x => x.TrimQuotes()).ToHashSet(StringComparer.OrdinalIgnoreCase); - if (disabledValidationRules.Any()) + if (disabledValidationRules.Count != 0) Configuration.Generation.DisabledValidationRules = disabledValidationRules .Select(static x => x.TrimQuotes()) .SelectMany(static x => x.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) .ToHashSet(StringComparer.OrdinalIgnoreCase); - if (structuredMimeTypes.Any()) + if (structuredMimeTypes.Count != 0) Configuration.Generation.StructuredMimeTypes = new(structuredMimeTypes.SelectMany(static x => x.Split(new[] { ' ' })) .Select(static x => x.TrimQuotes())); diff --git a/src/kiota/KiotaConfigurationExtensions.cs b/src/kiota/KiotaConfigurationExtensions.cs index a44dce586b..70a45841b9 100644 --- a/src/kiota/KiotaConfigurationExtensions.cs +++ b/src/kiota/KiotaConfigurationExtensions.cs @@ -74,7 +74,7 @@ private static void LoadCollection(this IConfigurationSection section, ICollecti ArgumentNullException.ThrowIfNull(collection); if (section is null) return; var children = section.GetChildren(); - if (children.Any() && collection.Any()) collection.Clear(); + if (children.Any() && collection.Count != 0) collection.Clear(); foreach (var item in children) { if (section[item.Key] is string value && !string.IsNullOrEmpty(value)) @@ -86,7 +86,7 @@ private static void LoadHashSet(this IConfigurationSection section, HashSet ShowAsync(string descriptionPath, string[] include var fullUrlTreeNode = await builder.GetUrlTreeNodeAsync(cancellationToken); configuration.IncludePatterns = includeFilters.ToHashSet(StringComparer.Ordinal); configuration.ExcludePatterns = excludeFilters.ToHashSet(StringComparer.Ordinal); - var filteredTreeNode = configuration.IncludePatterns.Any() || configuration.ExcludePatterns.Any() ? + var filteredTreeNode = configuration.IncludePatterns.Count != 0 || configuration.ExcludePatterns.Count != 0 ? await new KiotaBuilder(new NoopLogger(), configuration, httpClient).GetUrlTreeNodeAsync(cancellationToken) : // openapi.net seems to have side effects between tree node and the document, we need to drop all references default; var filteredPaths = filteredTreeNode is null ? new HashSet() : GetOperationsFromTreeNode(filteredTreeNode).ToHashSet(StringComparer.Ordinal); @@ -155,13 +155,13 @@ public async Task> GenerateAsync(string openAPIFilePath, string o configuration.ClearCache = clearCache; configuration.ExcludeBackwardCompatible = excludeBackwardCompatible; configuration.IncludeAdditionalData = includeAdditionalData; - if (disabledValidationRules is not null && disabledValidationRules.Any()) + if (disabledValidationRules is not null && disabledValidationRules.Length != 0) configuration.DisabledValidationRules = disabledValidationRules.ToHashSet(StringComparer.OrdinalIgnoreCase); - if (serializers is not null && serializers.Any()) + if (serializers is not null && serializers.Length != 0) configuration.Serializers = serializers.ToHashSet(StringComparer.OrdinalIgnoreCase); - if (deserializers is not null && deserializers.Any()) + if (deserializers is not null && deserializers.Length != 0) configuration.Deserializers = deserializers.ToHashSet(StringComparer.OrdinalIgnoreCase); - if (structuredMimeTypes is not null && structuredMimeTypes.Any()) + if (structuredMimeTypes is not null && structuredMimeTypes.Length != 0) configuration.StructuredMimeTypes = new(structuredMimeTypes); if (!string.IsNullOrEmpty(clientClassName)) configuration.ClientClassName = clientClassName; @@ -210,14 +210,14 @@ private static PathItem ConvertOpenApiUrlTreeNodeToPathItem(OpenApiUrlTreeNode n NormalizeOperationNodePath(node, x.Key), x.Key.ToString().ToUpperInvariant(), Array.Empty(), - !filteredPaths.Any() || filteredPaths.Contains(NormalizeOperationNodePath(node, x.Key, true)), + filteredPaths.Count == 0 || filteredPaths.Contains(NormalizeOperationNodePath(node, x.Key, true)), true, x.Value.ExternalDocs?.Url)) : Enumerable.Empty()) .OrderByDescending(static x => x.isOperation) .ThenBy(static x => x.segment, StringComparer.OrdinalIgnoreCase) .ToArray(); - return new PathItem(node.Path, node.Segment, children, !filteredPaths.Any() || Array.Exists(children, static x => x.isOperation) && children.Where(static x => x.isOperation).All(static x => x.selected)); + return new PathItem(node.Path, node.Segment, children, filteredPaths.Count == 0 || Array.Exists(children, static x => x.isOperation) && children.Where(static x => x.isOperation).All(static x => x.selected)); } protected static string GetAbsolutePath(string source) { From 884571b593e35531bccd547146c65756ca1ba3bd Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 09:49:59 -0500 Subject: [PATCH 03/10] - code linting: character comparison Signed-off-by: Vincent Biret --- src/Kiota.Builder/Extensions/StringExtensions.cs | 4 ++-- src/Kiota.Builder/Refiners/GoRefiner.cs | 6 +++--- src/Kiota.Builder/Refiners/JavaRefiner.cs | 4 ++-- src/Kiota.Builder/Refiners/PythonRefiner.cs | 4 ++-- src/Kiota.Builder/Refiners/SwiftRefiner.cs | 2 +- src/Kiota.Builder/Refiners/TypeScriptRefiner.cs | 4 ++-- src/Kiota.Builder/Writers/CSharp/CodePropertyWriter.cs | 2 +- src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs | 2 +- src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs | 2 +- .../Writers/Go/CodeProprietableBlockDeclarationWriter.cs | 2 +- 10 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Kiota.Builder/Extensions/StringExtensions.cs b/src/Kiota.Builder/Extensions/StringExtensions.cs index acc95d5a85..00388b3e2b 100644 --- a/src/Kiota.Builder/Extensions/StringExtensions.cs +++ b/src/Kiota.Builder/Extensions/StringExtensions.cs @@ -137,7 +137,7 @@ private static string HashString(string? input) public static string ReplaceDoubleQuoteWithSingleQuote(this string? current) { if (string.IsNullOrEmpty(current)) return string.Empty; - return current.StartsWith("\"", StringComparison.OrdinalIgnoreCase) ? current.Replace("'", "\\'", StringComparison.OrdinalIgnoreCase).Replace('\"', '\'') : current; + return current.StartsWith('"') ? current.Replace("'", "\\'", StringComparison.OrdinalIgnoreCase).Replace('\"', '\'') : current; } public static string ReplaceDotsWithSlashInNamespaces(this string? namespaced) @@ -229,7 +229,7 @@ public static string CleanupSymbolName(this string? original) private static string NormalizeSymbolsBeforeCleanup(string original) { var result = original; - if (result.StartsWith("-", StringComparison.OrdinalIgnoreCase)) + if (result.StartsWith('-')) { result = string.Concat("minus_", result.AsSpan(1)); } diff --git a/src/Kiota.Builder/Refiners/GoRefiner.cs b/src/Kiota.Builder/Refiners/GoRefiner.cs index 8bc0ae4089..00f848be39 100644 --- a/src/Kiota.Builder/Refiners/GoRefiner.cs +++ b/src/Kiota.Builder/Refiners/GoRefiner.cs @@ -164,8 +164,8 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance }); AddSerializationModulesImport( generatedCode, - new[] { "github.com/microsoft/kiota-abstractions-go/serialization.SerializationWriterFactory", "github.com/microsoft/kiota-abstractions-go.RegisterDefaultSerializer" }, - new[] { "github.com/microsoft/kiota-abstractions-go/serialization.ParseNodeFactory", "github.com/microsoft/kiota-abstractions-go.RegisterDefaultDeserializer" }); + ["github.com/microsoft/kiota-abstractions-go/serialization.SerializationWriterFactory", "github.com/microsoft/kiota-abstractions-go.RegisterDefaultSerializer"], + ["github.com/microsoft/kiota-abstractions-go/serialization.ParseNodeFactory", "github.com/microsoft/kiota-abstractions-go.RegisterDefaultDeserializer"]); cancellationToken.ThrowIfCancellationRequested(); AddParentClassToErrorClasses( generatedCode, @@ -614,7 +614,7 @@ private static void CorrectMethodType(CodeMethod currentMethod) } currentMethod.Parameters.Where(static x => x.IsOfKind(CodeParameterKind.RequestAdapter)) - .Where(static x => x.Type.Name.StartsWith("I", StringComparison.InvariantCultureIgnoreCase)) + .Where(static x => x.Type.Name.StartsWith('I')) .ToList() .ForEach(static x => x.Type.Name = x.Type.Name[1..]); // removing the "I" } diff --git a/src/Kiota.Builder/Refiners/JavaRefiner.cs b/src/Kiota.Builder/Refiners/JavaRefiner.cs index 722fc4a8df..b87a10325d 100644 --- a/src/Kiota.Builder/Refiners/JavaRefiner.cs +++ b/src/Kiota.Builder/Refiners/JavaRefiner.cs @@ -333,7 +333,7 @@ private static void CorrectMethodType(CodeMethod currentMethod) { x.Optional = false; x.Type.IsNullable = true; - if (x.Type.Name.StartsWith("i", StringComparison.OrdinalIgnoreCase)) + if (x.Type.Name.StartsWith('I')) x.Type.Name = x.Type.Name[1..]; }); else if (currentMethod.IsOfKind(CodeMethodKind.Deserializer)) @@ -344,7 +344,7 @@ private static void CorrectMethodType(CodeMethod currentMethod) else if (currentMethod.IsOfKind(CodeMethodKind.ClientConstructor, CodeMethodKind.Constructor, CodeMethodKind.RawUrlConstructor)) { currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.RequestAdapter, CodeParameterKind.BackingStore)) - .Where(x => x.Type.Name.StartsWith("I", StringComparison.OrdinalIgnoreCase)) + .Where(x => x.Type.Name.StartsWith('I')) .ToList() .ForEach(x => x.Type.Name = x.Type.Name[1..]); // removing the "I" currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.RequestAdapter, CodeParameterKind.PathParameters)) diff --git a/src/Kiota.Builder/Refiners/PythonRefiner.cs b/src/Kiota.Builder/Refiners/PythonRefiner.cs index 720991d244..232256c7a5 100644 --- a/src/Kiota.Builder/Refiners/PythonRefiner.cs +++ b/src/Kiota.Builder/Refiners/PythonRefiner.cs @@ -266,13 +266,13 @@ private static void CorrectPropertyType(CodeProperty currentProperty) private static void CorrectMethodType(CodeMethod currentMethod) { if (currentMethod.IsOfKind(CodeMethodKind.Serializer)) - currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.Serializer) && x.Type.Name.StartsWith("i", StringComparison.OrdinalIgnoreCase)).ToList().ForEach(x => x.Type.Name = x.Type.Name[1..]); + currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.Serializer) && x.Type.Name.StartsWith('I')).ToList().ForEach(x => x.Type.Name = x.Type.Name[1..]); else if (currentMethod.IsOfKind(CodeMethodKind.Deserializer)) currentMethod.ReturnType.Name = "Dict[str, Callable[[ParseNode], None]]"; else if (currentMethod.IsOfKind(CodeMethodKind.ClientConstructor, CodeMethodKind.Constructor, CodeMethodKind.Factory)) { currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.RequestAdapter, CodeParameterKind.BackingStore, CodeParameterKind.ParseNode)) - .Where(static x => x.Type.Name.StartsWith("I", StringComparison.InvariantCultureIgnoreCase)) + .Where(static x => x.Type.Name.StartsWith('I')) .ToList() .ForEach(static x => x.Type.Name = x.Type.Name[1..]); // removing the "I" var urlTplParams = currentMethod.Parameters.FirstOrDefault(x => x.IsOfKind(CodeParameterKind.PathParameters)); diff --git a/src/Kiota.Builder/Refiners/SwiftRefiner.cs b/src/Kiota.Builder/Refiners/SwiftRefiner.cs index 18e31276de..1a2cc104c5 100644 --- a/src/Kiota.Builder/Refiners/SwiftRefiner.cs +++ b/src/Kiota.Builder/Refiners/SwiftRefiner.cs @@ -101,7 +101,7 @@ private static void CorrectMethodType(CodeMethod currentMethod) if (rawUrlParam != null) rawUrlParam.Type.IsNullable = false; currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.RequestAdapter)) - .Where(x => x.Type.Name.StartsWith("I", StringComparison.InvariantCultureIgnoreCase)) + .Where(x => x.Type.Name.StartsWith('I')) .ToList() .ForEach(x => x.Type.Name = x.Type.Name[1..]); // removing the "I" } diff --git a/src/Kiota.Builder/Refiners/TypeScriptRefiner.cs b/src/Kiota.Builder/Refiners/TypeScriptRefiner.cs index 2fc73fcb1c..ae38eabcfe 100644 --- a/src/Kiota.Builder/Refiners/TypeScriptRefiner.cs +++ b/src/Kiota.Builder/Refiners/TypeScriptRefiner.cs @@ -435,13 +435,13 @@ private static void CorrectMethodType(CodeMethod currentMethod) requestBodyParam.Type.IsNullable = false; } else if (currentMethod.IsOfKind(CodeMethodKind.Serializer)) - currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.Serializer) && x.Type.Name.StartsWith("i", StringComparison.OrdinalIgnoreCase)).ToList().ForEach(x => x.Type.Name = x.Type.Name[1..]); + currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.Serializer) && x.Type.Name.StartsWith('I')).ToList().ForEach(x => x.Type.Name = x.Type.Name[1..]); else if (currentMethod.IsOfKind(CodeMethodKind.Deserializer)) currentMethod.ReturnType.Name = "Record void>"; else if (currentMethod.IsOfKind(CodeMethodKind.ClientConstructor, CodeMethodKind.Constructor)) { currentMethod.Parameters.Where(x => x.IsOfKind(CodeParameterKind.RequestAdapter, CodeParameterKind.BackingStore)) - .Where(x => x.Type.Name.StartsWith("I", StringComparison.InvariantCultureIgnoreCase)) + .Where(x => x.Type.Name.StartsWith('I')) .ToList() .ForEach(x => x.Type.Name = x.Type.Name[1..]); // removing the "I" if (currentMethod.Parameters.FirstOrDefault(x => x.IsOfKind(CodeParameterKind.PathParameters)) is CodeParameter urlTplParams && urlTplParams.Type is CodeType originalType) diff --git a/src/Kiota.Builder/Writers/CSharp/CodePropertyWriter.cs b/src/Kiota.Builder/Writers/CSharp/CodePropertyWriter.cs index df0d692458..48fef8fa98 100644 --- a/src/Kiota.Builder/Writers/CSharp/CodePropertyWriter.cs +++ b/src/Kiota.Builder/Writers/CSharp/CodePropertyWriter.cs @@ -12,7 +12,7 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w ArgumentNullException.ThrowIfNull(writer); if (codeElement.ExistsInExternalBaseType) return; var propertyType = conventions.GetTypeString(codeElement.Type, codeElement); - var isNullableReferenceType = !propertyType.EndsWith("?", StringComparison.OrdinalIgnoreCase) + var isNullableReferenceType = !propertyType.EndsWith('?') && codeElement.IsOfKind( CodePropertyKind.Custom, CodePropertyKind.QueryParameter);// Other property types are appropriately constructor initialized diff --git a/src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs b/src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs index 5158bb1bd2..998f19ec6e 100644 --- a/src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Go/CodeFileDeclarationWriter.cs @@ -28,7 +28,7 @@ public override void WriteCodeElement(CodeFileDeclaration codeElement, LanguageW .AllUsingsFromChildElements .Union(codeElement.Parent is CodeClass currentClass ? currentClass.InnerClasses.SelectMany(static x => x.Usings) : Enumerable.Empty()) .Where(static x => x.Declaration != null && x.Declaration.IsExternal) - .Select(static x => new Tuple(x.Name.StartsWith("*", StringComparison.OrdinalIgnoreCase) ? x.Name[1..] : x.Declaration!.Name.GetNamespaceImportSymbol(), x.Declaration!.Name)) + .Select(static x => new Tuple(x.Name.StartsWith('*') ? x.Name[1..] : x.Declaration!.Name.GetNamespaceImportSymbol(), x.Declaration!.Name)) .Distinct()) .OrderBy(static x => x.Item2.Count(static y => y == '/')) .ThenBy(static x => x) diff --git a/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs index 9e37aa82b3..4a77dd238a 100644 --- a/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs @@ -549,7 +549,7 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho .OrderBy(static x => x.Name)) { var defaultValueReference = propWithDefault.DefaultValue; - if (defaultValueReference.StartsWith("\"", StringComparison.OrdinalIgnoreCase)) + if (defaultValueReference.StartsWith('"')) { defaultValueReference = $"{propWithDefault.Name.ToFirstCharacterLowerCase()}Value"; var defaultValue = propWithDefault.DefaultValue; diff --git a/src/Kiota.Builder/Writers/Go/CodeProprietableBlockDeclarationWriter.cs b/src/Kiota.Builder/Writers/Go/CodeProprietableBlockDeclarationWriter.cs index 4bd8cc5e86..0dee8faa7e 100644 --- a/src/Kiota.Builder/Writers/Go/CodeProprietableBlockDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Go/CodeProprietableBlockDeclarationWriter.cs @@ -28,7 +28,7 @@ public override void WriteCodeElement(T codeElement, LanguageWriter writer) .Usings .Union(codeElement.Parent is CodeClass currentClass ? currentClass.InnerClasses.SelectMany(static x => x.Usings) : Enumerable.Empty()) .Where(static x => x.Declaration != null && x.Declaration.IsExternal) - .Select(static x => new Tuple(x.Name.StartsWith("*", StringComparison.OrdinalIgnoreCase) ? x.Name[1..] : x.Declaration!.Name.GetNamespaceImportSymbol(), x.Declaration!.Name)) + .Select(static x => new Tuple(x.Name.StartsWith('*') ? x.Name[1..] : x.Declaration!.Name.GetNamespaceImportSymbol(), x.Declaration!.Name)) .Distinct()) .OrderBy(static x => x.Item2.Count(static y => y == '/')) .ThenBy(static x => x) From 61e0eff0576f295062dbde760f45005408d97f44 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 09:56:22 -0500 Subject: [PATCH 04/10] - code linting: static constants to avoid allocs Signed-off-by: Vincent Biret --- src/Kiota.Builder/KiotaBuilder.cs | 3 ++- src/Kiota.Builder/Logging/FileLogLogger.cs | 5 +++-- src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs | 3 ++- src/Kiota.Builder/Refiners/PhpRefiner.cs | 6 ++++-- src/Kiota.Builder/Refiners/RubyRefiner.cs | 6 +++--- .../SearchProviders/OpenApiSpec/OpenApiSpecSeachProvider.cs | 3 ++- src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs | 2 +- 7 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/Kiota.Builder/KiotaBuilder.cs b/src/Kiota.Builder/KiotaBuilder.cs index a19d8ed4c7..6ec7d292ed 100644 --- a/src/Kiota.Builder/KiotaBuilder.cs +++ b/src/Kiota.Builder/KiotaBuilder.cs @@ -97,7 +97,7 @@ private static string NormalizeApiManifestPath(Request request, string? baseUrl) try { logger.LogDebug("Api manifest path: {ApiManifestPath}", config.ApiManifestPath); - var pathParts = config.ApiManifestPath.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries); + var pathParts = config.ApiManifestPath.Split(manifestPathSeparator, StringSplitOptions.RemoveEmptyEntries); var manifestPath = pathParts[0]; var apiIdentifier = pathParts.Length > 1 ? pathParts[1] : string.Empty; var manifestManagementService = new ManifestManagementService(); @@ -2212,6 +2212,7 @@ private Dictionary CollectAllProperties(OpenApiSchema sch internal const string BackedModelInterface = "IBackedModel"; private const string ParseNodeInterface = "IParseNode"; internal const string AdditionalHolderInterface = "IAdditionalDataHolder"; + private static readonly char[] manifestPathSeparator = ['#']; internal static void AddSerializationMembers(CodeClass model, bool includeAdditionalProperties, bool usesBackingStore, Func refineMethodName) { var serializationPropsType = $"IDictionary>"; diff --git a/src/Kiota.Builder/Logging/FileLogLogger.cs b/src/Kiota.Builder/Logging/FileLogLogger.cs index 6b4f788fb4..dba4b6cf43 100644 --- a/src/Kiota.Builder/Logging/FileLogLogger.cs +++ b/src/Kiota.Builder/Logging/FileLogLogger.cs @@ -11,11 +11,11 @@ public class FileLogLogger : ILogger, IDisposable private readonly LogLevel _logLevel; private readonly string _categoryName; internal const string LogFileName = ".kiota.log"; - private readonly Object writeLock = new(); + private readonly object writeLock = new(); public FileLogLogger(string logFileDirectoryAbsolutePath, LogLevel logLevel, string categoryName) { _logLevel = logLevel; - _categoryName = categoryName?.Split(new char[] { '.', ' ' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? string.Empty; + _categoryName = categoryName?.Split(categoryNameSeparators, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? string.Empty; if (_logLevel == LogLevel.None || string.IsNullOrEmpty(logFileDirectoryAbsolutePath)) _logStream = new StreamWriter(Stream.Null); else @@ -55,6 +55,7 @@ public bool IsEnabled(LogLevel logLevel) return logLevel != LogLevel.None && logLevel >= _logLevel; } private bool wroteAnything; + private static readonly char[] categoryNameSeparators = ['.', ' ']; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (formatter is null) return; diff --git a/src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs b/src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs index 550d511de0..d76339a2cf 100644 --- a/src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs +++ b/src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs @@ -8,7 +8,8 @@ public class PhpPathSegmenter : CommonPathSegmenter { public PhpPathSegmenter(string rootPath, string clientNamespaceName) : base(rootPath, clientNamespaceName) { } public override string FileSuffix => ".php"; + private static readonly char[] pathSeparators = ['.', '\\']; public override string NormalizeNamespaceSegment(string segmentName) => segmentName.ToFirstCharacterUpperCase(); - protected static new string GetLastFileNameSegment(CodeElement currentElement) => currentElement?.Name.Split(new char[] { '.', '\\' }, StringSplitOptions.RemoveEmptyEntries).Last() ?? string.Empty; + protected static new string GetLastFileNameSegment(CodeElement currentElement) => currentElement?.Name.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries).Last() ?? string.Empty; public override string NormalizeFileName(CodeElement currentElement) => GetLastFileNameSegment(currentElement).ToFirstCharacterUpperCase(); } diff --git a/src/Kiota.Builder/Refiners/PhpRefiner.cs b/src/Kiota.Builder/Refiners/PhpRefiner.cs index 9fb27f7430..13d25bd18b 100644 --- a/src/Kiota.Builder/Refiners/PhpRefiner.cs +++ b/src/Kiota.Builder/Refiners/PhpRefiner.cs @@ -98,7 +98,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance "Microsoft\\Kiota\\Serialization\\Text\\TextParseNodeFactory"} ); cancellationToken.ThrowIfCancellationRequested(); - AddSerializationModulesImport(generatedCode, new[] { "Microsoft\\Kiota\\Abstractions\\ApiClientBuilder" }, null, '\\'); + AddSerializationModulesImport(generatedCode, ["Microsoft\\Kiota\\Abstractions\\ApiClientBuilder"], null, '\\'); cancellationToken.ThrowIfCancellationRequested(); AddPropertiesAndMethodTypesImports(generatedCode, true, false, true); CorrectBackingStoreSetterParam(generatedCode); @@ -301,7 +301,7 @@ private static void AliasUsingWithSameSymbol(CodeElement currentElement) foreach (var usingElement in duplicatedSymbolsUsings) { var replacement = string.Join("\\", usingElement.Declaration!.TypeDefinition!.GetImmediateParentOfType().Name - .Split(new[] { '\\', '.' }, StringSplitOptions.RemoveEmptyEntries) + .Split(importPathSeparators, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.ToFirstCharacterUpperCase()) .ToArray()); usingElement.Alias = $"{(string.IsNullOrEmpty(replacement) ? string.Empty : $"\\{replacement}")}\\{usingElement.Declaration!.TypeDefinition!.Name.ToFirstCharacterUpperCase()}"; @@ -340,6 +340,8 @@ private void AddCollectionValidationUtilImportToModels(CodeElement codeElement) { CodePropertyKind.Options, CodeParameterKind.Options }, { CodePropertyKind.QueryParameters, CodeParameterKind.QueryParameter }, }; + private static readonly char[] importPathSeparators = ['\\', '.']; + private static void AddRequestConfigurationConstructors(CodeElement codeElement) { if (codeElement is CodeClass codeClass && codeClass.IsOfKind(CodeClassKind.RequestConfiguration, CodeClassKind.QueryParameters)) diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 7e0597e516..43cc0079b3 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -110,9 +110,9 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance new(StringComparer.OrdinalIgnoreCase) { "microsoft_kiota_serialization_json.JsonParseNodeFactory"}); AddSerializationModulesImport(generatedCode, - new[] { "microsoft_kiota_abstractions.ApiClientBuilder", - "microsoft_kiota_abstractions.SerializationWriterFactoryRegistry" }, - new[] { "microsoft_kiota_abstractions.ParseNodeFactoryRegistry" }); + ["microsoft_kiota_abstractions.ApiClientBuilder", + "microsoft_kiota_abstractions.SerializationWriterFactoryRegistry" ], + ["microsoft_kiota_abstractions.ParseNodeFactoryRegistry"]); AddQueryParameterMapperMethod( generatedCode ); diff --git a/src/Kiota.Builder/SearchProviders/OpenApiSpec/OpenApiSpecSeachProvider.cs b/src/Kiota.Builder/SearchProviders/OpenApiSpec/OpenApiSpecSeachProvider.cs index 30e6181f8e..74a6a4c2a4 100644 --- a/src/Kiota.Builder/SearchProviders/OpenApiSpec/OpenApiSpecSeachProvider.cs +++ b/src/Kiota.Builder/SearchProviders/OpenApiSpec/OpenApiSpecSeachProvider.cs @@ -14,7 +14,7 @@ public Task> SearchAsync(string term, string? { ArgumentException.ThrowIfNullOrEmpty(term); - if (term.Split(new char[] { ' ', '-' }, StringSplitOptions.RemoveEmptyEntries).Any(Keywords.Contains)) + if (term.Split(termSeparator, StringSplitOptions.RemoveEmptyEntries).Any(Keywords.Contains)) { return Task.FromResult>(new Dictionary { { "petstore", new SearchResult(ApiTitle, ApiDescription, new Uri("https://petstore.swagger.io/v1"), new Uri("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/petstore.yaml"), new List { "1.0.0" }) } @@ -36,4 +36,5 @@ public Task> SearchAsync(string term, string? "example", "swagger", }; + private static readonly char[] termSeparator = [' ', '-']; } diff --git a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs index e07578e0d7..d80ae29ec3 100644 --- a/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Ruby/CodeMethodWriter.cs @@ -159,7 +159,7 @@ private static void WriteSerializationRegistration(CodeClass parentClass, HashSe { var prefix = parentClass.Usings.FirstOrDefault(x => x.IsExternal && x.Name.Equals(serializationClassName, StringComparison.OrdinalIgnoreCase))?.Declaration?.Name; if (!string.IsNullOrEmpty(prefix)) - prefix = $"{prefix.ToCamelCase(new char[] { '_' }).ToFirstCharacterUpperCase()}::"; + prefix = $"{prefix.ToCamelCase(['_']).ToFirstCharacterUpperCase()}::"; writer.WriteLine($"MicrosoftKiotaAbstractions::ApiClientBuilder.{methodName}({prefix}{serializationClassName})"); } } From c28ba891cd0190d63fafbac55637add5385f5f89 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 10:04:49 -0500 Subject: [PATCH 05/10] - code linting: last reported net8 upgrade defects --- src/Kiota.Builder/CodeDOM/CodeBlock.cs | 5 ++--- .../CodeDOM/DiscriminatorInformation.cs | 6 +++--- src/Kiota.Builder/CodeRenderers/CodeRenderer.cs | 2 +- .../Extensions/OpenApiOperationExtensions.cs | 15 ++++++++------- src/Kiota.Builder/KiotaBuilder.cs | 8 ++++---- .../Refiners/CommonLanguageRefiner.cs | 2 +- .../Writers/Java/CodeMethodWriter.cs | 2 +- src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs | 2 +- 8 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Kiota.Builder/CodeDOM/CodeBlock.cs b/src/Kiota.Builder/CodeDOM/CodeBlock.cs index b1ac03a283..780d3973d5 100644 --- a/src/Kiota.Builder/CodeDOM/CodeBlock.cs +++ b/src/Kiota.Builder/CodeDOM/CodeBlock.cs @@ -137,11 +137,10 @@ public IEnumerable FindChildrenByName(string childName) where T : ICodeEle public IEnumerable FindChildrenByName(IEnumerable childrenName, bool findInChildElements = true) where T : ICodeElement { - if (childrenName == null) - throw new ArgumentNullException(nameof(childrenName)); + ArgumentNullException.ThrowIfNull(childrenName); return childrenName.Where(static x => !string.IsNullOrEmpty(x)) - .Select(x => this.FindChildByName(x, findInChildElements)); + .Select(x => FindChildByName(x, findInChildElements)); } public T? FindChildByName(string childName, bool findInChildElements = true) where T : ICodeElement diff --git a/src/Kiota.Builder/CodeDOM/DiscriminatorInformation.cs b/src/Kiota.Builder/CodeDOM/DiscriminatorInformation.cs index 69a6c7f8cd..fd62b79ed5 100644 --- a/src/Kiota.Builder/CodeDOM/DiscriminatorInformation.cs +++ b/src/Kiota.Builder/CodeDOM/DiscriminatorInformation.cs @@ -6,11 +6,11 @@ namespace Kiota.Builder.CodeDOM; public class DiscriminatorInformation : CodeElement, ICloneable { - private ConcurrentDictionary discriminatorMappings = new(StringComparer.OrdinalIgnoreCase); + private ConcurrentDictionary discriminatorMappings = new(StringComparer.OrdinalIgnoreCase); /// /// Gets the discriminator values for the class where the key is the value as represented in the payload. /// - public IOrderedEnumerable> DiscriminatorMappings + public IOrderedEnumerable> DiscriminatorMappings { get { @@ -29,7 +29,7 @@ public string DiscriminatorPropertyName get; set; } = string.Empty; - public void AddDiscriminatorMapping(string key, CodeTypeBase type) + public void AddDiscriminatorMapping(string key, CodeType type) { ArgumentNullException.ThrowIfNull(type); ArgumentException.ThrowIfNullOrEmpty(key); diff --git a/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs b/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs index c8a3bc3272..51cba2789c 100644 --- a/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs +++ b/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs @@ -34,7 +34,7 @@ public async Task RenderCodeNamespaceToSingleFileAsync(LanguageWriter writer, Co writer.SetTextWriter(sw); RenderCode(writer, codeElement); if (!cancellationToken.IsCancellationRequested) - await sw.FlushAsync().ConfigureAwait(false); // stream writer doesn't not have a cancellation token overload https://github.com/dotnet/runtime/issues/64340 + await sw.FlushAsync(cancellationToken).ConfigureAwait(false); // stream writer doesn't not have a cancellation token overload https://github.com/dotnet/runtime/issues/64340 } // We created barrels for code namespaces. Skipping for empty namespaces, ones created for users, and ones with same namespace as class name. public async Task RenderCodeNamespaceToFilePerClassAsync(LanguageWriter writer, CodeNamespace currentNamespace, CancellationToken cancellationToken) diff --git a/src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs b/src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs index 390986267b..767ac3696a 100644 --- a/src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs +++ b/src/Kiota.Builder/Extensions/OpenApiOperationExtensions.cs @@ -41,15 +41,16 @@ internal static bool IsMultipartFormDataSchema(this IDictionary GetValidSchemas(this IDictionary source, StructuredMimeTypesCollection structuredMimeTypes) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(structuredMimeTypes); if (structuredMimeTypes.Count == 0) throw new ArgumentNullException(nameof(structuredMimeTypes)); - return source? - .Where(static c => !string.IsNullOrEmpty(c.Key)) - .Select(static c => (Key: c.Key.Split(';', StringSplitOptions.RemoveEmptyEntries)[0], c.Value)) - .Where(c => structuredMimeTypes.Contains(c.Key) || structuredMimeTypes.Contains(vendorSpecificCleanup.Replace(c.Key, string.Empty))) - .Select(static co => co.Value.Schema) - .Where(static s => s is not null) ?? - Enumerable.Empty(); + return source + .Where(static c => !string.IsNullOrEmpty(c.Key)) + .Select(static c => (Key: c.Key.Split(';', StringSplitOptions.RemoveEmptyEntries)[0], c.Value)) + .Where(c => structuredMimeTypes.Contains(c.Key) || structuredMimeTypes.Contains(vendorSpecificCleanup.Replace(c.Key, string.Empty))) + .Select(static co => co.Value.Schema) + .Where(static s => s is not null); } internal static OpenApiSchema? GetResponseSchema(this OpenApiResponse response, StructuredMimeTypesCollection structuredMimeTypes) { diff --git a/src/Kiota.Builder/KiotaBuilder.cs b/src/Kiota.Builder/KiotaBuilder.cs index 6ec7d292ed..bc49a65d69 100644 --- a/src/Kiota.Builder/KiotaBuilder.cs +++ b/src/Kiota.Builder/KiotaBuilder.cs @@ -1649,7 +1649,7 @@ private CodeType CreateModelDeclarationAndType(OpenApiUrlTreeNode currentNode, O TypeDefinition = codeDeclaration, }; } - private CodeTypeBase CreateInheritedModelDeclaration(OpenApiUrlTreeNode currentNode, OpenApiSchema schema, OpenApiOperation? operation, string classNameSuffix, CodeNamespace codeNamespace, bool isRequestBody) + private CodeType CreateInheritedModelDeclaration(OpenApiUrlTreeNode currentNode, OpenApiSchema schema, OpenApiOperation? operation, string classNameSuffix, CodeNamespace codeNamespace, bool isRequestBody) { var allOfs = schema.AllOf.FlattenSchemaIfRequired(static x => x.AllOf); CodeElement? codeDeclaration = null; @@ -1974,7 +1974,7 @@ type.TypeDefinition is CodeClass definition && AddDiscriminatorMethod(newClass, schema.GetDiscriminatorPropertyName(), mappings, static s => s); return newClass; } - private IEnumerable> GetDiscriminatorMappings(OpenApiUrlTreeNode currentNode, OpenApiSchema schema, CodeNamespace currentNamespace, CodeClass? baseClass) + private IEnumerable> GetDiscriminatorMappings(OpenApiUrlTreeNode currentNode, OpenApiSchema schema, CodeNamespace currentNamespace, CodeClass? baseClass) { return schema.GetDiscriminatorMappings(inheritanceIndex) .Select(x => KeyValuePair.Create(x.Key, GetCodeTypeForMapping(currentNode, x.Value, currentNamespace, baseClass, schema))) @@ -2119,7 +2119,7 @@ private void InitializeInheritanceIndex() { openApiDocument?.InitializeInheritanceIndex(inheritanceIndex); } - internal static void AddDiscriminatorMethod(CodeClass newClass, string discriminatorPropertyName, IEnumerable> discriminatorMappings, Func refineMethodName) + internal static void AddDiscriminatorMethod(CodeClass newClass, string discriminatorPropertyName, IEnumerable> discriminatorMappings, Func refineMethodName) { var factoryMethod = new CodeMethod { @@ -2150,7 +2150,7 @@ internal static void AddDiscriminatorMethod(CodeClass newClass, string discrimin newClass.DiscriminatorInformation.DiscriminatorPropertyName = discriminatorPropertyName; newClass.AddMethod(factoryMethod); } - private CodeTypeBase? GetCodeTypeForMapping(OpenApiUrlTreeNode currentNode, string referenceId, CodeNamespace currentNamespace, CodeClass? baseClass, OpenApiSchema currentSchema) + private CodeType? GetCodeTypeForMapping(OpenApiUrlTreeNode currentNode, string referenceId, CodeNamespace currentNamespace, CodeClass? baseClass, OpenApiSchema currentSchema) { var componentKey = referenceId?.Replace("#/components/schemas/", string.Empty, StringComparison.OrdinalIgnoreCase); if (openApiDocument == null || !openApiDocument.Components.Schemas.TryGetValue(componentKey, out var discriminatorSchema)) diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index e60d139a0d..0265081819 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -469,7 +469,7 @@ protected static void ConvertUnionTypesToWrapper(CodeElement currentElement, boo } CrawlTree(currentElement, x => ConvertUnionTypesToWrapper(x, usesBackingStore, refineMethodName, supportInnerClasses, markerInterfaceNamespace, markerInterfaceName, markerMethodName)); } - private static CodeTypeBase ConvertComposedTypeToWrapper(CodeClass codeClass, CodeComposedTypeBase codeComposedType, bool usesBackingStore, Func refineMethodName, bool supportsInnerClasses, string markerInterfaceNamespace, string markerInterfaceName, string markerMethodName) + private static CodeType ConvertComposedTypeToWrapper(CodeClass codeClass, CodeComposedTypeBase codeComposedType, bool usesBackingStore, Func refineMethodName, bool supportsInnerClasses, string markerInterfaceNamespace, string markerInterfaceName, string markerMethodName) { ArgumentNullException.ThrowIfNull(codeClass); ArgumentNullException.ThrowIfNull(codeComposedType); diff --git a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs index 67dac96b21..a4350bb94a 100644 --- a/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs @@ -171,7 +171,7 @@ private static void WriteSplitFactoryMethodBodyForInheritedModel(CodeClass paren writer.CloseBlock(); } } - private static void WriteFactoryMethodBodyForInheritedModel(IOrderedEnumerable> discriminatorMappings, LanguageWriter writer, string varName = "") + private static void WriteFactoryMethodBodyForInheritedModel(IOrderedEnumerable> discriminatorMappings, LanguageWriter writer, string varName = "") { if (string.IsNullOrEmpty(varName)) varName = DiscriminatorMappingVarName; diff --git a/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs index 77784f1f0f..8172fcbcbe 100644 --- a/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs @@ -969,7 +969,7 @@ private void WriteFactoryMethodBodyForUnionModelForUnDiscriminatedTypes(CodeMeth writer.CloseBlock(decreaseIndent: false); } - private void WriteFactoryMethodBodyForInheritedModel(IOrderedEnumerable> discriminatorMappings, LanguageWriter writer, CodeMethod method, string? varName = default) + private void WriteFactoryMethodBodyForInheritedModel(IOrderedEnumerable> discriminatorMappings, LanguageWriter writer, CodeMethod method, string? varName = default) { if (string.IsNullOrEmpty(varName)) varName = DiscriminatorMappingVarName; From e991827390fd2d60fd91a4421fd21a1e23c77272 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 10:07:13 -0500 Subject: [PATCH 06/10] - updates contributing guidelines Signed-off-by: Vincent Biret --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0ed21786ce..12ca78d998 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ Thanks for your interest in contributing to Kiota! We welcome contributions from To get started, you'll need to have the following tools installed: -- [.NET SDK 7.0](https://get.dot.net/7) +- [.NET SDK 8.0](https://get.dot.net/8) ## Recommended tools From 9964ab511cd66464e147ce435c7c6ed8a7bdb951 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 10:14:07 -0500 Subject: [PATCH 07/10] - fixes formatting --- src/Kiota.Builder/Refiners/RubyRefiner.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Kiota.Builder/Refiners/RubyRefiner.cs b/src/Kiota.Builder/Refiners/RubyRefiner.cs index 43cc0079b3..e180f072da 100644 --- a/src/Kiota.Builder/Refiners/RubyRefiner.cs +++ b/src/Kiota.Builder/Refiners/RubyRefiner.cs @@ -111,7 +111,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance "microsoft_kiota_serialization_json.JsonParseNodeFactory"}); AddSerializationModulesImport(generatedCode, ["microsoft_kiota_abstractions.ApiClientBuilder", - "microsoft_kiota_abstractions.SerializationWriterFactoryRegistry" ], + "microsoft_kiota_abstractions.SerializationWriterFactoryRegistry"], ["microsoft_kiota_abstractions.ParseNodeFactoryRegistry"]); AddQueryParameterMapperMethod( generatedCode From 823a7a76390ea9517d49efd58e9150a62da7a0ff Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 10:22:13 -0500 Subject: [PATCH 08/10] - code linting Signed-off-by: Vincent Biret --- src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs | 3 +-- src/kiota/Handlers/KiotaGenerationCommandHandler.cs | 4 ++-- src/kiota/KiotaConfigurationExtensions.cs | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs b/src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs index d76339a2cf..c7422f370f 100644 --- a/src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs +++ b/src/Kiota.Builder/PathSegmenters/PHPPathSegmenter.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using Kiota.Builder.CodeDOM; using Kiota.Builder.Extensions; @@ -10,6 +9,6 @@ public PhpPathSegmenter(string rootPath, string clientNamespaceName) : base(root public override string FileSuffix => ".php"; private static readonly char[] pathSeparators = ['.', '\\']; public override string NormalizeNamespaceSegment(string segmentName) => segmentName.ToFirstCharacterUpperCase(); - protected static new string GetLastFileNameSegment(CodeElement currentElement) => currentElement?.Name.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries).Last() ?? string.Empty; + protected static new string GetLastFileNameSegment(CodeElement currentElement) => currentElement?.Name.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries)[^1] ?? string.Empty; public override string NormalizeFileName(CodeElement currentElement) => GetLastFileNameSegment(currentElement).ToFirstCharacterUpperCase(); } diff --git a/src/kiota/Handlers/KiotaGenerationCommandHandler.cs b/src/kiota/Handlers/KiotaGenerationCommandHandler.cs index 9981e0e3f8..6228ea01da 100644 --- a/src/kiota/Handlers/KiotaGenerationCommandHandler.cs +++ b/src/kiota/Handlers/KiotaGenerationCommandHandler.cs @@ -104,10 +104,10 @@ public override async Task InvokeAsync(InvocationContext context) if (disabledValidationRules.Count != 0) Configuration.Generation.DisabledValidationRules = disabledValidationRules .Select(static x => x.TrimQuotes()) - .SelectMany(static x => x.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + .SelectMany(static x => x.Split(',', StringSplitOptions.RemoveEmptyEntries)) .ToHashSet(StringComparer.OrdinalIgnoreCase); if (structuredMimeTypes.Count != 0) - Configuration.Generation.StructuredMimeTypes = new(structuredMimeTypes.SelectMany(static x => x.Split(new[] { ' ' })) + Configuration.Generation.StructuredMimeTypes = new(structuredMimeTypes.SelectMany(static x => x.Split([' '])) .Select(static x => x.TrimQuotes())); Configuration.Generation.OpenAPIFilePath = GetAbsolutePath(Configuration.Generation.OpenAPIFilePath); diff --git a/src/kiota/KiotaConfigurationExtensions.cs b/src/kiota/KiotaConfigurationExtensions.cs index 70a45841b9..e2a0a3edb5 100644 --- a/src/kiota/KiotaConfigurationExtensions.cs +++ b/src/kiota/KiotaConfigurationExtensions.cs @@ -69,7 +69,7 @@ public static void BindConfiguration(this KiotaConfiguration configObject, IConf configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.ExcludePatterns)}").LoadHashSet(configObject.Generation.ExcludePatterns); configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.DisabledValidationRules)}").LoadHashSet(configObject.Generation.DisabledValidationRules); } - private static void LoadCollection(this IConfigurationSection section, ICollection collection) + private static void LoadCollection(this IConfigurationSection section, StructuredMimeTypesCollection collection) { ArgumentNullException.ThrowIfNull(collection); if (section is null) return; From e7efae7de7d2cbc6fe96a20e8f1f61533e113d2b Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Wed, 15 Nov 2023 10:28:37 -0500 Subject: [PATCH 09/10] - additional linting Signed-off-by: Vincent Biret --- src/kiota/Handlers/KiotaGenerationCommandHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/kiota/Handlers/KiotaGenerationCommandHandler.cs b/src/kiota/Handlers/KiotaGenerationCommandHandler.cs index 6228ea01da..f4df49016e 100644 --- a/src/kiota/Handlers/KiotaGenerationCommandHandler.cs +++ b/src/kiota/Handlers/KiotaGenerationCommandHandler.cs @@ -107,7 +107,7 @@ public override async Task InvokeAsync(InvocationContext context) .SelectMany(static x => x.Split(',', StringSplitOptions.RemoveEmptyEntries)) .ToHashSet(StringComparer.OrdinalIgnoreCase); if (structuredMimeTypes.Count != 0) - Configuration.Generation.StructuredMimeTypes = new(structuredMimeTypes.SelectMany(static x => x.Split([' '])) + Configuration.Generation.StructuredMimeTypes = new(structuredMimeTypes.SelectMany(static x => x.Split(' ', StringSplitOptions.RemoveEmptyEntries)) .Select(static x => x.TrimQuotes())); Configuration.Generation.OpenAPIFilePath = GetAbsolutePath(Configuration.Generation.OpenAPIFilePath); From 8ce3b7308363a7c8003ae8d81df5b7079286c50b Mon Sep 17 00:00:00 2001 From: Eastman Date: Thu, 16 Nov 2023 10:22:14 +0300 Subject: [PATCH 10/10] Update src/Kiota.Builder/CodeRenderers/CodeRenderer.cs --- src/Kiota.Builder/CodeRenderers/CodeRenderer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs b/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs index 51cba2789c..d0c4e12499 100644 --- a/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs +++ b/src/Kiota.Builder/CodeRenderers/CodeRenderer.cs @@ -34,7 +34,7 @@ public async Task RenderCodeNamespaceToSingleFileAsync(LanguageWriter writer, Co writer.SetTextWriter(sw); RenderCode(writer, codeElement); if (!cancellationToken.IsCancellationRequested) - await sw.FlushAsync(cancellationToken).ConfigureAwait(false); // stream writer doesn't not have a cancellation token overload https://github.com/dotnet/runtime/issues/64340 + await sw.FlushAsync(cancellationToken).ConfigureAwait(false); } // We created barrels for code namespaces. Skipping for empty namespaces, ones created for users, and ones with same namespace as class name. public async Task RenderCodeNamespaceToFilePerClassAsync(LanguageWriter writer, CodeNamespace currentNamespace, CancellationToken cancellationToken)