Skip to content

Commit

Permalink
dotnet 5 anayzer continues
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real committed Dec 26, 2020
1 parent d9e8c40 commit 6a85491
Show file tree
Hide file tree
Showing 12 changed files with 104 additions and 87 deletions.
6 changes: 6 additions & 0 deletions src/DaemonRunner/DaemonRunner/DaemonRunner.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00839" />
<PackageReference Include="YamlDotNet" Version="9.1.0" />
<PackageReference Include="Roslynator.Analyzers" Version="3.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
Expand All @@ -42,5 +46,7 @@

<PropertyGroup>
<CodeAnalysisRuleSet>..\..\..\.linting\roslynator.ruleset</CodeAnalysisRuleSet>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@ public static class NetDaemonConsoleThemes
{
private static SystemConsoleTheme SystemTheme { get; } = new(new Dictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>
{
[ConsoleThemeStyle.Text] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Gray},
[ConsoleThemeStyle.SecondaryText] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.DarkGray},
[ConsoleThemeStyle.TertiaryText] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.DarkGray},
[ConsoleThemeStyle.Invalid] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Yellow},
[ConsoleThemeStyle.Null] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Green},
[ConsoleThemeStyle.Name] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Green},
[ConsoleThemeStyle.String] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Green},
[ConsoleThemeStyle.Number] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Green},
[ConsoleThemeStyle.Boolean] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Green},
[ConsoleThemeStyle.Scalar] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Green},
[ConsoleThemeStyle.LevelVerbose] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Gray},
[ConsoleThemeStyle.LevelDebug] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.DarkYellow},
[ConsoleThemeStyle.LevelInformation] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.DarkGreen},
[ConsoleThemeStyle.LevelWarning] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Yellow},
[ConsoleThemeStyle.LevelError] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.Red},
[ConsoleThemeStyle.LevelFatal] = new SystemConsoleThemeStyle {Foreground = ConsoleColor.DarkRed},
[ConsoleThemeStyle.Text] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Gray },
[ConsoleThemeStyle.SecondaryText] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.DarkGray },
[ConsoleThemeStyle.TertiaryText] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.DarkGray },
[ConsoleThemeStyle.Invalid] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Yellow },
[ConsoleThemeStyle.Null] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Green },
[ConsoleThemeStyle.Name] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Green },
[ConsoleThemeStyle.String] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Green },
[ConsoleThemeStyle.Number] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Green },
[ConsoleThemeStyle.Boolean] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Green },
[ConsoleThemeStyle.Scalar] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Green },
[ConsoleThemeStyle.LevelVerbose] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Gray },
[ConsoleThemeStyle.LevelDebug] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.DarkYellow },
[ConsoleThemeStyle.LevelInformation] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.DarkGreen },
[ConsoleThemeStyle.LevelWarning] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Yellow },
[ConsoleThemeStyle.LevelError] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.Red },
[ConsoleThemeStyle.LevelFatal] = new SystemConsoleThemeStyle { Foreground = ConsoleColor.DarkRed },
});

private static AnsiConsoleTheme AnsiTheme { get; } = new(new Dictionary<ConsoleThemeStyle, string>
Expand All @@ -48,7 +48,7 @@ public static class NetDaemonConsoleThemes

public static ConsoleTheme GetThemeByType(string type)
{
return string.Equals(type, "system", StringComparison.InvariantCultureIgnoreCase) ? SystemTheme : AnsiTheme;
return string.Equals(type, "system", StringComparison.OrdinalIgnoreCase) ? SystemTheme : AnsiTheme;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.IO;
using System.Globalization;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using NetDaemon.Common.Exceptions;
using Serilog;
using Serilog.Core;
using Serilog.Events;
Expand All @@ -13,6 +15,11 @@ public static class SerilogConfigurator

public static LoggerConfiguration Configure(LoggerConfiguration loggerConfiguration, IHostEnvironment hostingEnvironment)
{
_ = loggerConfiguration ??
throw new NetDaemonArgumentNullException(nameof(loggerConfiguration));
_ = hostingEnvironment ??
throw new NetDaemonArgumentNullException(nameof(hostingEnvironment));

var loggingConfiguration = GetLoggingConfiguration(hostingEnvironment);

SetMinimumLogLevel(loggingConfiguration.MinimumLevel);
Expand Down Expand Up @@ -40,7 +47,9 @@ private static LoggingConfiguration GetLoggingConfiguration(IHostEnvironment hos

public static void SetMinimumLogLevel(string level)
{
LevelSwitch.MinimumLevel = level.ToLower() switch
_ = level ??
throw new NetDaemonArgumentNullException(nameof(level));
LevelSwitch.MinimumLevel = level.ToLower(CultureInfo.InvariantCulture) switch
{
"info" => LogEventLevel.Information,
"debug" => LogEventLevel.Debug,
Expand Down
12 changes: 9 additions & 3 deletions src/DaemonRunner/DaemonRunner/NetDaemonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
using Serilog;
using NetDaemon.Infrastructure.Config;
using NetDaemon.Common.Exceptions;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;

namespace NetDaemon
{
Expand All @@ -21,6 +23,9 @@ public static class NetDaemonExtensions

public static IHostBuilder UseNetDaemon(this IHostBuilder hostBuilder)
{
_ = hostBuilder ??
throw new NetDaemonArgumentNullException(nameof(hostBuilder));

if (File.Exists(HassioConfigPath))
ReadHassioConfig();

Expand Down Expand Up @@ -70,13 +75,14 @@ private static bool UseLocalAssemblyLoading()
if (string.IsNullOrEmpty(appSource))
return true;

return appSource.EndsWith(".csproj") || appSource.EndsWith(".dll");
return appSource.EndsWith(".csproj", true, CultureInfo.InvariantCulture)
|| appSource.EndsWith(".dll", true, CultureInfo.InvariantCulture);
}

/// <summary>
/// Reads the Home Assistant (hassio) configuration file
/// </summary>
/// <returns></returns>
[SuppressMessage("", "CA1031")]
private static void ReadHassioConfig()
{
try
Expand All @@ -98,7 +104,7 @@ private static void ReadHassioConfig()
_ = hassAddOnSettings?.AppSource ??
throw new NetDaemonNullReferenceException("AppSource cannot be null");

if (hassAddOnSettings.AppSource.StartsWith("/") || hassAddOnSettings.AppSource[1] == ':')
if (hassAddOnSettings.AppSource.StartsWith("/", true, CultureInfo.InvariantCulture) || hassAddOnSettings.AppSource[1] == ':')
{
// Hard codede path
Environment.SetEnvironmentVariable("NETDAEMON__APPSOURCE", hassAddOnSettings.AppSource);
Expand Down
15 changes: 12 additions & 3 deletions src/DaemonRunner/DaemonRunner/Service/API/WsHandler.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
Expand Down Expand Up @@ -42,6 +43,10 @@ public class ApiWebsocketMiddleware
NetDaemonHost? host = null
)
{
_ = netDaemonSettings ??
throw new NetDaemonArgumentNullException(nameof(netDaemonSettings));
_ = homeAssistantSettings ??
throw new NetDaemonArgumentNullException(nameof(homeAssistantSettings));
_logger = loggerFactory.CreateLogger<ApiWebsocketMiddleware>();
_host = host;
_netdaemonSettings = netDaemonSettings.Value;
Expand All @@ -67,11 +72,15 @@ private async Task NewEvent(ExternalEventBase ev)
LastErrorMessage = n.IsEnabled ? n.RuntimeInfo.LastErrorMessage : null
})
};
await BroadCast(JsonSerializer.Serialize<WsExternalEvent>(eventMessage, _jsonOptions)).ConfigureAwait(false);
await BroadCast(JsonSerializer.Serialize(eventMessage, _jsonOptions)).ConfigureAwait(false);
}
}

[SuppressMessage("", "CA1031")]
public async Task Invoke(HttpContext context)
{
_ = context ??
throw new NetDaemonArgumentNullException(nameof(context));
if (!context.WebSockets.IsWebSocketRequest && context.Request.Path != "/api/ws")
{
await _next.Invoke(context).ConfigureAwait(false);
Expand Down Expand Up @@ -115,7 +124,7 @@ public async Task Invoke(HttpContext context)
})
};

await BroadCast(JsonSerializer.Serialize<WsExternalEvent>(eventMessage, _jsonOptions)).ConfigureAwait(false);
await BroadCast(JsonSerializer.Serialize(eventMessage, _jsonOptions)).ConfigureAwait(false);

break;
case "settings":
Expand Down Expand Up @@ -156,7 +165,7 @@ public async Task Invoke(HttpContext context)
}
if (command.IsEnabled is not null)
{
if (command.IsEnabled ?? false)
if (command.IsEnabled.Value)
{
_host?.CallService("switch", "turn_on", new { entity_id = $"switch.netdaemon_{msg.App.ToSafeHomeAssistantEntityId()}" });
}
Expand Down
9 changes: 2 additions & 7 deletions src/DaemonRunner/DaemonRunner/Service/ApiService.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,23 @@
using System.Reflection;
using JoySoftware.HomeAssistant.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.Daemon;
using NetDaemon.Daemon.Storage;
using NetDaemon.Service;
using Microsoft.Extensions.Options;
using System.IO;
using Microsoft.Extensions.Hosting;
using NetDaemon.Common;
using System;
using System.Net.WebSockets;
using Microsoft.AspNetCore.WebSockets;
using NetDaemon.Service.Api;
using NetDaemon.Common.Configuration;

namespace NetDaemon.Service
{
public class ApiStartup
{
private readonly bool _useAdmin = false;
private readonly bool _useAdmin;

public ApiStartup(IConfiguration configuration)
{
Expand All @@ -42,7 +37,7 @@ public static void ConfigureServices(IServiceCollection services)
Path.Combine(
n.GetRequiredService<IOptions<NetDaemonSettings>>().Value.GetAppSourceDirectory()
, ".storage")));
services.AddTransient<IHttpHandler, NetDaemon.Daemon.HttpHandler>();
services.AddTransient<IHttpHandler, HttpHandler>();
services.AddSingleton<NetDaemonHost>();
services.AddHttpClient();
}
Expand Down
24 changes: 10 additions & 14 deletions src/DaemonRunner/DaemonRunner/Service/App/CodeGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using JoySoftware.HomeAssistant.Client;
Expand Down Expand Up @@ -30,9 +31,6 @@ public static class CodeGenerator
["camera"] = ("Camera", "ICamera"),
["media_player"] = ("MediaPlayer", "IMediaPlayer"),
["automation"] = ("Entity", "IEntity"),
// ["input_boolean"],
// ["remote"],
// ["climate"],
};

public static string? GenerateCode(string nameSpace, IEnumerable<string> entities)
Expand All @@ -41,7 +39,7 @@ public static class CodeGenerator

// Add Usings statements
code = code.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(NetDaemonApp).Namespace!)));
code = code.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(NetDaemon.Common.Fluent.IMediaPlayer).Namespace!)));
code = code.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(Common.Fluent.IMediaPlayer).Namespace!)));

// Add namespace
var namespaceDeclaration = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(nameSpace)).NormalizeWhitespace();
Expand All @@ -53,9 +51,7 @@ public static class CodeGenerator
SyntaxFactory.Token(SyntaxKind.StaticKeyword), SyntaxFactory.Token(SyntaxKind.PartialKeyword));

// Get all available domains, this is used to create the extensionmethods
var domains = GetDomainsFromEntities(entities);

foreach (var domain in domains)
foreach (var domain in GetDomainsFromEntities(entities))
{
if (_FluentApiMapper.ContainsKey(domain))
{
Expand Down Expand Up @@ -85,10 +81,10 @@ public static class CodeGenerator
}}";
var entityClass = CSharpSyntaxTree.ParseText(classDeclaration).GetRoot().ChildNodes().OfType<ClassDeclarationSyntax>().FirstOrDefault()
?? throw new NetDaemonNullReferenceException($"Parse class {nameof(NetDaemonApp)} failed");
foreach (var entity in entities.Where(n => n.StartsWith(domain)))
foreach (var entity in entities.Where(n => n.StartsWith(domain, true, CultureInfo.InvariantCulture)))
{
var (fluent, fluentInterface) = _FluentApiMapper[domain];
var name = entity[(entity.IndexOf(".") + 1)..];
var name = entity[(entity.IndexOf(".", StringComparison.InvariantCultureIgnoreCase) + 1)..];
// Quick check to make sure the name is a valid C# identifier. Should really check to make
// sure it doesn't collide with a reserved keyword as well.
if (!char.IsLetter(name[0]) && (name[0] != '_'))
Expand Down Expand Up @@ -121,7 +117,7 @@ public static class CodeGenerator
code = code.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Linq")));
code = code.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(NetDaemonApp).Namespace!)));
code = code.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(NetDaemonRxApp).Namespace!)));
code = code.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(NetDaemon.Common.Fluent.FluentExpandoObject).Namespace!)));
code = code.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(Common.Fluent.FluentExpandoObject).Namespace!)));

// Add namespace
var namespaceDeclaration = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(nameSpace)).NormalizeWhitespace();
Expand Down Expand Up @@ -183,7 +179,7 @@ public static class CodeGenerator
if (s.Service is null)
continue;

var name = s.Service[(s.Service.IndexOf(".") + 1)..];
var name = s.Service[(s.Service.IndexOf(".", StringComparison.InvariantCultureIgnoreCase) + 1)..];

if (Array.IndexOf(skipServices, name) >= 0)
continue;
Expand Down Expand Up @@ -236,9 +232,9 @@ public static class CodeGenerator
}}";
var entityClass = CSharpSyntaxTree.ParseText(classDeclaration).GetRoot().ChildNodes().OfType<ClassDeclarationSyntax>().FirstOrDefault()
?? throw new NetDaemonNullReferenceException("Failed to parse entity class");
foreach (var entity in entities.Where(n => n.StartsWith(domain)))
foreach (var entity in entities.Where(n => n.StartsWith(domain, StringComparison.InvariantCultureIgnoreCase)))
{
var name = entity[(entity.IndexOf(".") + 1)..];
var name = entity[(entity.IndexOf(".", StringComparison.InvariantCultureIgnoreCase) + 1)..];
// Quick check to make sure the name is a valid C# identifier. Should really check to make
// sure it doesn't collide with a reserved keyword as well.
if (!char.IsLetter(name[0]) && (name[0] != '_'))
Expand All @@ -264,6 +260,6 @@ public static class CodeGenerator
/// </summary>
/// <param name="entities">A list of entities</param>
internal static IEnumerable<string> GetDomainsFromEntities(IEnumerable<string> entities) =>
entities.Select(n => n[0..n.IndexOf(".")]).Distinct();
entities.Select(n => n[0..n.IndexOf(".", StringComparison.InvariantCultureIgnoreCase)]).Distinct();
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.Common;
using NetDaemon.Common.Configuration;
using NetDaemon.Common.Exceptions;
using NetDaemon.Infrastructure.Extensions;

namespace NetDaemon.Service.App
Expand All @@ -15,9 +15,11 @@ public class DaemonAppCompiler : IDaemonAppCompiler
{
private readonly ILogger<DaemonAppCompiler> _logger;

private readonly string? _sourceFolder = null;
private readonly string? _sourceFolder;
public DaemonAppCompiler(ILogger<DaemonAppCompiler> logger, IOptions<NetDaemonSettings> netDaemonSettings)
{
_ = netDaemonSettings ??
throw new NetDaemonArgumentNullException(nameof(netDaemonSettings));
_logger = logger;
NetDaemonSettings = netDaemonSettings;
_sourceFolder = netDaemonSettings.Value.GetAppSourceDirectory();
Expand Down
Loading

0 comments on commit 6a85491

Please sign in to comment.