Skip to content

Commit

Permalink
Fixing all the bloody warnings that .net bits produce :)
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real committed Nov 23, 2024
1 parent 3594376 commit 3eb9a2f
Show file tree
Hide file tree
Showing 31 changed files with 122 additions and 115 deletions.
25 changes: 25 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,28 @@ dotnet_diagnostic.CA1069.severity = none
dotnet_diagnostic.CA2008.severity = none
#Use concrete types
dotnet_diagnostic.CA1859.severity = none

# After this line there are suppressions from .NET 9 upgraqdes, check these later

#Use var keyword
dotnet_diagnostic.IDE0008.severity = none
#Use namespace declaration
dotnet_diagnostic.IDE0160.severity = none
#Discard Expression value never used
dotnet_diagnostic.IDE0058.severity = none
#A type inside an executable assembly is declared as public.
dotnet_diagnostic.CA1015.severity = none
dotnet_diagnostic.CA1515.severity = none
dotnet_diagnostic.CS0618.severity = none
dotnet_diagnostic.IDE0011.severity = none
dotnet_diagnostic.IDE1006.severity = none
dotnet_diagnostic.IDE0040.severity = none
dotnet_diagnostic.IDE0079.severity = none
dotnet_diagnostic.IDE0022.severity = none
dotnet_diagnostic.IDE0300.severity = none
dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0130.severity = none
dotnet_diagnostic.IDE0046.severity = none
dotnet_diagnostic.IDE0072.severity = none
dotnet_diagnostic.IDE0005.severity = none

3 changes: 2 additions & 1 deletion .github/workflows/ci_build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ jobs:
run: echo "::add-matcher::.github/matchers/dotnet.json"

- name: 🛠️ Build code
run: dotnet build --configuration Release -p:TreatWarningsAsErrors=true
run: dotnet build --configuration Release
# run: dotnet build --configuration Release -p:TreatWarningsAsErrors=true temprarily disabled due to Nuget bug

- name: 👀 Unit Test
run: |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public void TestAddYamlConfigGetsEnumWithUnderlyingTypeCorrectly()
var config = GetObjectFromSection<IEnumerable<TestShortEnum>>("AnotherTestShortEnum");
// CHECK
config!.Should().HaveCount(2);
Enum.GetUnderlyingType(config!.First().GetType()).Should().Be(typeof(ushort));
Enum.GetUnderlyingType(config!.First().GetType()).Should().Be<ushort>();
}

private static T? GetObjectFromSection<T>(string sectionName)
Expand Down Expand Up @@ -218,17 +218,17 @@ public record CollectionBindingTestClass

public record CollectionBindingIEnumerableWithInitTestClass
{
public IEnumerable<string>? SomeEnumerable { get; init; } = new List<string>();
public IEnumerable<string>? SomeEnumerable { get; init; } = [];
}

public record CollectionBindingIReadOnlyListWithInitTestClass
{
public IReadOnlyList<string>? SomeReadOnlyList { get; init; } = new List<string>();
public IReadOnlyList<string>? SomeReadOnlyList { get; init; } = [];
}

public record CollectionBindingIReadOnlyCollectionWithInitTestClass
{
public IReadOnlyCollection<string>? SomeReadOnlyCollection { get; init; } = new List<string>();
public IReadOnlyCollection<string>? SomeReadOnlyCollection { get; init; } = [];
}

public record CollectionBindingIReadOnlyDictionaryWithInitTestClass
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@ public static void AddRange(this JsonObject target, JsonObject? toMerge)
var k = kvp.Key;
var v = kvp.Value;

if (target.ContainsKey(k))
target.Remove(k);
target.Remove(k);

target.Add(new(k, v?.Deserialize<JsonNode>()));
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisp
return disposable;
});

cancellationTokenRegistration = _cancellationTokenSource.Token.Register(() => subscription.Dispose());
cancellationTokenRegistration = _cancellationTokenSource.Token.Register(subscription.Dispose);

return subscription;
}
Expand All @@ -52,7 +52,7 @@ public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<ISchedu
return disposable;
});

cancellationTokenRegistration = _cancellationTokenSource.Token.Register(() => subscription.Dispose());
cancellationTokenRegistration = _cancellationTokenSource.Token.Register(subscription.Dispose);

return subscription;
}
Expand All @@ -73,7 +73,7 @@ public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<I
return disposable;
});

cancellationTokenRegistration = _cancellationTokenSource.Token.Register(() => subscription.Dispose());
cancellationTokenRegistration = _cancellationTokenSource.Token.Register(subscription.Dispose);

return subscription;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@ namespace NetDaemon.Extensions.Scheduler;
/// <summary>
/// Provides scheduling capability to be injected into apps
/// </summary>
internal sealed class NetDaemonScheduler : INetDaemonScheduler, IDisposable
/// <remarks>
/// Constructor
/// </remarks>
/// <param name="logger">Injected logger</param>
/// <param name="reactiveScheduler">Used for unit testing the scheduler</param>
internal sealed class NetDaemonScheduler(ILogger<NetDaemonScheduler>? logger = null, IScheduler? reactiveScheduler = null) : INetDaemonScheduler, IDisposable
{
private readonly CancellationTokenSource _cancelTimers;
private readonly CancellationTokenSource _cancelTimers = new();
private volatile bool _disposed;

private static ILoggerFactory DefaultLoggerFactory => LoggerFactory.Create(builder =>
Expand All @@ -24,20 +29,8 @@ internal sealed class NetDaemonScheduler : INetDaemonScheduler, IDisposable
.AddConsole();
});

private readonly ILogger _logger;
private readonly IScheduler _reactiveScheduler;

/// <summary>
/// Constructor
/// </summary>
/// <param name="logger">Injected logger</param>
/// <param name="reactiveScheduler">Used for unit testing the scheduler</param>
public NetDaemonScheduler(ILogger<NetDaemonScheduler>? logger = null, IScheduler? reactiveScheduler = null)
{
_cancelTimers = new();
_logger = logger ?? DefaultLoggerFactory.CreateLogger<NetDaemonScheduler>();
_reactiveScheduler = reactiveScheduler ?? TaskPoolScheduler.Default;
}
private readonly ILogger _logger = logger ?? DefaultLoggerFactory.CreateLogger<NetDaemonScheduler>();
private readonly IScheduler _reactiveScheduler = reactiveScheduler ?? TaskPoolScheduler.Default;

/// <inheritdoc/>
public IDisposable RunEvery(TimeSpan timespan, Action action)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public TextToSpeechService(IServiceProvider provider, ILogger<ITextToSpeechServi
{
_provider = provider;
_logger = logger;
_processTtsTask = Task.Run(async () => await ProcessTtsMessages().ConfigureAwait(false));
_processTtsTask = Task.Run(ProcessTtsMessages);
}

public void Speak(string entityId, string message, string service, string? language, object? options)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public static IEnumerable<MemberDeclarationSyntax> Generate(IReadOnlyCollection<

foreach (var domainMetadata in metaData.GroupBy(m => m.EntitiesForDomainClassName))
{
yield return GenerateEntitiesForDomainClass(domainMetadata.Key, domainMetadata.ToList());
yield return GenerateEntitiesForDomainClass(domainMetadata.Key, [.. domainMetadata]);
}
foreach (var domainMetadata in metaData)
{
Expand Down Expand Up @@ -49,7 +49,7 @@ private static TypeDeclarationSyntax GenerateRootEntitiesClass(IEnumerable<Entit
}).ToArray();

return ClassWithInjectedHaContext(EntitiesClassName)
.WithBase((string)"IEntities")
.WithBase("IEntities")
.AddMembers(properties);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ public static IEnumerable<MemberDeclarationSyntax> Generate(IEnumerable<HassServ
.SelectMany(service => GenerateExtensionMethodsForService(serviceDomain.Domain, service, entityClassNameByDomain))
.ToArray();

if (serviceMethodDeclarations.Length == 0) return null;

return ClassDeclaration(GetEntityDomainExtensionMethodClassName(serviceDomain.Domain))
return serviceMethodDeclarations.Length == 0
? null
: ClassDeclaration(GetEntityDomainExtensionMethodClassName(serviceDomain.Domain))
.AddMembers(serviceMethodDeclarations)
.ToPublic()
.ToStatic();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static IEnumerable<MemberDeclarationSyntax> Generate(IReadOnlyList<HassSe

yield return GenerateRootServicesType(domains);

foreach (var domainServicesGroup in serviceDomains.Where(sd => sd.Services.Any() == true).GroupBy(x => x.Domain, x => x.Services))
foreach (var domainServicesGroup in serviceDomains.Where(sd => sd.Services.Any()).GroupBy(x => x.Domain, x => x.Services))
{
var domain = domainServicesGroup.Key!;
var domainServices = domainServicesGroup
Expand All @@ -37,7 +37,7 @@ private static TypeDeclarationSyntax GenerateRootServicesType(IEnumerable<string
{
var properties = domains.Select(domain => PropertyWithExpressionBodyNew(GetServicesTypeName(domain), domain.ToPascalCase(), "_haContext")).ToArray();

return ClassWithInjectedHaContext(ServicesClassName).WithBase((string)"IServices").AddMembers(properties);
return ClassWithInjectedHaContext(ServicesClassName).WithBase("IServices").AddMembers(properties);
}

private static TypeDeclarationSyntax GenerateRootServicesInterface(IEnumerable<string> domains)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private void SaveGeneratedCode(MemberDeclarationSyntax[] generatedTypes)
if (!generationSettings.GenerateOneFilePerEntity)
{
Console.WriteLine("Generating single file for all entities.");
var unit = Generator.BuildCompilationUnit(generationSettings.Namespace, generatedTypes.ToArray());
var unit = Generator.BuildCompilationUnit(generationSettings.Namespace, [.. generatedTypes]);

Check warning on line 103 in src/HassModel/NetDaemon.HassModel.CodeGenerator/Controller.cs

View check run for this annotation

Codecov / codecov/patch

src/HassModel/NetDaemon.HassModel.CodeGenerator/Controller.cs#L103

Added line #L103 was not covered by tests

Directory.CreateDirectory(Directory.GetParent(generationSettings.OutputFile)!.FullName);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ internal static string TrimPreReleaseVersion(string version)
return parts[0];
}

private static IEnumerable<(string name, string version)>GetPackageReferences(string projectFilePath)
private static IEnumerable<(string name, string version)> GetPackageReferences(string projectFilePath)
{
var csproj = new XmlDocument();
csproj.Load(projectFilePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,11 @@ public static string GetFriendlyName(this Type type)
for (var i = 0; i < typeParameters.Length; i++)
{
string typeParamName = typeParameters[i].GetFriendlyName();
friendlyName += (i == 0 ? typeParamName : ", " + typeParamName);
friendlyName += i == 0 ? typeParamName : ", " + typeParamName;
}
friendlyName += ">";
}

if (type.IsArray)
{
return type.GetElementType()?.GetFriendlyName() + "[]";
}

return friendlyName;
return type.IsArray ? type.GetElementType()?.GetFriendlyName() + "[]" : friendlyName;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace NetDaemon.HassModel.CodeGenerator;

record EntitiesMetaData
{
public IReadOnlyCollection<EntityDomainMetadata> Domains { get; init; } = Array.Empty<EntityDomainMetadata>();
public IReadOnlyCollection<EntityDomainMetadata> Domains { get; init; } = [];
}

record EntityDomainMetadata(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace NetDaemon.HassModel.CodeGenerator;
internal static class EntityMetaDataGenerator
{
/// <summary>
/// Creates metadata describing entities and their attributes based on all the states from HA
/// Creates metadata describing entities and their attributes based on all the states from HA
/// </summary>
public static EntitiesMetaData GetEntityDomainMetaData(IReadOnlyCollection<HassState> entityStates)
{
Expand All @@ -20,21 +20,21 @@ public static EntitiesMetaData GetEntityDomainMetaData(IReadOnlyCollection<HassS

private static EntityDomainMetadata mapEntityDomainMetadata(IGrouping<(string domain, bool isNumeric), HassState> domainGroup) =>
new (
Domain: domainGroup.Key.domain,
IsNumeric: domainGroup.Key.isNumeric,
Domain: domainGroup.Key.domain,
IsNumeric: domainGroup.Key.isNumeric,
Entities: MapToEntityMetaData(domainGroup),
Attributes: AttributeMetaDataGenerator.GetMetaDataFromEntityStates(domainGroup).ToList());

private static List<EntityMetaData> MapToEntityMetaData(IEnumerable<HassState> g)
{
var entityMetaDatas = g.Select(state => new EntityMetaData(
id: state.EntityId,
id: state.EntityId,
friendlyName: GetFriendlyName(state),
cSharpName: GetPreferredCSharpName(state.EntityId)));

entityMetaDatas = DeDuplicateCSharpNames(entityMetaDatas);
return entityMetaDatas.OrderBy(e => e.id).ToList();

return [.. entityMetaDatas.OrderBy(e => e.id)];
}

private static IEnumerable<EntityMetaData> DeDuplicateCSharpNames(IEnumerable<EntityMetaData> entityMetaDatas)
Expand All @@ -43,8 +43,8 @@ private static IEnumerable<EntityMetaData> DeDuplicateCSharpNames(IEnumerable<En
// If we have duplicates we will use the original ID instead and only make sure it is a Valid C# identifier
return entityMetaDatas
.ToLookup(e => e.cSharpName)
.SelectMany(e => e.Count() == 1
? e
.SelectMany(e => e.Count() == 1
? e
: e.Select(i => i with { cSharpName = GetUniqueCSharpName(i.id) }));
}

Expand All @@ -56,7 +56,7 @@ private static IEnumerable<EntityMetaData> DeDuplicateCSharpNames(IEnumerable<En
/// <summary>
/// HA entity ID's can only contain [a-z0-9_]. Which are all also valid in Csharp identifiers.
/// HA does allow the id to begin with a digit which is not valid for C#. In those cases it will be prefixed with
/// an _
/// an _
/// </summary>
private static string GetUniqueCSharpName(string id) => EntityIdHelper.GetEntity(id).ToValidCSharpIdentifier();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static void RegisterServiceCallBack<T>(this IHaContext haContext, string
if (string.IsNullOrWhiteSpace(serviceName))
throw new ArgumentException("serviceName must have a value", serviceName);

haContext.CallService("netdaemon", "register_service", data: new {service = serviceName});
haContext.CallService("netdaemon", "register_service", data: new { service = serviceName });

haContext.Events.Filter<HassServiceEventData<T>>("call_service")
.Where(e => e.Data?.domain == "netdaemon"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static CompilationUnitSyntax GenerateCompilationUnit(
return Generator.BuildCompilationUnit(codeGenerationSettings.Namespace, generatedTypes);
}

public static void AssertCodeCompiles(string generated, string appCode)
public static void AssertCodeCompiles(string generated, string appCode)
{
var compilation = CreateCSharpCompilation(generated, appCode);
var emitResult = compilation.Emit(Stream.Null); // we are not actually interested in the result, just check for errors or warnings
Expand Down Expand Up @@ -73,7 +73,7 @@ public static Assembly LoadDynamicAssembly(string generated, string appCode, Ass

private static CSharpCompilation CreateCSharpCompilation(string generated, string appCode)
{
var syntaxTrees = new []
var syntaxTrees = new[]
{
SyntaxFactory.ParseSyntaxTree(generated, path: "generated.cs", encoding:Encoding.UTF8),
SyntaxFactory.ParseSyntaxTree(appCode, path: "appcode.cs", encoding:Encoding.UTF8)
Expand Down
2 changes: 1 addition & 1 deletion src/HassModel/NetDeamon.HassModel/Entities/EntityState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public record EntityState
/// <summary>
/// The attributes
/// </summary>
public virtual object? Attributes => AttributesJson?.Deserialize<Dictionary<string, object>>() ?? new Dictionary<string, object>();
public virtual object? Attributes => AttributesJson?.Deserialize<Dictionary<string, object>>() ?? [];

/// <summary>Last changed, when state changed from and to different values</summary>
[JsonPropertyName("last_changed")] public DateTime? LastChanged { get; init; }
Expand Down
8 changes: 4 additions & 4 deletions src/HassModel/NetDeamon.HassModel/Event.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ public Event(Event source) : base(source)
{
_lazyData = new Lazy<TData?>(() => DataElement?.Deserialize<TData>());
}
private Lazy<TData?> _lazyData;

private readonly Lazy<TData?> _lazyData;

/// <summary>
/// The Data of this Event deserialized as TData
/// </summary>
public TData? Data => _lazyData.Value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ internal class AppScopedHaContextProvider : IHaContext, IAsyncDisposable
private readonly IHomeAssistantRunner _hassRunner;
private readonly QueuedObservable<HassEvent> _queuedObservable;
private readonly IBackgroundTaskTracker _backgroundTaskTracker;
private readonly ILogger<AppScopedHaContextProvider> _logger;
private readonly IEntityFactory _entityFactory;

private readonly CancellationTokenSource _tokenSource = new();
Expand All @@ -39,7 +38,6 @@ public AppScopedHaContextProvider(
// This makes sure we will unsubscribe when this ContextProvider is Disposed
_queuedObservable = new QueuedObservable<HassEvent>(_entityStateCache.AllEvents, logger);
_backgroundTaskTracker = backgroundTaskTracker;
_logger = logger;
_entityFactory = entityFactory;

// The HaRegistry needs a reference to this AppScopedHaContextProvider And we need the reference
Expand Down
Loading

0 comments on commit 3eb9a2f

Please sign in to comment.