From 3702fd6e904869ad6ec239c956d3d26567851da5 Mon Sep 17 00:00:00 2001 From: Manuel Menegazzo <65919883+m3nax@users.noreply.github.com> Date: Wed, 28 Sep 2022 22:34:32 +0200 Subject: [PATCH] Standardization of using order and object initialization (#1028) * Code cleanup KubernetesClient * KubernetesClient.Basic code cleanup * KubernetesClient.Models cleanup * LibKubernetesGenerator code cleanup * Improved readability of object initialization * FIx namespace order * Fixed some compilation warning --- examples/namespace/NamespaceExample.cs | 4 +- examples/yaml/Program.cs | 10 ++-- .../AbstractKubernetes.cs | 2 +- .../Autorest/HttpRequestMessageWrapper.cs | 2 - .../Autorest/TokenCredentials.cs | 2 +- src/KubernetesClient.Basic/Global.cs | 6 +-- src/KubernetesClient.Models/Extensions.cs | 2 +- src/KubernetesClient.Models/IItems.cs | 5 ++ .../ExecCredentialResponse.cs | 4 +- src/KubernetesClient.Models/KubernetesYaml.cs | 2 +- .../ResourceQuantity.cs | 2 +- .../Versioning/VersionConverter.cs | 2 +- .../Authentication/ExecTokenProvider.cs | 4 +- .../Authentication/GcpTokenProvider.cs | 4 +- .../Authentication/OidcTokenProvider.cs | 4 +- .../Authentication/TokenFileAuth.cs | 4 +- src/KubernetesClient/CertUtils.cs | 24 +++++----- src/KubernetesClient/Kubernetes.ConfigInit.cs | 4 +- src/KubernetesClient/Kubernetes.Exec.cs | 38 +++++++-------- src/KubernetesClient/Kubernetes.WebSocket.cs | 32 ++++++++----- src/KubernetesClient/Kubernetes.cs | 11 +++-- ...ubernetesClientConfiguration.ConfigFile.cs | 19 +++++--- ...KubernetesClientConfiguration.InCluster.cs | 2 +- .../KubernetesClientConfiguration.cs | 2 +- .../KubernetesRequestDigest.cs | 6 +-- .../LeaderElection/LeaderElectionRecord.cs | 2 +- .../LeaderElection/LeaderElector.cs | 2 +- .../ResourceLock/MetaObjectLock.cs | 12 ++--- .../LeaderElection/ResourceLock/MultiLock.cs | 4 +- src/KubernetesClient/MuxedStream.cs | 6 +-- src/KubernetesClient/Watcher.cs | 2 +- src/KubernetesClient/WatcherExt.cs | 4 +- src/LibKubernetesGenerator/ApiGenerator.cs | 4 +- src/LibKubernetesGenerator/ClassNameHelper.cs | 4 +- .../GeneralNameHelper.cs | 8 ++-- .../KubernetesClientSourceGenerator.cs | 14 +++--- src/LibKubernetesGenerator/MetaHelper.cs | 4 +- .../ModelExtGenerator.cs | 4 +- src/LibKubernetesGenerator/ParamHelper.cs | 4 +- src/LibKubernetesGenerator/PluralHelper.cs | 8 ++-- src/LibKubernetesGenerator/StringHelpers.cs | 4 +- src/LibKubernetesGenerator/TypeHelper.cs | 6 +-- src/LibKubernetesGenerator/UtilHelper.cs | 4 +- .../KubernetesClient.Tests/ItemsEnumTests.cs | 2 +- .../KubernetesExecTests.cs | 16 +++++-- .../KubernetesYamlTests.cs | 47 ++++++++++--------- .../ModelExtensionTests.cs | 8 +++- 47 files changed, 201 insertions(+), 165 deletions(-) diff --git a/examples/namespace/NamespaceExample.cs b/examples/namespace/NamespaceExample.cs index 351453a..22ad06c 100644 --- a/examples/namespace/NamespaceExample.cs +++ b/examples/namespace/NamespaceExample.cs @@ -35,9 +35,9 @@ namespace @namespace { foreach (var innerEx in ex.InnerExceptions) { - if (innerEx is k8s.Autorest.HttpOperationException) + if (innerEx is k8s.Autorest.HttpOperationException exception) { - var code = ((k8s.Autorest.HttpOperationException)innerEx).Response.StatusCode; + var code = exception.Response.StatusCode; if (code == HttpStatusCode.NotFound) { return; diff --git a/examples/yaml/Program.cs b/examples/yaml/Program.cs index a724f30..04676b1 100644 --- a/examples/yaml/Program.cs +++ b/examples/yaml/Program.cs @@ -10,10 +10,12 @@ namespace yaml { private static async Task Main(string[] args) { - var typeMap = new Dictionary(); - typeMap.Add("v1/Pod", typeof(V1Pod)); - typeMap.Add("v1/Service", typeof(V1Service)); - typeMap.Add("apps/v1/Deployment", typeof(V1Deployment)); + var typeMap = new Dictionary + { + { "v1/Pod", typeof(V1Pod) }, + { "v1/Service", typeof(V1Service) }, + { "apps/v1/Deployment", typeof(V1Deployment) } + }; var objects = await KubernetesYaml.LoadAllFromFileAsync(args[0], typeMap); diff --git a/src/KubernetesClient.Basic/AbstractKubernetes.cs b/src/KubernetesClient.Basic/AbstractKubernetes.cs index dd77461..c4b30d8 100644 --- a/src/KubernetesClient.Basic/AbstractKubernetes.cs +++ b/src/KubernetesClient.Basic/AbstractKubernetes.cs @@ -19,7 +19,7 @@ public abstract partial class AbstractKubernetes private sealed class QueryBuilder { - private List parameters = new List(); + private readonly List parameters = new List(); public void Append(string key, params object[] values) { diff --git a/src/KubernetesClient.Basic/Autorest/HttpRequestMessageWrapper.cs b/src/KubernetesClient.Basic/Autorest/HttpRequestMessageWrapper.cs index efdefa0..5505429 100644 --- a/src/KubernetesClient.Basic/Autorest/HttpRequestMessageWrapper.cs +++ b/src/KubernetesClient.Basic/Autorest/HttpRequestMessageWrapper.cs @@ -30,12 +30,10 @@ namespace k8s.Autorest this.Content = content; this.Method = httpRequest.Method; this.RequestUri = httpRequest.RequestUri; -#pragma warning disable CS0618 // Type or member is obsolete if (httpRequest.Properties != null) { Properties = new Dictionary(); foreach (KeyValuePair pair in httpRequest.Properties) -#pragma warning restore CS0618 // Type or member is obsolete { this.Properties[pair.Key] = pair.Value; } diff --git a/src/KubernetesClient.Basic/Autorest/TokenCredentials.cs b/src/KubernetesClient.Basic/Autorest/TokenCredentials.cs index f48c543..da44886 100644 --- a/src/KubernetesClient.Basic/Autorest/TokenCredentials.cs +++ b/src/KubernetesClient.Basic/Autorest/TokenCredentials.cs @@ -98,7 +98,7 @@ namespace k8s.Autorest /// /// Task that will complete when processing has completed. /// - public async override Task ProcessHttpRequestAsync( + public override async Task ProcessHttpRequestAsync( HttpRequestMessage request, CancellationToken cancellationToken) { diff --git a/src/KubernetesClient.Basic/Global.cs b/src/KubernetesClient.Basic/Global.cs index d91efcf..69a1f6a 100644 --- a/src/KubernetesClient.Basic/Global.cs +++ b/src/KubernetesClient.Basic/Global.cs @@ -1,8 +1,8 @@ -global using System; -global using System.Collections.Generic; -global using System.Linq; global using k8s.Autorest; global using k8s.Models; +global using System; +global using System.Collections.Generic; global using System.IO; +global using System.Linq; global using System.Threading; global using System.Threading.Tasks; diff --git a/src/KubernetesClient.Models/Extensions.cs b/src/KubernetesClient.Models/Extensions.cs index accab5c..f7cde08 100644 --- a/src/KubernetesClient.Models/Extensions.cs +++ b/src/KubernetesClient.Models/Extensions.cs @@ -1,6 +1,6 @@ +using k8s.Models; using System.Reflection; using System.Text.RegularExpressions; -using k8s.Models; namespace k8s { diff --git a/src/KubernetesClient.Models/IItems.cs b/src/KubernetesClient.Models/IItems.cs index 58f4a62..4f23d93 100644 --- a/src/KubernetesClient.Models/IItems.cs +++ b/src/KubernetesClient.Models/IItems.cs @@ -17,6 +17,11 @@ namespace k8s { public static IEnumerator GetEnumerator(this IItems items) { + if (items is null) + { + throw new ArgumentNullException(nameof(items)); + } + return items.Items.GetEnumerator(); } } diff --git a/src/KubernetesClient.Models/KubeConfigModels/ExecCredentialResponse.cs b/src/KubernetesClient.Models/KubeConfigModels/ExecCredentialResponse.cs index 57c916e..6654ba3 100644 --- a/src/KubernetesClient.Models/KubeConfigModels/ExecCredentialResponse.cs +++ b/src/KubernetesClient.Models/KubeConfigModels/ExecCredentialResponse.cs @@ -13,8 +13,8 @@ namespace k8s.KubeConfigModels public bool IsValid() { - return (!string.IsNullOrEmpty(Token) || - (!string.IsNullOrEmpty(ClientCertificateData) && !string.IsNullOrEmpty(ClientKeyData))); + return !string.IsNullOrEmpty(Token) || + (!string.IsNullOrEmpty(ClientCertificateData) && !string.IsNullOrEmpty(ClientKeyData)); } } diff --git a/src/KubernetesClient.Models/KubernetesYaml.cs b/src/KubernetesClient.Models/KubernetesYaml.cs index 1de5ad7..dd79e9d 100644 --- a/src/KubernetesClient.Models/KubernetesYaml.cs +++ b/src/KubernetesClient.Models/KubernetesYaml.cs @@ -1,3 +1,4 @@ +using k8s.Models; using System.IO; using System.Reflection; using System.Text; @@ -6,7 +7,6 @@ using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; -using k8s.Models; namespace k8s { diff --git a/src/KubernetesClient.Models/ResourceQuantity.cs b/src/KubernetesClient.Models/ResourceQuantity.cs index 41af529..757acef 100644 --- a/src/KubernetesClient.Models/ResourceQuantity.cs +++ b/src/KubernetesClient.Models/ResourceQuantity.cs @@ -1,6 +1,6 @@ +using Fractions; using System.Globalization; using System.Numerics; -using Fractions; namespace k8s.Models { diff --git a/src/KubernetesClient.Models/Versioning/VersionConverter.cs b/src/KubernetesClient.Models/Versioning/VersionConverter.cs index 914b111..8c2c5ce 100644 --- a/src/KubernetesClient.Models/Versioning/VersionConverter.cs +++ b/src/KubernetesClient.Models/Versioning/VersionConverter.cs @@ -1,8 +1,8 @@ // WARNING: DO NOT LEAVE COMMENTED CODE IN THIS FILE. IT GETS SCANNED BY GEN PROJECT SO IT CAN EXCLUDE ANY MANUALLY DEFINED MAPS -using System.Reflection; using AutoMapper; using k8s.Models; +using System.Reflection; namespace k8s.Versioning { diff --git a/src/KubernetesClient/Authentication/ExecTokenProvider.cs b/src/KubernetesClient/Authentication/ExecTokenProvider.cs index d445b91..b0b8650 100644 --- a/src/KubernetesClient/Authentication/ExecTokenProvider.cs +++ b/src/KubernetesClient/Authentication/ExecTokenProvider.cs @@ -1,8 +1,8 @@ +using k8s.Autorest; +using k8s.KubeConfigModels; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; -using k8s.KubeConfigModels; -using k8s.Autorest; namespace k8s.Authentication { diff --git a/src/KubernetesClient/Authentication/GcpTokenProvider.cs b/src/KubernetesClient/Authentication/GcpTokenProvider.cs index de6671d..d21bd1d 100644 --- a/src/KubernetesClient/Authentication/GcpTokenProvider.cs +++ b/src/KubernetesClient/Authentication/GcpTokenProvider.cs @@ -1,9 +1,9 @@ +using k8s.Autorest; +using k8s.Exceptions; using System.Diagnostics; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; -using k8s.Exceptions; -using k8s.Autorest; namespace k8s.Authentication { diff --git a/src/KubernetesClient/Authentication/OidcTokenProvider.cs b/src/KubernetesClient/Authentication/OidcTokenProvider.cs index 51a6a22..2d2d0e8 100644 --- a/src/KubernetesClient/Authentication/OidcTokenProvider.cs +++ b/src/KubernetesClient/Authentication/OidcTokenProvider.cs @@ -1,6 +1,6 @@ using IdentityModel.OidcClient; -using k8s.Exceptions; using k8s.Autorest; +using k8s.Exceptions; using System.IdentityModel.Tokens.Jwt; using System.Net.Http.Headers; using System.Threading; @@ -10,7 +10,7 @@ namespace k8s.Authentication { public class OidcTokenProvider : ITokenProvider { - private OidcClient _oidcClient; + private readonly OidcClient _oidcClient; private string _idToken; private string _refreshToken; private DateTimeOffset _expiry; diff --git a/src/KubernetesClient/Authentication/TokenFileAuth.cs b/src/KubernetesClient/Authentication/TokenFileAuth.cs index 84f7ae2..7d34242 100644 --- a/src/KubernetesClient/Authentication/TokenFileAuth.cs +++ b/src/KubernetesClient/Authentication/TokenFileAuth.cs @@ -1,8 +1,8 @@ -using System.Net.Http.Headers; +using k8s.Autorest; using System.IO; +using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; -using k8s.Autorest; namespace k8s.Authentication { diff --git a/src/KubernetesClient/CertUtils.cs b/src/KubernetesClient/CertUtils.cs index aa4bb1b..ad4fad9 100644 --- a/src/KubernetesClient/CertUtils.cs +++ b/src/KubernetesClient/CertUtils.cs @@ -156,8 +156,7 @@ namespace k8s using (var reader = new StreamReader(new MemoryStream(keyData))) { obj = new PemReader(reader).ReadObject(); - var key = obj as AsymmetricCipherKeyPair; - if (key != null) + if (obj is AsymmetricCipherKeyPair key) { var cipherKey = key; obj = cipherKey.Private; @@ -169,18 +168,17 @@ namespace k8s var store = new Pkcs12StoreBuilder().Build(); store.SetKeyEntry("K8SKEY", new AsymmetricKeyEntry(keyParams), new[] { new X509CertificateEntry(cert) }); - using (var pkcs = new MemoryStream()) - { - store.Save(pkcs, new char[0], new SecureRandom()); + using var pkcs = new MemoryStream(); - if (config.ClientCertificateKeyStoreFlags.HasValue) - { - return new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value); - } - else - { - return new X509Certificate2(pkcs.ToArray()); - } + store.Save(pkcs, new char[0], new SecureRandom()); + + if (config.ClientCertificateKeyStoreFlags.HasValue) + { + return new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value); + } + else + { + return new X509Certificate2(pkcs.ToArray()); } #endif } diff --git a/src/KubernetesClient/Kubernetes.ConfigInit.cs b/src/KubernetesClient/Kubernetes.ConfigInit.cs index ee155e2..e98678b 100644 --- a/src/KubernetesClient/Kubernetes.ConfigInit.cs +++ b/src/KubernetesClient/Kubernetes.ConfigInit.cs @@ -1,9 +1,9 @@ +using k8s.Autorest; +using k8s.Exceptions; using System.Net.Http; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; -using k8s.Exceptions; -using k8s.Autorest; namespace k8s { diff --git a/src/KubernetesClient/Kubernetes.Exec.cs b/src/KubernetesClient/Kubernetes.Exec.cs index 240d8cc..cacc737 100644 --- a/src/KubernetesClient/Kubernetes.Exec.cs +++ b/src/KubernetesClient/Kubernetes.Exec.cs @@ -1,5 +1,5 @@ -using k8s.Models; using k8s.Autorest; +using k8s.Models; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -19,31 +19,31 @@ namespace k8s try { - using (var muxedStream = await MuxedStreamNamespacedPodExecAsync( + using var muxedStream = await MuxedStreamNamespacedPodExecAsync( name, @namespace, command, container, tty: tty, - cancellationToken: cancellationToken).ConfigureAwait(false)) - using (var stdIn = muxedStream.GetStream(null, ChannelIndex.StdIn)) - using (var stdOut = muxedStream.GetStream(ChannelIndex.StdOut, null)) - using (var stdErr = muxedStream.GetStream(ChannelIndex.StdErr, null)) - using (var error = muxedStream.GetStream(ChannelIndex.Error, null)) - using (var errorReader = new StreamReader(error)) - { - muxedStream.Start(); + cancellationToken: cancellationToken).ConfigureAwait(false); - await action(stdIn, stdOut, stdErr).ConfigureAwait(false); + using var stdIn = muxedStream.GetStream(null, ChannelIndex.StdIn); + using var stdOut = muxedStream.GetStream(ChannelIndex.StdOut, null); + using var stdErr = muxedStream.GetStream(ChannelIndex.StdErr, null); + using var error = muxedStream.GetStream(ChannelIndex.Error, null); + using var errorReader = new StreamReader(error); - var errors = await errorReader.ReadToEndAsync().ConfigureAwait(false); + muxedStream.Start(); - // StatusError is defined here: - // https://github.com/kubernetes/kubernetes/blob/068e1642f63a1a8c48c16c18510e8854a4f4e7c5/staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go#L37 - var returnMessage = KubernetesJson.Deserialize(errors); - return GetExitCodeOrThrow(returnMessage); - } + await action(stdIn, stdOut, stdErr).ConfigureAwait(false); + + var errors = await errorReader.ReadToEndAsync().ConfigureAwait(false); + + // StatusError is defined here: + // https://github.com/kubernetes/kubernetes/blob/068e1642f63a1a8c48c16c18510e8854a4f4e7c5/staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go#L37 + var returnMessage = KubernetesJson.Deserialize(errors); + return GetExitCodeOrThrow(returnMessage); } - catch (HttpOperationException httpEx) when (httpEx.Body is V1Status) + catch (HttpOperationException httpEx) when (httpEx.Body is V1Status status) { - throw new KubernetesException((V1Status)httpEx.Body, httpEx); + throw new KubernetesException(status, httpEx); } } diff --git a/src/KubernetesClient/Kubernetes.WebSocket.cs b/src/KubernetesClient/Kubernetes.WebSocket.cs index abcae21..de3721d 100644 --- a/src/KubernetesClient/Kubernetes.WebSocket.cs +++ b/src/KubernetesClient/Kubernetes.WebSocket.cs @@ -1,13 +1,13 @@ -using k8s.Models; using k8s.Autorest; +using k8s.Models; +using System.Globalization; using System.Net; using System.Net.Http; using System.Net.WebSockets; using System.Security.Cryptography.X509Certificates; +using System.Text; using System.Threading; using System.Threading.Tasks; -using System.Text; -using System.Globalization; namespace k8s { @@ -84,8 +84,10 @@ namespace k8s } // Construct URL - var uriBuilder = new UriBuilder(BaseUri); - uriBuilder.Scheme = BaseUri.Scheme == "https" ? "wss" : "ws"; + var uriBuilder = new UriBuilder(BaseUri) + { + Scheme = BaseUri.Scheme == "https" ? "wss" : "ws", + }; if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture)) { @@ -143,8 +145,10 @@ namespace k8s // Construct URL - var uriBuilder = new UriBuilder(BaseUri); - uriBuilder.Scheme = BaseUri.Scheme == "https" ? "wss" : "ws"; + var uriBuilder = new UriBuilder(BaseUri) + { + Scheme = BaseUri.Scheme == "https" ? "wss" : "ws", + }; if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture)) { @@ -187,8 +191,10 @@ namespace k8s } // Construct URL - var uriBuilder = new UriBuilder(BaseUri); - uriBuilder.Scheme = BaseUri.Scheme == "https" ? "wss" : "ws"; + var uriBuilder = new UriBuilder(BaseUri) + { + Scheme = BaseUri.Scheme == "https" ? "wss" : "ws", + }; if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture)) { @@ -294,8 +300,10 @@ namespace k8s { // This usually indicates the server sent an error message, like 400 Bad Request. Unfortunately, the WebSocket client // class doesn't give us a lot of information about what went wrong. So, retry the connection. - var uriBuilder = new UriBuilder(uri); - uriBuilder.Scheme = uri.Scheme == "wss" ? "https" : "http"; + var uriBuilder = new UriBuilder(uri) + { + Scheme = uri.Scheme == "wss" ? "https" : "http", + }; var response = await HttpClient.GetAsync(uriBuilder.Uri, cancellationToken).ConfigureAwait(false); @@ -327,7 +335,7 @@ namespace k8s $"The operation returned an invalid status code: {response.StatusCode}", wse) { Response = new HttpResponseMessageWrapper(response, content), - Body = status != null ? (object)status : content, + Body = status != null ? status : content, }; response.Dispose(); diff --git a/src/KubernetesClient/Kubernetes.cs b/src/KubernetesClient/Kubernetes.cs index 9239bbf..353dcf3 100644 --- a/src/KubernetesClient/Kubernetes.cs +++ b/src/KubernetesClient/Kubernetes.cs @@ -1,9 +1,9 @@ +using k8s.Autorest; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; -using k8s.Autorest; namespace k8s { @@ -101,9 +101,12 @@ namespace k8s protected override HttpRequestMessage CreateRequest(string relativeUri, HttpMethod method, IReadOnlyDictionary> customHeaders) { - var httpRequest = new HttpRequestMessage(); - httpRequest.Method = method; - httpRequest.RequestUri = new Uri(BaseUri, relativeUri); + var httpRequest = new HttpRequestMessage + { + Method = method, + RequestUri = new Uri(BaseUri, relativeUri), + }; + #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER httpRequest.Version = HttpVersion.Version20; #endif diff --git a/src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs b/src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs index cf0172d..5cc42a9 100644 --- a/src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs +++ b/src/KubernetesClient/KubernetesClientConfiguration.ConfigFile.cs @@ -61,8 +61,11 @@ namespace k8s return InClusterConfig(); } - var config = new KubernetesClientConfiguration(); - config.Host = "http://localhost:8080"; + var config = new KubernetesClientConfiguration + { + Host = "http://localhost:8080", + }; + return config; } @@ -274,14 +277,18 @@ namespace k8s { if (IPAddress.Equals(IPAddress.Any, ipAddress)) { - var builder = new UriBuilder(Host); - builder.Host = $"{IPAddress.Loopback}"; + var builder = new UriBuilder(Host) + { + Host = $"{IPAddress.Loopback}", + }; Host = builder.ToString(); } else if (IPAddress.Equals(IPAddress.IPv6Any, ipAddress)) { - var builder = new UriBuilder(Host); - builder.Host = $"{IPAddress.IPv6Loopback}"; + var builder = new UriBuilder(Host) + { + Host = $"{IPAddress.IPv6Loopback}", + }; Host = builder.ToString(); } } diff --git a/src/KubernetesClient/KubernetesClientConfiguration.InCluster.cs b/src/KubernetesClient/KubernetesClientConfiguration.InCluster.cs index d799cf1..5107442 100644 --- a/src/KubernetesClient/KubernetesClientConfiguration.InCluster.cs +++ b/src/KubernetesClient/KubernetesClientConfiguration.InCluster.cs @@ -1,6 +1,6 @@ -using System.IO; using k8s.Authentication; using k8s.Exceptions; +using System.IO; namespace k8s { diff --git a/src/KubernetesClient/KubernetesClientConfiguration.cs b/src/KubernetesClient/KubernetesClientConfiguration.cs index c0d1715..35efd60 100644 --- a/src/KubernetesClient/KubernetesClientConfiguration.cs +++ b/src/KubernetesClient/KubernetesClientConfiguration.cs @@ -1,6 +1,6 @@ +using k8s.Autorest; using System.Net.Http; using System.Security.Cryptography.X509Certificates; -using k8s.Autorest; namespace k8s { diff --git a/src/KubernetesClient/KubernetesRequestDigest.cs b/src/KubernetesClient/KubernetesRequestDigest.cs index b6d669a..8024d9f 100644 --- a/src/KubernetesClient/KubernetesRequestDigest.cs +++ b/src/KubernetesClient/KubernetesRequestDigest.cs @@ -8,7 +8,7 @@ namespace k8s { internal class KubernetesRequestDigest { - private static Regex resourcePattern = + private static readonly Regex ResourcePattern = new Regex(@"^/(api|apis)(/\S+)?/v\d\w*/\S+", RegexOptions.Compiled); public string Path { get; } @@ -94,13 +94,13 @@ namespace k8s private static KubernetesRequestDigest NonResource(string urlPath) { - KubernetesRequestDigest digest = new KubernetesRequestDigest(urlPath, true, "nonresource", "na", "na", "na"); + var digest = new KubernetesRequestDigest(urlPath, true, "nonresource", "na", "na", "na"); return digest; } public static bool IsResourceRequest(string urlPath) { - return resourcePattern.Matches(urlPath).Count > 0; + return ResourcePattern.Matches(urlPath).Count > 0; } private static bool HasWatchParameter(HttpRequestMessage request) diff --git a/src/KubernetesClient/LeaderElection/LeaderElectionRecord.cs b/src/KubernetesClient/LeaderElection/LeaderElectionRecord.cs index 1bdb54f..98bae7d 100644 --- a/src/KubernetesClient/LeaderElection/LeaderElectionRecord.cs +++ b/src/KubernetesClient/LeaderElection/LeaderElectionRecord.cs @@ -62,7 +62,7 @@ namespace k8s.LeaderElection { unchecked { - var hashCode = (HolderIdentity != null ? HolderIdentity.GetHashCode() : 0); + var hashCode = HolderIdentity != null ? HolderIdentity.GetHashCode() : 0; hashCode = (hashCode * 397) ^ AcquireTime.GetHashCode(); hashCode = (hashCode * 397) ^ RenewTime.GetHashCode(); return hashCode; diff --git a/src/KubernetesClient/LeaderElection/LeaderElector.cs b/src/KubernetesClient/LeaderElection/LeaderElector.cs index 8d0291e..af25059 100644 --- a/src/KubernetesClient/LeaderElection/LeaderElector.cs +++ b/src/KubernetesClient/LeaderElection/LeaderElector.cs @@ -1,7 +1,7 @@ +using k8s.Autorest; using System.Net; using System.Threading; using System.Threading.Tasks; -using k8s.Autorest; namespace k8s.LeaderElection { diff --git a/src/KubernetesClient/LeaderElection/ResourceLock/MetaObjectLock.cs b/src/KubernetesClient/LeaderElection/ResourceLock/MetaObjectLock.cs index 0e5e61f..8a0b7de 100644 --- a/src/KubernetesClient/LeaderElection/ResourceLock/MetaObjectLock.cs +++ b/src/KubernetesClient/LeaderElection/ResourceLock/MetaObjectLock.cs @@ -1,7 +1,7 @@ +using k8s.Autorest; +using k8s.Models; using System.Threading; using System.Threading.Tasks; -using k8s.Models; -using k8s.Autorest; namespace k8s.LeaderElection.ResourceLock @@ -9,10 +9,10 @@ namespace k8s.LeaderElection.ResourceLock public abstract class MetaObjectLock : ILock where T : class, IMetadata, new() { - private IKubernetes client; - private string ns; - private string name; - private string identity; + private readonly IKubernetes client; + private readonly string ns; + private readonly string name; + private readonly string identity; private T metaObjCache; protected MetaObjectLock(IKubernetes client, string @namespace, string name, string identity) diff --git a/src/KubernetesClient/LeaderElection/ResourceLock/MultiLock.cs b/src/KubernetesClient/LeaderElection/ResourceLock/MultiLock.cs index 4ce6679..920c25d 100644 --- a/src/KubernetesClient/LeaderElection/ResourceLock/MultiLock.cs +++ b/src/KubernetesClient/LeaderElection/ResourceLock/MultiLock.cs @@ -5,8 +5,8 @@ namespace k8s.LeaderElection.ResourceLock { public class MultiLock : ILock { - private ILock primary; - private ILock secondary; + private readonly ILock primary; + private readonly ILock secondary; public MultiLock(ILock primary, ILock secondary) { diff --git a/src/KubernetesClient/MuxedStream.cs b/src/KubernetesClient/MuxedStream.cs index ed73d17..8670bab 100644 --- a/src/KubernetesClient/MuxedStream.cs +++ b/src/KubernetesClient/MuxedStream.cs @@ -7,9 +7,9 @@ namespace k8s /// public class MuxedStream : Stream { - private ByteBuffer inputBuffer; - private byte? outputIndex; - private StreamDemuxer muxer; + private readonly ByteBuffer inputBuffer; + private readonly byte? outputIndex; + private readonly StreamDemuxer muxer; /// /// Initializes a new instance of the class. diff --git a/src/KubernetesClient/Watcher.cs b/src/KubernetesClient/Watcher.cs index f8d4c4e..9e19960 100644 --- a/src/KubernetesClient/Watcher.cs +++ b/src/KubernetesClient/Watcher.cs @@ -1,9 +1,9 @@ +using k8s.Models; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; -using k8s.Models; namespace k8s { diff --git a/src/KubernetesClient/WatcherExt.cs b/src/KubernetesClient/WatcherExt.cs index 4cf7a82..f4fbd41 100644 --- a/src/KubernetesClient/WatcherExt.cs +++ b/src/KubernetesClient/WatcherExt.cs @@ -1,7 +1,7 @@ +using k8s.Autorest; +using k8s.Exceptions; using System.IO; using System.Threading.Tasks; -using k8s.Exceptions; -using k8s.Autorest; namespace k8s { diff --git a/src/LibKubernetesGenerator/ApiGenerator.cs b/src/LibKubernetesGenerator/ApiGenerator.cs index 8c151fd..e860d2c 100644 --- a/src/LibKubernetesGenerator/ApiGenerator.cs +++ b/src/LibKubernetesGenerator/ApiGenerator.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; -using System.Linq; using CaseExtensions; using Microsoft.CodeAnalysis; using NSwag; +using System.Collections.Generic; +using System.Linq; namespace LibKubernetesGenerator { diff --git a/src/LibKubernetesGenerator/ClassNameHelper.cs b/src/LibKubernetesGenerator/ClassNameHelper.cs index 434091e..b7e2240 100644 --- a/src/LibKubernetesGenerator/ClassNameHelper.cs +++ b/src/LibKubernetesGenerator/ClassNameHelper.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; -using System.Linq; using CaseExtensions; using NJsonSchema; using NSwag; using Nustache.Core; +using System.Collections.Generic; +using System.Linq; namespace LibKubernetesGenerator { diff --git a/src/LibKubernetesGenerator/GeneralNameHelper.cs b/src/LibKubernetesGenerator/GeneralNameHelper.cs index b34b7dc..c864644 100644 --- a/src/LibKubernetesGenerator/GeneralNameHelper.cs +++ b/src/LibKubernetesGenerator/GeneralNameHelper.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; using CaseExtensions; using NJsonSchema; using NSwag; using Nustache.Core; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; namespace LibKubernetesGenerator { @@ -91,7 +91,7 @@ namespace LibKubernetesGenerator var parameter = arguments[0] as OpenApiParameter; context.Write(GetDotNetName(parameter.Name)); - if (arguments.Count > 1 && arguments[1] as string == "true" && !parameter.IsRequired) + if (arguments.Count > 1 && (arguments[1] as string) == "true" && !parameter.IsRequired) { context.Write(" = null"); } diff --git a/src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs b/src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs index 325e83c..241b1bb 100644 --- a/src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs +++ b/src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs @@ -12,11 +12,11 @@ namespace LibKubernetesGenerator [Generator] public class KubernetesClientSourceGenerator : ISourceGenerator { - private static object execlock = new object(); + private static readonly object Execlock = new object(); public void ExecuteInner(GeneratorExecutionContext context) { - lock (execlock) + lock (Execlock) { var swaggerfile = context.AdditionalFiles.First(f => f.Path.EndsWith("swagger.json")); var swagger = OpenApiDocument.FromJsonAsync(swaggerfile.GetText().ToString()).GetAwaiter().GetResult(); @@ -131,11 +131,11 @@ namespace LibKubernetesGenerator public void Initialize(GeneratorInitializationContext context) { #if DEBUG - // if (!Debugger.IsAttached) - // { - // Debugger.Launch(); - // } + // if (!Debugger.IsAttached) + // { + // Debugger.Launch(); + // } #endif - } + } } } diff --git a/src/LibKubernetesGenerator/MetaHelper.cs b/src/LibKubernetesGenerator/MetaHelper.cs index 5cc7013..d11cdfd 100644 --- a/src/LibKubernetesGenerator/MetaHelper.cs +++ b/src/LibKubernetesGenerator/MetaHelper.cs @@ -1,8 +1,8 @@ -using System; -using System.Collections.Generic; using NJsonSchema; using NSwag; using Nustache.Core; +using System; +using System.Collections.Generic; namespace LibKubernetesGenerator { diff --git a/src/LibKubernetesGenerator/ModelExtGenerator.cs b/src/LibKubernetesGenerator/ModelExtGenerator.cs index 13d942d..a518995 100644 --- a/src/LibKubernetesGenerator/ModelExtGenerator.cs +++ b/src/LibKubernetesGenerator/ModelExtGenerator.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using System.Linq; using Microsoft.CodeAnalysis; using NSwag; +using System.Collections.Generic; +using System.Linq; namespace LibKubernetesGenerator { diff --git a/src/LibKubernetesGenerator/ParamHelper.cs b/src/LibKubernetesGenerator/ParamHelper.cs index 35ad932..ffe6fed 100644 --- a/src/LibKubernetesGenerator/ParamHelper.cs +++ b/src/LibKubernetesGenerator/ParamHelper.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NSwag; using Nustache.Core; +using System.Collections.Generic; +using System.Linq; namespace LibKubernetesGenerator { diff --git a/src/LibKubernetesGenerator/PluralHelper.cs b/src/LibKubernetesGenerator/PluralHelper.cs index 4d48a3f..26d9390 100644 --- a/src/LibKubernetesGenerator/PluralHelper.cs +++ b/src/LibKubernetesGenerator/PluralHelper.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NSwag; using Nustache.Core; +using System; +using System.Collections.Generic; +using System.Linq; namespace LibKubernetesGenerator { @@ -11,7 +11,7 @@ namespace LibKubernetesGenerator { private readonly Dictionary _classNameToPluralMap; private readonly ClassNameHelper classNameHelper; - private HashSet opblackList = new HashSet() + private readonly HashSet opblackList = new HashSet() { "listClusterCustomObject", "listNamespacedCustomObject", diff --git a/src/LibKubernetesGenerator/StringHelpers.cs b/src/LibKubernetesGenerator/StringHelpers.cs index bba545b..22e0466 100644 --- a/src/LibKubernetesGenerator/StringHelpers.cs +++ b/src/LibKubernetesGenerator/StringHelpers.cs @@ -1,11 +1,11 @@ +using NJsonSchema; +using Nustache.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Text.RegularExpressions; -using NJsonSchema; -using Nustache.Core; namespace LibKubernetesGenerator { diff --git a/src/LibKubernetesGenerator/TypeHelper.cs b/src/LibKubernetesGenerator/TypeHelper.cs index 133cf8e..7bed705 100644 --- a/src/LibKubernetesGenerator/TypeHelper.cs +++ b/src/LibKubernetesGenerator/TypeHelper.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; using NJsonSchema; using NSwag; using Nustache.Core; +using System; +using System.Collections.Generic; +using System.Linq; namespace LibKubernetesGenerator { diff --git a/src/LibKubernetesGenerator/UtilHelper.cs b/src/LibKubernetesGenerator/UtilHelper.cs index 17f9609..25a2d18 100644 --- a/src/LibKubernetesGenerator/UtilHelper.cs +++ b/src/LibKubernetesGenerator/UtilHelper.cs @@ -1,8 +1,8 @@ +using NSwag; +using Nustache.Core; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; -using NSwag; -using Nustache.Core; namespace LibKubernetesGenerator { diff --git a/tests/KubernetesClient.Tests/ItemsEnumTests.cs b/tests/KubernetesClient.Tests/ItemsEnumTests.cs index 2fd4098..deac32c 100644 --- a/tests/KubernetesClient.Tests/ItemsEnumTests.cs +++ b/tests/KubernetesClient.Tests/ItemsEnumTests.cs @@ -1,5 +1,5 @@ -using Xunit; using k8s.Models; +using Xunit; namespace k8s.Tests; diff --git a/tests/KubernetesClient.Tests/KubernetesExecTests.cs b/tests/KubernetesClient.Tests/KubernetesExecTests.cs index 6bc82c4..1b7e390 100644 --- a/tests/KubernetesClient.Tests/KubernetesExecTests.cs +++ b/tests/KubernetesClient.Tests/KubernetesExecTests.cs @@ -23,13 +23,17 @@ namespace k8s.Tests [Fact] public async Task WebSocketNamespacedPodExecAsync() { - Kubernetes client = new Kubernetes(new KubernetesClientConfiguration() + var clientConfiguration = new KubernetesClientConfiguration() { Host = "http://localhost", Username = "my-user", Password = "my-secret-password", - }); - client.BaseUri = new Uri("http://localhost"); + }; + + var client = new Kubernetes(clientConfiguration) + { + BaseUri = new Uri("http://localhost"), + }; MockWebSocketBuilder mockWebSocketBuilder = new MockWebSocketBuilder(); client.CreateWebSocketBuilder = () => mockWebSocketBuilder; @@ -113,8 +117,10 @@ namespace k8s.Tests Host = "http://localhost", Username = "my-user", Password = "my-secret-password", - }); - client.BaseUri = new Uri("http://localhost"); + }) + { + BaseUri = new Uri("http://localhost"), + }; MockWebSocketBuilder mockWebSocketBuilder = new MockWebSocketBuilder(); client.CreateWebSocketBuilder = () => mockWebSocketBuilder; diff --git a/tests/KubernetesClient.Tests/KubernetesYamlTests.cs b/tests/KubernetesClient.Tests/KubernetesYamlTests.cs index 050b288..9e0482a 100644 --- a/tests/KubernetesClient.Tests/KubernetesYamlTests.cs +++ b/tests/KubernetesClient.Tests/KubernetesYamlTests.cs @@ -40,8 +40,10 @@ metadata: [Fact] public void LoadAllFromStringWithTypes() { - var types = new Dictionary(); - types.Add("v1/Pod", typeof(MyPod)); + var types = new Dictionary + { + { "v1/Pod", typeof(MyPod) }, + }; var content = @"apiVersion: v1 kind: Pod @@ -89,8 +91,11 @@ metadata: [Fact] public void LoadAllFromStringWithAdditionalPropertiesAndTypes() { - var types = new Dictionary(); - types.Add("v1/Pod", typeof(MyPod)); + var types = new Dictionary + { + { "v1/Pod", typeof(MyPod) }, + }; + var content = @"apiVersion: v1 kind: Pod metadata: @@ -150,8 +155,10 @@ metadata: [Fact] public async Task LoadAllFromFileWithTypes() { - var types = new Dictionary(); - types.Add("v1/Pod", typeof(MyPod)); + var types = new Dictionary + { + { "v1/Pod", typeof(MyPod) }, + }; var content = @"apiVersion: v1 kind: Pod @@ -279,12 +286,11 @@ metadata: name: foo "; - using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) - { - var obj = KubernetesYaml.LoadFromStreamAsync(stream).Result; + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)); - Assert.Equal("foo", obj.Metadata.Name); - } + var obj = KubernetesYaml.LoadFromStreamAsync(stream).Result; + + Assert.Equal("foo", obj.Metadata.Name); } [Fact] @@ -430,18 +436,17 @@ spec: private static IEnumerable ToLines(string s) { - using (var reader = new StringReader(s)) - { - for (; ; ) - { - var line = reader.ReadLine(); - if (line == null) - { - yield break; - } + using var reader = new StringReader(s); - yield return line; + for (; ; ) + { + var line = reader.ReadLine(); + if (line == null) + { + yield break; } + + yield return line; } } diff --git a/tests/KubernetesClient.Tests/ModelExtensionTests.cs b/tests/KubernetesClient.Tests/ModelExtensionTests.cs index 83037a6..f7b7145 100644 --- a/tests/KubernetesClient.Tests/ModelExtensionTests.cs +++ b/tests/KubernetesClient.Tests/ModelExtensionTests.cs @@ -111,8 +111,12 @@ namespace k8s.Tests public void TestReferences() { // test object references - var pod = new V1Pod() { ApiVersion = "v1", Kind = "Pod" }; - pod.Metadata = new V1ObjectMeta() { Name = "name", NamespaceProperty = "ns", ResourceVersion = "ver", Uid = "id" }; + var pod = new V1Pod + { + ApiVersion = "v1", + Kind = "Pod", + Metadata = new V1ObjectMeta() { Name = "name", NamespaceProperty = "ns", ResourceVersion = "ver", Uid = "id" }, + }; var objr = new V1ObjectReference() { ApiVersion = pod.ApiVersion, Kind = pod.Kind, Name = pod.Name(), NamespaceProperty = pod.Namespace(), Uid = pod.Uid() }; Assert.True(objr.Matches(pod));