Skip to content

Commit

Permalink
clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
karimz1 committed Jun 9, 2024
1 parent 02a6e4e commit a97f682
Show file tree
Hide file tree
Showing 10 changed files with 109 additions and 201 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Check warning on line 8 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Non-nullable property 'Command' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 8 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Non-nullable property 'Command' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 8 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Non-nullable property 'Command' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 8 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Non-nullable property 'Command' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 8 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Non-nullable property 'Command' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 8 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Non-nullable property 'Command' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
Expand All @@ -12,4 +12,4 @@ internal class Options

[Option('l', "logFolderPath", Required = true, HelpText = "Path to log folder.")]
public string LogFolderPath { get; set; }

Check warning on line 14 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Non-nullable property 'LogFolderPath' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 14 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Non-nullable property 'LogFolderPath' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

Check warning on line 14 in src/AwsServiceAuthenticator.Cli/ArgumentOptions.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Non-nullable property 'LogFolderPath' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
}
}
8 changes: 4 additions & 4 deletions src/AwsServiceAuthenticator.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
using CommandLine;
using Microsoft.Extensions.DependencyInjection;

ILogger logger = null;
ILogger? logger = null;

try
{
ServiceConfiguration.ConfigureAwsLogging();
ServiceConfiguration.InitializeTraceListeners();
var logFileName = $"refreshTokens-{DateTime.Now:yyyy-MM-dd}.log";

var result = await Parser.Default.ParseArguments<Options>(args)
_ = await Parser.Default.ParseArguments<ArgumentOptions>(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<ILogger>();
var region = options.Region;
Expand Down
43 changes: 28 additions & 15 deletions src/AwsServiceAuthenticator.Cli/ServiceConfiguration.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<ILogger, SerilogLogger>(_ => new SerilogLogger(logger));
serviceCollection.RegisterLogging(logFilePath);
serviceCollection.RegisterCommandsMapping();

serviceCollection.AddSingleton<IAwsAuthenticator, AwsAuthenticator>();
serviceCollection.AddSingleton<ISystemRegion>(_ => new SystemRegion(region));
serviceCollection.AddSingleton<ICommandResolver, CommandResolver>();

// Register commands
serviceCollection.AddTransient<EcrAuthCommand>();
serviceCollection.AddTransient<NuGetAuthCommand>();

return serviceCollection.BuildServiceProvider();
}

public static void ConfigureAwsLogging()
{
AWSConfigs.LoggingConfig.LogTo = LoggingOptions.Console;
Expand All @@ -45,4 +36,26 @@ public static void InitializeTraceListeners()
{
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
}
}

private static IServiceCollection RegisterLogging(this IServiceCollection services, string logFilePath)
{
var logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File(logFilePath)
.CreateLogger();

services.AddSingleton<ILogger, SerilogLogger>(_ => new SerilogLogger(logger));
return services;
}

private static IServiceCollection RegisterCommandsMapping(this IServiceCollection services)
{
services.AddSingleton<ICommandResolver, CommandResolver>();
var commandMappings = CommandConfiguration.GetCommandMappings();

foreach (var command in commandMappings)
services.AddTransient(command.Value);

return services;
}
}
13 changes: 13 additions & 0 deletions src/AwsServiceAuthenticator.Commands/CommandConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace AwsServiceAuthenticator.Commands;

public static class CommandConfiguration
{
public static Dictionary<string, Type> GetCommandMappings()
{
return new Dictionary<string, Type>
{
{ "ecr", typeof(EcrAuthCommand) },
{ "nuget", typeof(NuGetAuthCommand) }
};
}
}
25 changes: 6 additions & 19 deletions src/AwsServiceAuthenticator.Commands/CommandResolver.cs
Original file line number Diff line number Diff line change
@@ -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<string, Type> _commands;

public CommandResolver(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_commands = new Dictionary<string, Type>
{
{ "ecr", typeof(EcrAuthCommand) },
{ "nuget", typeof(NuGetAuthCommand) }
};
}
private readonly Dictionary<string, Type> _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));
}
}
34 changes: 7 additions & 27 deletions src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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(':');
Expand All @@ -41,18 +31,8 @@ public async Task ExecuteAsync()
var process = Process.Start(startInfo);
await process.WaitForExitAsync();

Check warning on line 32 in src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 32 in src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 32 in src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Dereference of a possibly null reference.

Check warning on line 32 in src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Dereference of a possibly null reference.

Check warning on line 32 in src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Dereference of a possibly null reference.

Check warning on line 32 in src/AwsServiceAuthenticator.Commands/EcrAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Dereference of a possibly null reference.

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()}");
}
}
53 changes: 13 additions & 40 deletions src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -63,15 +46,9 @@ private async Task AddNuGetSource(string domainName, string domainOwner, string
var process = Process.Start(addSourceInfo);
await process.WaitForExitAsync();

Check warning on line 47 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 47 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 47 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Dereference of a possibly null reference.

Check warning on line 47 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Dereference of a possibly null reference.

Check warning on line 47 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Dereference of a possibly null reference.

Check warning on line 47 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Dereference of a possibly null reference.

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)
Expand All @@ -88,12 +65,8 @@ private async Task RemoveNuGetSource(string repoName)
var removeProcess = Process.Start(removeSourceInfo);
await removeProcess.WaitForExitAsync();

Check warning on line 66 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 66 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 66 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Dereference of a possibly null reference.

Check warning on line 66 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (windows-latest)

Dereference of a possibly null reference.

Check warning on line 66 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Dereference of a possibly null reference.

Check warning on line 66 in src/AwsServiceAuthenticator.Commands/NuGetAuthCommand.cs

View workflow job for this annotation

GitHub Actions / build (macos-latest)

Dereference of a possibly null reference.
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()}");
}
}
2 changes: 1 addition & 1 deletion src/AwsServiceAuthenticator.Core/Models/SystemRegion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Loading

0 comments on commit a97f682

Please sign in to comment.