From a97f682bc4c198b0799058fd18e7d8c71ab6cd1a Mon Sep 17 00:00:00 2001 From: karimz1 Date: Sun, 9 Jun 2024 18:48:14 +0200 Subject: [PATCH] clean code --- .../{Options.cs => ArgumentOptions.cs} | 4 +- src/AwsServiceAuthenticator.Cli/Program.cs | 8 +- .../ServiceConfiguration.cs | 43 ++++--- .../CommandConfiguration.cs | 13 ++ .../CommandResolver.cs | 25 +--- .../EcrAuthCommand.cs | 34 ++---- .../NuGetAuthCommand.cs | 53 ++------ .../Models/SystemRegion.cs | 2 +- .../Services/AwsAuthenticator.cs | 113 +++++------------- .../Services/SerilogLogger.cs | 15 +-- 10 files changed, 109 insertions(+), 201 deletions(-) rename src/AwsServiceAuthenticator.Cli/{Options.cs => ArgumentOptions.cs} (93%) create mode 100644 src/AwsServiceAuthenticator.Commands/CommandConfiguration.cs diff --git a/src/AwsServiceAuthenticator.Cli/Options.cs b/src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs similarity index 93% rename from src/AwsServiceAuthenticator.Cli/Options.cs rename to src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs index 3efbf67..4e6d7fd 100644 --- a/src/AwsServiceAuthenticator.Cli/Options.cs +++ b/src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs @@ -2,7 +2,7 @@ namespace AwsServiceAuthenticator.Cli; -internal class Options +internal class ArgumentOptions { [Option('c', "command", Required = true, HelpText = "Command to execute (ecr or nuget).")] public string Command { get; set; } @@ -12,4 +12,4 @@ internal class Options [Option('l', "logFolderPath", Required = true, HelpText = "Path to log folder.")] public string LogFolderPath { get; set; } -} \ No newline at end of file +} diff --git a/src/AwsServiceAuthenticator.Cli/Program.cs b/src/AwsServiceAuthenticator.Cli/Program.cs index 8af08f1..2628834 100644 --- a/src/AwsServiceAuthenticator.Cli/Program.cs +++ b/src/AwsServiceAuthenticator.Cli/Program.cs @@ -3,7 +3,7 @@ using CommandLine; using Microsoft.Extensions.DependencyInjection; -ILogger logger = null; +ILogger? logger = null; try { @@ -11,11 +11,11 @@ ServiceConfiguration.InitializeTraceListeners(); var logFileName = $"refreshTokens-{DateTime.Now:yyyy-MM-dd}.log"; - var result = await Parser.Default.ParseArguments(args) + _ = await Parser.Default.ParseArguments(args) .WithParsedAsync(async options => { - logFileName = Path.Combine(options.LogFolderPath, logFileName); - var serviceProvider = ServiceConfiguration.ConfigureServices(options.Region, logFileName); + var logFilePath = Path.Combine(options.LogFolderPath, logFileName); + var serviceProvider = ServiceConfiguration.ConfigureServices(options.Region, logFilePath); logger = serviceProvider.GetRequiredService(); var region = options.Region; diff --git a/src/AwsServiceAuthenticator.Cli/ServiceConfiguration.cs b/src/AwsServiceAuthenticator.Cli/ServiceConfiguration.cs index 75339a4..d014b5c 100644 --- a/src/AwsServiceAuthenticator.Cli/ServiceConfiguration.cs +++ b/src/AwsServiceAuthenticator.Cli/ServiceConfiguration.cs @@ -1,7 +1,6 @@ using System.Diagnostics; using Amazon; using AwsServiceAuthenticator.Commands; -using AwsServiceAuthenticator.Commands.Logic; using AwsServiceAuthenticator.Core.Interfaces; using AwsServiceAuthenticator.Core.Models; using AwsServiceAuthenticator.Infrastructure.Services; @@ -13,26 +12,18 @@ namespace AwsServiceAuthenticator.Cli; public static class ServiceConfiguration { - public static ServiceProvider ConfigureServices(string region, string logPath) + public static ServiceProvider ConfigureServices(string region, string logFilePath) { - var logger = new LoggerConfiguration() - .WriteTo.Console() - .WriteTo.File(logPath) - .CreateLogger(); - var serviceCollection = new ServiceCollection(); - serviceCollection.AddSingleton(_ => new SerilogLogger(logger)); + serviceCollection.RegisterLogging(logFilePath); + serviceCollection.RegisterCommandsMapping(); + serviceCollection.AddSingleton(); serviceCollection.AddSingleton(_ => new SystemRegion(region)); - serviceCollection.AddSingleton(); - - // Register commands - serviceCollection.AddTransient(); - serviceCollection.AddTransient(); return serviceCollection.BuildServiceProvider(); } - + public static void ConfigureAwsLogging() { AWSConfigs.LoggingConfig.LogTo = LoggingOptions.Console; @@ -45,4 +36,26 @@ public static void InitializeTraceListeners() { Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); } -} \ No newline at end of file + + private static IServiceCollection RegisterLogging(this IServiceCollection services, string logFilePath) + { + var logger = new LoggerConfiguration() + .WriteTo.Console() + .WriteTo.File(logFilePath) + .CreateLogger(); + + services.AddSingleton(_ => new SerilogLogger(logger)); + return services; + } + + private static IServiceCollection RegisterCommandsMapping(this IServiceCollection services) + { + services.AddSingleton(); + var commandMappings = CommandConfiguration.GetCommandMappings(); + + foreach (var command in commandMappings) + services.AddTransient(command.Value); + + return services; + } +} diff --git a/src/AwsServiceAuthenticator.Commands/CommandConfiguration.cs b/src/AwsServiceAuthenticator.Commands/CommandConfiguration.cs new file mode 100644 index 0000000..be71c01 --- /dev/null +++ b/src/AwsServiceAuthenticator.Commands/CommandConfiguration.cs @@ -0,0 +1,13 @@ +namespace AwsServiceAuthenticator.Commands; + +public static class CommandConfiguration +{ + public static Dictionary GetCommandMappings() + { + return new Dictionary + { + { "ecr", typeof(EcrAuthCommand) }, + { "nuget", typeof(NuGetAuthCommand) } + }; + } +} diff --git a/src/AwsServiceAuthenticator.Commands/CommandResolver.cs b/src/AwsServiceAuthenticator.Commands/CommandResolver.cs index e17acc2..0febb04 100644 --- a/src/AwsServiceAuthenticator.Commands/CommandResolver.cs +++ b/src/AwsServiceAuthenticator.Commands/CommandResolver.cs @@ -1,29 +1,16 @@ using AwsServiceAuthenticator.Core.Interfaces; -namespace AwsServiceAuthenticator.Commands.Logic; +namespace AwsServiceAuthenticator.Commands; -public class CommandResolver : ICommandResolver +public class CommandResolver(IServiceProvider serviceProvider) : ICommandResolver { - private readonly IServiceProvider _serviceProvider; - private readonly Dictionary _commands; - - public CommandResolver(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - _commands = new Dictionary - { - { "ecr", typeof(EcrAuthCommand) }, - { "nuget", typeof(NuGetAuthCommand) } - }; - } + private readonly Dictionary _commands = CommandConfiguration.GetCommandMappings(); - ICommand? ICommandResolver.ResolveCommand(string commandName) + public ICommand? ResolveCommand(string commandName) { if (_commands.TryGetValue(commandName, out var commandType)) - { - return _serviceProvider.GetService(commandType) as ICommand; - } + return serviceProvider.GetService(commandType) as ICommand; - throw new ArgumentException("This argument does not exists", nameof(commandName)); + throw new ArgumentException("This argument does not exist", nameof(commandName)); } } \ No newline at end of file diff --git a/src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs b/src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs index 10ca373..d660de5 100644 --- a/src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs +++ b/src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs @@ -5,24 +5,14 @@ namespace AwsServiceAuthenticator.Commands; -public class EcrAuthCommand : ICommand +public class EcrAuthCommand(ILogger logger, ISystemRegion systemRegion) : ICommand { - private readonly ILogger _logger; - private readonly string _systemRegion; - - public EcrAuthCommand(ILogger logger, ISystemRegion systemRegion) - { - _logger = logger; - _systemRegion = systemRegion.Region; - } + private readonly string _systemRegion = systemRegion.Region; public async Task ExecuteAsync() { - try - { - var ecrClient = new AmazonECRClient(RegionEndpoint.GetBySystemName(_systemRegion)); - var response = - await ecrClient.GetAuthorizationTokenAsync(new Amazon.ECR.Model.GetAuthorizationTokenRequest()); + using var client = new AmazonECRClient(RegionEndpoint.GetBySystemName(_systemRegion)); + var response = await client.GetAuthorizationTokenAsync(new Amazon.ECR.Model.GetAuthorizationTokenRequest()); var authData = response.AuthorizationData[0]; var token = Convert.FromBase64String(authData.AuthorizationToken); var credentials = System.Text.Encoding.UTF8.GetString(token).Split(':'); @@ -41,18 +31,8 @@ public async Task ExecuteAsync() var process = Process.Start(startInfo); await process.WaitForExitAsync(); - if (process.ExitCode == 0) - { - _logger.LogInformation("ECR authentication successful."); - } - else - { - _logger.LogInformation($"ECR authentication failed: {process.StandardError.ReadToEnd()}"); - } - } - catch (Exception ex) - { - _logger.LogInformation($"Error: {ex.Message}"); - } + logger.LogInformation(process.ExitCode == 0 + ? "ECR authentication successful." + : $"ECR authentication failed: {await process.StandardError.ReadToEndAsync()}"); } } \ No newline at end of file diff --git a/src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs b/src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs index 2bd28b3..e614fc3 100644 --- a/src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs +++ b/src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs @@ -6,50 +6,33 @@ namespace AwsServiceAuthenticator.Commands; -public class NuGetAuthCommand : ICommand +public class NuGetAuthCommand(IAwsAuthenticator awsAuthenticator, ILogger logger, ISystemRegion region) : ICommand { - private readonly IAwsAuthenticator _awsAuthenticator; - private readonly ILogger _logger; - private readonly string _region; - - public NuGetAuthCommand(IAwsAuthenticator awsAuthenticator, ILogger logger, ISystemRegion region) - { - _awsAuthenticator = awsAuthenticator; - _logger = logger; - _region = region.Region; - } + private readonly string _region = region.Region; public async Task ExecuteAsync() { - try - { - string domainOwner = await _awsAuthenticator.GetDomainOwnerIdAsync(); - string domainName = await _awsAuthenticator.GetDomainNameAsync(); - string token = await _awsAuthenticator.GetAuthorizationTokenAsync(domainName, domainOwner); + var domainOwner = await awsAuthenticator.GetDomainOwnerIdAsync(); + var domainName = await awsAuthenticator.GetDomainNameAsync(); + var token = await awsAuthenticator.GetAuthorizationTokenAsync(domainName, domainOwner); - var client = new AmazonCodeArtifactClient(RegionEndpoint.GetBySystemName(_region)); + using var client = new AmazonCodeArtifactClient(RegionEndpoint.GetBySystemName(_region)); var reposResponse = await client.ListRepositoriesInDomainAsync(new ListRepositoriesInDomainRequest { Domain = domainName, DomainOwner = domainOwner }); - foreach (var repo in reposResponse.Repositories) + foreach (var repoName in reposResponse.Repositories.Select(repo => repo.Name)) { - string repoName = repo.Name; await RemoveNuGetSource(repoName); await AddNuGetSource(domainName, domainOwner, repoName, token); } - } - catch (Exception ex) - { - _logger.LogInformation($"Error: {ex.Message}"); - } } private async Task AddNuGetSource(string domainName, string domainOwner, string repoName, string token) { - string nugetSource = $"https://{domainName}-{domainOwner}.d.codeartifact.{_region}.amazonaws.com/nuget/{repoName}/v3/index.json"; + var nugetSource = $"https://{domainName}-{domainOwner}.d.codeartifact.{_region}.amazonaws.com/nuget/{repoName}/v3/index.json"; var addSourceInfo = new ProcessStartInfo { @@ -63,15 +46,9 @@ private async Task AddNuGetSource(string domainName, string domainOwner, string var process = Process.Start(addSourceInfo); await process.WaitForExitAsync(); - if (process.ExitCode == 0) - { - _logger.LogInformation($"NuGet authentication for repository {repoName} successful."); - } - else - { - _logger.LogInformation( - $"NuGet authentication for repository {repoName} failed: {process.StandardError.ReadToEnd()}"); - } + logger.LogInformation(process.ExitCode == 0 + ? $"NuGet authentication for repository {repoName} successful." + : $"NuGet authentication for repository {repoName} failed: {await process.StandardError.ReadToEndAsync()}"); } private async Task RemoveNuGetSource(string repoName) @@ -88,12 +65,8 @@ private async Task RemoveNuGetSource(string repoName) var removeProcess = Process.Start(removeSourceInfo); await removeProcess.WaitForExitAsync(); if (removeProcess.ExitCode == 0) - { - _logger.LogInformation($"Removed existing NuGet source: {repoName}"); - } + logger.LogInformation($"Removed existing NuGet source: {repoName}"); else - { - _logger.LogError($"Failed to remove existing NuGet source: {repoName}. Error: {removeProcess.StandardError.ReadToEnd()}"); - } + logger.LogError($"Failed to remove existing NuGet source: {repoName}. Error: {await removeProcess.StandardError.ReadToEndAsync()}"); } } \ No newline at end of file diff --git a/src/AwsServiceAuthenticator.Core/Models/SystemRegion.cs b/src/AwsServiceAuthenticator.Core/Models/SystemRegion.cs index 56ca574..c5880c0 100644 --- a/src/AwsServiceAuthenticator.Core/Models/SystemRegion.cs +++ b/src/AwsServiceAuthenticator.Core/Models/SystemRegion.cs @@ -4,7 +4,7 @@ namespace AwsServiceAuthenticator.Core.Models; public record SystemRegion : ISystemRegion { - public string Region { get; init; } + public string Region { get; } public SystemRegion(string region) { diff --git a/src/AwsServiceAuthenticator.Infrastructure/Services/AwsAuthenticator.cs b/src/AwsServiceAuthenticator.Infrastructure/Services/AwsAuthenticator.cs index cb3dc30..c8b03a8 100644 --- a/src/AwsServiceAuthenticator.Infrastructure/Services/AwsAuthenticator.cs +++ b/src/AwsServiceAuthenticator.Infrastructure/Services/AwsAuthenticator.cs @@ -1,107 +1,56 @@ using Amazon; using Amazon.CodeArtifact; using Amazon.CodeArtifact.Model; -using Amazon.Runtime; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using AwsServiceAuthenticator.Core.Interfaces; namespace AwsServiceAuthenticator.Infrastructure.Services; -public class AwsAuthenticator : IAwsAuthenticator +public class AwsAuthenticator(ILogger logger, ISystemRegion systemName) : IAwsAuthenticator { - private readonly ILogger _logger; - private readonly string _regionSystemName; + private readonly string _regionSystemName = systemName.Region; - public AwsAuthenticator(ILogger logger, ISystemRegion systemName) - { - _logger = logger; - _regionSystemName = systemName.Region; - } - public async Task GetDomainOwnerIdAsync() { - try + var config = new AmazonSecurityTokenServiceConfig { - var config = new AmazonSecurityTokenServiceConfig - { - Timeout = TimeSpan.FromSeconds(30), - RegionEndpoint = RegionEndpoint.GetBySystemName(_regionSystemName) - }; - var stsClient = new AmazonSecurityTokenServiceClient(config); + Timeout = TimeSpan.FromSeconds(30), + RegionEndpoint = RegionEndpoint.GetBySystemName(_regionSystemName) + }; + + using var client = new AmazonSecurityTokenServiceClient(config); - _logger.LogInformation("Attempting to get caller identity..."); - var response = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest()); - _logger.LogInformation($"Caller identity retrieved: {response.Account}"); - return response.Account; - } - catch (AmazonServiceException ex) - { - _logger.LogInformation($"Amazon service exception: {ex.Message}"); - _logger.LogInformation($"Stack trace: {ex.StackTrace}"); - throw; - } - catch (Exception ex) - { - _logger.LogInformation($"Exception: {ex.Message}"); - _logger.LogInformation($"Stack trace: {ex.StackTrace}"); - throw; - } + logger.LogInformation("Attempting to get caller identity..."); + var response = await client.GetCallerIdentityAsync(new GetCallerIdentityRequest()); + logger.LogInformation($"Caller identity retrieved: {response.Account}"); + return response.Account; } public async Task GetDomainNameAsync() { - try - { - using var client = new AmazonCodeArtifactClient(RegionEndpoint.GetBySystemName(_regionSystemName)); - _logger.LogInformation("Attempting to list CodeArtifact domains..."); - var response = await client.ListDomainsAsync(new ListDomainsRequest()); - if (response.Domains.Count > 0) - { - _logger.LogInformation($"Domain found: {response.Domains[0].Name}"); - return response.Domains[0].Name; - } - throw new Exception("No CodeArtifact domains found."); - } - catch (AmazonServiceException ex) - { - _logger.LogInformation($"Amazon service exception: {ex.Message}"); - _logger.LogInformation($"Stack trace: {ex.StackTrace}"); - throw; - } - catch (Exception ex) - { - _logger.LogInformation($"Exception: {ex.Message}"); - _logger.LogInformation($"Stack trace: {ex.StackTrace}"); - throw; - } + using var client = new AmazonCodeArtifactClient(RegionEndpoint.GetBySystemName(_regionSystemName)); + logger.LogInformation("Attempting to list CodeArtifact domains..."); + var response = await client.ListDomainsAsync(new ListDomainsRequest()); + + if (response.Domains.Count <= 0) throw new Exception("No CodeArtifact domains found."); + + logger.LogInformation($"Domain found: {response.Domains[0].Name}"); + return response.Domains[0].Name; + } public async Task GetAuthorizationTokenAsync(string domainName, string domainOwner) { - try - { - using var client = new AmazonCodeArtifactClient(RegionEndpoint.GetBySystemName(_regionSystemName)); - _logger.LogInformation($"Attempting to get authorization token for domain: {domainName}, owner: {domainOwner}..."); - var response = await client.GetAuthorizationTokenAsync(new GetAuthorizationTokenRequest - { - Domain = domainName, - DomainOwner = domainOwner - }); - _logger.LogInformation("Authorization token retrieved."); - return response.AuthorizationToken; - } - catch (AmazonServiceException ex) - { - _logger.LogInformation($"Amazon service exception: {ex.Message}"); - _logger.LogInformation($"Stack trace: {ex.StackTrace}"); - throw; - } - catch (Exception ex) - { - _logger.LogInformation($"Exception: {ex.Message}"); - _logger.LogInformation($"Stack trace: {ex.StackTrace}"); - throw; - } + using var client = new AmazonCodeArtifactClient(RegionEndpoint.GetBySystemName(_regionSystemName)); + logger.LogInformation( + $"Attempting to get authorization token for domain: {domainName}, owner: {domainOwner}..."); + var response = await client.GetAuthorizationTokenAsync(new GetAuthorizationTokenRequest + { + Domain = domainName, + DomainOwner = domainOwner + }); + logger.LogInformation("Authorization token retrieved."); + return response.AuthorizationToken; } } \ No newline at end of file diff --git a/src/AwsServiceAuthenticator.Infrastructure/Services/SerilogLogger.cs b/src/AwsServiceAuthenticator.Infrastructure/Services/SerilogLogger.cs index 2ba2709..5d68910 100644 --- a/src/AwsServiceAuthenticator.Infrastructure/Services/SerilogLogger.cs +++ b/src/AwsServiceAuthenticator.Infrastructure/Services/SerilogLogger.cs @@ -2,27 +2,20 @@ namespace AwsServiceAuthenticator.Infrastructure.Services; -public class SerilogLogger : Interfaces_ILogger +public class SerilogLogger(Serilog.ILogger logger) : Interfaces_ILogger { - private readonly Serilog.ILogger _logger; - - public SerilogLogger(Serilog.ILogger logger) - { - _logger = logger; - } - public void LogInformation(string message) { - _logger.Information(message); + logger.Information(message); } public void LogError(string message) { - _logger.Error(message); + logger.Error(message); } public void LogError(string message, Exception exception) { - _logger.Error(exception, message); + logger.Error(exception, message); } } \ No newline at end of file