Skip to content

Commit

Permalink
Merge pull request microsoft#286 from microsoft/andrueastman/formating
Browse files Browse the repository at this point in the history
Adds formatting/lint checks
  • Loading branch information
andrueastman authored Jul 9, 2024
2 parents f2b6f73 + 6de6bd5 commit 773df94
Show file tree
Hide file tree
Showing 49 changed files with 384 additions and 289 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ jobs:
languages: csharp
- name: Restore dependencies
run: dotnet restore ${{ env.solutionName }}
- name: Check formatting
run: dotnet format ${{ env.solutionName }} --verify-no-changes
- name: Build
run: dotnet build ${{ env.solutionName }} --no-restore /p:UseSharedCompilation=false
- name: Test for net462
Expand Down
2 changes: 1 addition & 1 deletion src/abstractions/Helpers/EnumHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ private static ReadOnlySpan<char> ToEnumRawName<T>(ReadOnlySpan<char> span) wher
}
return result;


}

#if NET5_0_OR_GREATER
Expand Down
14 changes: 7 additions & 7 deletions src/abstractions/extensions/IEnumerableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ public static class IEnumerableExtensions
/// <returns>A <see cref="List{T}"/> containing the elements of the enumerable, or <c>null</c> if the input is <c>null</c>.</returns>
public static List<T>? AsList<T>(this IEnumerable<T>? e)
{
if (e is null) return null;
if(e is null) return null;

if (e is List<T> list) return list;
if(e is List<T> list) return list;

return new List<T>(e);
}
Expand All @@ -37,13 +37,13 @@ public static class IEnumerableExtensions
/// <returns>An array containing the elements of the enumerable, or <c>null</c> if the input is <c>null</c>.</returns>
public static T[]? AsArray<T>(this IEnumerable<T>? e)
{
if (e is null) return null;
if(e is null) return null;

if (e is T[] array) return array;
if(e is T[] array) return array;

T[]? result = null;

if (e is ICollection<T> collection)
if(e is ICollection<T> collection)
{
// Allocate an array with the exact size
result = AllocateOnHeap(collection.Count);
Expand All @@ -53,13 +53,13 @@ public static class IEnumerableExtensions

// First pass to count the elements
int count = 0;
foreach (var item in e) count++;
foreach(var item in e) count++;

result = AllocateOnHeap(count);

// Second pass to copy the elements
count = 0;
foreach (var item in e) result[count++] = item;
foreach(var item in e) result[count++] = item;
return result;

static T[] AllocateOnHeap(int count)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ public static async Task<IEnumerable<T>> DeserializeCollectionAsync<T>(string co
/// <param name="serializedRepresentation">The serialized representation of the objects.</param>
/// <param name="parsableFactory">The factory to create the object.</param>
/// <param name="cancellationToken">The cancellation token for the task</param>
public static async Task<IEnumerable<T>> DeserializeCollectionAsync<T>(string contentType, string serializedRepresentation,
public static async Task<IEnumerable<T>> DeserializeCollectionAsync<T>(string contentType, string serializedRepresentation,
ParsableFactory<T> parsableFactory, CancellationToken cancellationToken = default) where T : IParsable
{
if(string.IsNullOrEmpty(serializedRepresentation)) throw new ArgumentNullException(nameof(serializedRepresentation));
Expand Down
4 changes: 2 additions & 2 deletions src/abstractions/serialization/ParseNodeProxyFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ private void WireParseNode(IParseNode node)
/// <param name="contentType">The content type of the parse node.</param>
/// <param name="cancellationToken">The cancellation token for the task</param>
/// <returns>A parse node.</returns>
public async Task<IParseNode> GetRootParseNodeAsync(string contentType, Stream content,
public async Task<IParseNode> GetRootParseNodeAsync(string contentType, Stream content,
CancellationToken cancellationToken = default)
{
if (_concrete is not IAsyncParseNodeFactory asyncConcrete)
if(_concrete is not IAsyncParseNodeFactory asyncConcrete)
{
throw new Exception("IAsyncParseNodeFactory is required for async operations");
}
Expand Down
2 changes: 1 addition & 1 deletion src/abstractions/serialization/UntypedInteger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Microsoft.Kiota.Abstractions.Serialization
/// Represents an untyped node with integer value.
/// </summary>
/// <param name="value">The integer value associated with the node.</param>
public class UntypedInteger(int value): UntypedNode
public class UntypedInteger(int value) : UntypedNode
{
private readonly int _value = value;
/// <summary>
Expand Down
24 changes: 15 additions & 9 deletions src/authentication/azure/AzureIdentityAccessTokenProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class AzureIdentityAccessTokenProvider : IAccessTokenProvider, IDisposabl
/// <param name="allowedHosts">The list of allowed hosts for which to request access tokens.</param>
/// <param name="scopes">The scopes to request the access token for.</param>
/// <param name="observabilityOptions">The observability options to use for the authentication provider.</param>
public AzureIdentityAccessTokenProvider(TokenCredential credential, string []? allowedHosts = null, ObservabilityOptions? observabilityOptions = null, params string[] scopes)
public AzureIdentityAccessTokenProvider(TokenCredential credential, string[]? allowedHosts = null, ObservabilityOptions? observabilityOptions = null, params string[] scopes)
{
_credential = credential ?? throw new ArgumentNullException(nameof(credential));

Expand Down Expand Up @@ -61,33 +61,39 @@ public AzureIdentityAccessTokenProvider(TokenCredential credential, string []? a
public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object>? additionalAuthenticationContext = default, CancellationToken cancellationToken = default)
{
using var span = _activitySource?.StartActivity(nameof(GetAuthorizationTokenAsync));
if(!AllowedHostsValidator.IsUrlHostValid(uri)) {
if(!AllowedHostsValidator.IsUrlHostValid(uri))
{
span?.SetTag("com.microsoft.kiota.authentication.is_url_valid", BoxedFalse);
return string.Empty;
}

if(!uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) && !_localHostStrings.Contains(uri.Host)) {
if(!uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) && !_localHostStrings.Contains(uri.Host))
{
span?.SetTag("com.microsoft.kiota.authentication.is_url_valid", BoxedFalse);
throw new ArgumentException("Only https is supported");
}
span?.SetTag("com.microsoft.kiota.authentication.is_url_valid", BoxedTrue);

string? decodedClaim = null;
if (additionalAuthenticationContext is not null &&
if(additionalAuthenticationContext is not null &&
additionalAuthenticationContext.ContainsKey(ClaimsKey) &&
additionalAuthenticationContext[ClaimsKey] is string claims) {
additionalAuthenticationContext[ClaimsKey] is string claims)
{
span?.SetTag("com.microsoft.kiota.authentication.additional_claims_provided", BoxedTrue);
var decodedBase64Bytes = Convert.FromBase64String(claims);
decodedClaim = Encoding.UTF8.GetString(decodedBase64Bytes);
} else
}
else
span?.SetTag("com.microsoft.kiota.authentication.additional_claims_provided", BoxedFalse);

string[] scopes;
if (_scopes.Count > 0) {
if(_scopes.Count > 0)
{
scopes = new string[_scopes.Count];
_scopes.CopyTo(scopes);
} else
scopes = [ $"{uri.Scheme}://{uri.Host}/.default" ];
}
else
scopes = [$"{uri.Scheme}://{uri.Host}/.default"];
span?.SetTag("com.microsoft.kiota.authentication.scopes", string.Join(",", scopes));

var result = await _credential.GetTokenAsync(new TokenRequestContext(scopes, claims: decodedClaim), cancellationToken).ConfigureAwait(false);
Expand Down
3 changes: 2 additions & 1 deletion src/authentication/azure/ObservabilityOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ namespace Microsoft.Kiota.Authentication.Azure;
/// <summary>
/// Holds the tracing, metrics and logging configuration for the authentication provider
/// </summary>
public class ObservabilityOptions {
public class ObservabilityOptions
{
private static readonly Lazy<string> _name = new Lazy<string>(() => typeof(ObservabilityOptions).Namespace!);
/// <summary>
/// Gets the observability name to use for the tracer
Expand Down
6 changes: 4 additions & 2 deletions src/generated/KiotaVersionGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ public void Execute(GeneratorExecutionContext context)
var projectDirectory = Path.GetDirectoryName(mainSyntaxTree.FilePath);

var version = "unknown";
try {
try
{
XmlDocument csproj = new XmlDocument();
projectDirectory = Path.Combine(projectDirectory, "..", "..", "..", "..", "Directory.Build.props");
csproj.Load(projectDirectory);
version = csproj.GetElementsByTagName("VersionPrefix")[0].InnerText;
} catch (Exception e)
}
catch(Exception e)
{
throw new FileNotFoundException($"KiotaVersionGenerator expanded in an invalid project, missing 'Directory.Build.props' file in the following directory {projectDirectory}", e);
}
Expand Down
22 changes: 11 additions & 11 deletions src/http/httpClient/HttpClientRequestAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,21 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Serialization;
using Microsoft.Kiota.Abstractions.Store;
using Microsoft.Kiota.Abstractions.Authentication;
using System.Threading;
using System.Net;
using Microsoft.Kiota.Abstractions.Extensions;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Diagnostics;
using Microsoft.Kiota.Abstractions.Serialization;
using Microsoft.Kiota.Abstractions.Store;
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.Kiota.Http.HttpClientLibrary
{
Expand Down Expand Up @@ -397,8 +397,8 @@ private async Task ThrowIfFailedResponse(HttpResponseMessage response, Dictionar
var statusCodeAsInt = (int)response.StatusCode;
var statusCodeAsString = statusCodeAsInt.ToString();
var responseHeadersDictionary = new Dictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase);
foreach (var header in response.Headers)
responseHeadersDictionary[header.Key] = header.Value;
foreach(var header in response.Headers)
responseHeadersDictionary[header.Key] = header.Value;
ParsableFactory<IParsable>? errorFactory;
if(errorMapping == null ||
!errorMapping.TryGetValue(statusCodeAsString, out errorFactory) &&
Expand Down Expand Up @@ -528,7 +528,7 @@ private async Task<HttpResponseMessage> RetryCAEResponseIfRequired(HttpResponseM

if(authHeader is not null)
{
var authHeaderParameters = authHeader.Parameter?.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries);
var authHeaderParameters = authHeader.Parameter?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

string? rawResponseClaims = null;
if(authHeaderParameters != null)
Expand Down
2 changes: 1 addition & 1 deletion src/http/httpClient/Middleware/ActivitySourceRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace Microsoft.Kiota.Http.HttpClientLibrary.Middleware;
/// </summary>
internal class ActivitySourceRegistry
{
private readonly ConcurrentDictionary<string, ActivitySource> _activitySources = new (StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, ActivitySource> _activitySources = new(StringComparer.OrdinalIgnoreCase);

/// <summary>
/// The default instance of the registry
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Microsoft.Kiota.Http.HttpClientLibrary.Middleware.Options
/// <summary>
/// The redirect request option class
/// </summary>
public class RedirectHandlerOption: IRequestOption
public class RedirectHandlerOption : IRequestOption
{
private const int DefaultMaxRedirect = 5;
private const int MaxMaxRedirect = 20;
Expand Down
3 changes: 2 additions & 1 deletion src/http/httpClient/ObservabilityOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ namespace Microsoft.Kiota.Http.HttpClientLibrary;
/// <summary>
/// Holds the tracing, metrics and logging configuration for the request adapter
/// </summary>
public class ObservabilityOptions : IRequestOption {
public class ObservabilityOptions : IRequestOption
{
/// <summary>
/// Gets or sets a value indicating whether to include attributes which could contain EUII information.
/// </summary>
Expand Down
39 changes: 22 additions & 17 deletions src/serialization/form/FormParseNode.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Xml;
using System;
using System.Collections.Generic;
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Extensions;
using Microsoft.Kiota.Abstractions.Serialization;
Expand All @@ -26,15 +26,15 @@ public FormParseNode(string rawValue)
Fields = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
char[] pairDelimiter = new char[] { '=' };
string[] pairs = rawValue.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string pair in pairs)
foreach(string pair in pairs)
{
string[] keyValue = pair.Split(pairDelimiter, StringSplitOptions.RemoveEmptyEntries);
if (keyValue.Length == 2)
if(keyValue.Length == 2)
{
string key = SanitizeKey(keyValue[0]);
string value = keyValue[1].Trim();

if (Fields.ContainsKey(key))
if(Fields.ContainsKey(key))
{
Fields[key] += $",{value}";
}
Expand All @@ -46,8 +46,9 @@ public FormParseNode(string rawValue)
}
}

private static string SanitizeKey(string key) {
if (string.IsNullOrEmpty(key)) return key;
private static string SanitizeKey(string key)
{
if(string.IsNullOrEmpty(key)) return key;
return Uri.UnescapeDataString(key.Trim());
}
/// <inheritdoc/>
Expand All @@ -57,16 +58,18 @@ private static string SanitizeKey(string key) {
/// <inheritdoc/>
public bool? GetBoolValue() => bool.TryParse(DecodedValue, out var result) && result;
/// <inheritdoc/>
public byte[]? GetByteArrayValue() {
public byte[]? GetByteArrayValue()
{
var rawValue = DecodedValue;
if(string.IsNullOrEmpty(rawValue)) return null;
return Convert.FromBase64String(rawValue);
}
/// <inheritdoc/>
public byte? GetByteValue() => byte.TryParse(DecodedValue, out var result) ? result : null;
/// <inheritdoc/>
public IParseNode? GetChildNode(string identifier) => Fields.TryGetValue(SanitizeKey(identifier), out var value) ?
new FormParseNode(value){
public IParseNode? GetChildNode(string identifier) => Fields.TryGetValue(SanitizeKey(identifier), out var value) ?
new FormParseNode(value)
{
OnBeforeAssignFieldValues = OnBeforeAssignFieldValues,
OnAfterAssignFieldValues = OnAfterAssignFieldValues
} : null;
Expand Down Expand Up @@ -94,7 +97,7 @@ private static string SanitizeKey(string key) {
public IEnumerable<T> GetCollectionOfPrimitiveValues<T>()
{
var genericType = typeof(T);
var primitiveValueCollection = DecodedValue.Split(new[] { ',' } , StringSplitOptions.RemoveEmptyEntries);
var primitiveValueCollection = DecodedValue.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach(var collectionValue in primitiveValueCollection)
{
var currentParseNode = new FormParseNode(collectionValue)
Expand Down Expand Up @@ -149,7 +152,8 @@ public IEnumerable<T> GetCollectionOfPrimitiveValues<T>()
/// <inheritdoc/>
public long? GetLongValue() => long.TryParse(DecodedValue, out var result) ? result : null;
/// <inheritdoc/>
public T GetObjectValue<T>(ParsableFactory<T> factory) where T : IParsable {
public T GetObjectValue<T>(ParsableFactory<T> factory) where T : IParsable
{
var item = factory(this);
OnBeforeAssignFieldValues?.Invoke(item);
AssignFieldValues(item);
Expand Down Expand Up @@ -181,7 +185,7 @@ private void AssignFieldValues<T>(T item) where T : IParsable
OnAfterAssignFieldValues = OnAfterAssignFieldValues
});
}
else if (itemAdditionalData != null)
else if(itemAdditionalData != null)
{
Debug.WriteLine($"found additional property {fieldValue.Key} to deserialize");
IDictionaryExtensions.TryAdd(itemAdditionalData, fieldValue.Key, fieldValue.Value);
Expand All @@ -200,7 +204,8 @@ private void AssignFieldValues<T>(T item) where T : IParsable
public string GetStringValue() => DecodedValue;

/// <inheritdoc/>
public TimeSpan? GetTimeSpanValue() {
public TimeSpan? GetTimeSpanValue()
{
var rawString = DecodedValue;
if(string.IsNullOrEmpty(rawString))
return null;
Expand All @@ -218,7 +223,7 @@ private void AssignFieldValues<T>(T item) where T : IParsable
IEnumerable<T?> IParseNode.GetCollectionOfEnumValues<T>()
#endif
{
foreach (var v in DecodedValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
foreach(var v in DecodedValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
yield return GetEnumValueInternal<T>(v);
}

Expand All @@ -230,12 +235,12 @@ private void AssignFieldValues<T>(T item) where T : IParsable
{
return GetEnumValueInternal<T>(DecodedValue);
}

private static T? GetEnumValueInternal<T>(string rawValue) where T : struct, Enum
{
if(string.IsNullOrEmpty(rawValue))
return null;
if (typeof(T).IsDefined(typeof(FlagsAttribute)))
if(typeof(T).IsDefined(typeof(FlagsAttribute)))
{
ReadOnlySpan<char> valueSpan = rawValue.AsSpan();
int value = 0;
Expand Down
Loading

0 comments on commit 773df94

Please sign in to comment.