Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement API for configurable cmdlet behavior and mapping #10

Merged
merged 2 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Kysect.PowerShellRunner.Abstractions.Objects;
using Kysect.PowerShellRunner.Abstractions.Variables;

namespace Kysect.PowerShellRunner.Abstractions.Cmdlets;

public interface IPowerShellCmdletExecutor
{
IReadOnlyCollection<IPowerShellObject> Execute(IPowerShellCmdlet cmdlet);
PowerShellVariable<IPowerShellObject> InitializeVariable(string variableName, IPowerShellCmdlet cmdlet);

IReadOnlyCollection<T> Execute<T>(IPowerShellCmdlet<T> cmdlet) where T : notnull;
PowerShellVariable<T> InitializeVariable<T>(string variableName, IPowerShellCmdlet<T> cmdlet) where T : notnull;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Kysect.PowerShellRunner.Abstractions.Objects;

namespace Kysect.PowerShellRunner.Abstractions.Cmdlets;

public interface IPowerShellObjectMapper
{
T Map<T>(IPowerShellObject powerShellObject) where T : notnull;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Kysect.CommonLib.BaseTypes.Extensions;
using Kysect.PowerShellRunner.Abstractions.Variables;
using System.Text;

namespace Kysect.PowerShellRunner.Abstractions.Queries;

Expand Down Expand Up @@ -60,4 +61,18 @@ public PowerShellQuery WithRedirection(string path)
{
return this with { RedirectionPath = path };
}

public readonly string Format()
{
var sb = new StringBuilder();

if (ResultVariable is not null)
sb.Append($"{ResultVariable.AsReference()} = ");

sb.Append(Query);
if (!string.IsNullOrEmpty(RedirectionPath))
sb.Append($" *> \"{RedirectionPath}\"");

return sb.ToString();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Kysect.CommonLib.BaseTypes.Extensions;
using Kysect.CommonLib.DependencyInjection.Logging;
using Kysect.PowerShellRunner.Abstractions.Accessors;
using Kysect.PowerShellRunner.Abstractions.Cmdlets;
using Kysect.PowerShellRunner.Accessors;
using Kysect.PowerShellRunner.Cmdlets;
using Microsoft.Extensions.DependencyInjection;

namespace Kysect.PowerShellRunner.Configuration;
Expand Down Expand Up @@ -29,6 +31,11 @@ public static IServiceCollection AddPowerShellAccessor(this IServiceCollection s
return serviceCollection.AddSingleton(GetPowerShellAccessor);
}

public static IServiceCollection AddPowerShellCmdletExecutor(this IServiceCollection serviceCollection)
{
return serviceCollection.AddSingleton<IPowerShellCmdletExecutor, PowerShellCmdletExecutor>();
}

private static IPowerShellAccessor GetPowerShellAccessor(IServiceProvider serviceProvider)
{
IPowerShellLogger powerShellLogger = serviceProvider.GetRequiredService<IPowerShellLogger>();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using FluentAssertions;
using Kysect.PowerShellRunner.Abstractions.Variables;
using Kysect.PowerShellRunner.Cmdlets;
using Kysect.PowerShellRunner.CustomCmdlets;
using Kysect.PowerShellRunner.Mapping;
using Kysect.PowerShellRunner.Tests.Mocks;
using NUnit.Framework;

namespace Kysect.PowerShellRunner.Tests;

public class PowerShellCmdletExecutorTests
{
[Test]
public void ExecuteAndSetTo_NonGenericImplementation_FinishWithoutError()
{
string expectedResult = @"C:\\Folder";

using var testPowerShellAccessor = new FakePowerShellAccessor();
var powerShellCmdletExecutor = new PowerShellCmdletExecutor(testPowerShellAccessor, PowerShellObjectMapper.Instance);
testPowerShellAccessor.SetSuccessResult(new GetLocationCmdletWrapperResult(expectedResult));

PowerShellVariable<GetLocationCmdletWrapperResult> result = powerShellCmdletExecutor.InitializeVariable("$result", new GetLocationCmdlet());

GetLocationCmdletWrapperResult resultObject = result.Values.Single();
resultObject.Path.Should().NotBeNull();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,14 @@ namespace Kysect.PowerShellRunner.Tests;

public class PowerShellQueryFormatterTests
{
private readonly PowerShellQueryFormatter _sut;

public PowerShellQueryFormatterTests()
{
_sut = new PowerShellQueryFormatter();
}

[Test]
public void Format_QueryWithCmdletName_ReturnCorrectQuery()
{
string expectedValue = "Get-Value";
var query = new PowerShellQuery(expectedValue);

string result = _sut.Format(query);
string result = query.Format();

Assert.That(result, Is.EqualTo(expectedValue));
}
Expand All @@ -31,7 +25,7 @@ public void Format_WithRedirection_ReturnCorrectQuery()
var expectedValue = "GetValue *> \"Log/file.log\"";
var query = new PowerShellQuery("GetValue").WithRedirection("Log/file.log");

string result = _sut.Format(query);
string result = query.Format();

Assert.That(result, Is.EqualTo(expectedValue));
}
Expand All @@ -44,7 +38,7 @@ public void Format_ResultVariableSet_ReturnCorrectQuery()
var variable = new PowerShellVariable("$variable_name");

query = query with { ResultVariable = variable };
string result = _sut.Format(query);
string result = query.Format();

Assert.That(result, Is.EqualTo(expectedValue));
}
Expand Down
1 change: 1 addition & 0 deletions Sources/Kysect.PowerShellRunner.sln
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{1D69C86F-577E-4246-B9E7-B7D2C3F6E0A3}"
ProjectSection(SolutionItems) = preProject
Directory.Build.props = Directory.Build.props
Directory.Packages.props = Directory.Packages.props
EndProjectSection
EndProject
Global
Expand Down
30 changes: 10 additions & 20 deletions Sources/Kysect.PowerShellRunner/Accessors/PowerShellAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,23 @@

namespace Kysect.PowerShellRunner.Accessors;

public class PowerShellAccessor : IPowerShellAccessor
public class PowerShellAccessor(PowerShell powerShellInstance) : IPowerShellAccessor
{
private readonly PowerShell _powerShellInstance;
private readonly PowerShellQueryFormatter _executionStringFormatter;

public PowerShellAccessor(PowerShell powerShellInstance)
{
_powerShellInstance = powerShellInstance;

_executionStringFormatter = new PowerShellQueryFormatter();
}

public IPowerShellExecutionResult Execute(PowerShellQuery query)
{
string fullCommand = _executionStringFormatter.Format(query);
string fullCommand = query.Format();

lock (_powerShellInstance)
lock (powerShellInstance)
{
_powerShellInstance.AddScript(fullCommand);
Collection<PSObject> result = _powerShellInstance.Invoke();
powerShellInstance.AddScript(fullCommand);
Collection<PSObject> result = powerShellInstance.Invoke();

IPowerShellExecutionResult methodResult = _powerShellInstance.HadErrors
IPowerShellExecutionResult methodResult = powerShellInstance.HadErrors
? CreateFailedResult(result)
: CreateSuccessResult(result);

_powerShellInstance.Streams.ClearStreams();
_powerShellInstance.Commands.Clear();
powerShellInstance.Streams.ClearStreams();
powerShellInstance.Commands.Clear();
return methodResult;
}
}
Expand All @@ -50,7 +40,7 @@ private PowerShellSuccessExecutionResult CreateSuccessResult(Collection<PSObject

private PowerShellFailedExecutionResult CreateFailedResult(Collection<PSObject> result)
{
var errors = _powerShellInstance.Streams.Error.ToList();
var errors = powerShellInstance.Streams.Error.ToList();
var errorMessages = errors.Select(e => e.ToString()).ToList();

var failedPowerShellExecutionResult = new PowerShellFailedExecutionResult(errorMessages, result
Expand All @@ -63,7 +53,7 @@ private PowerShellFailedExecutionResult CreateFailedResult(Collection<PSObject>

protected virtual void Dispose(bool disposing)
{
_powerShellInstance.Dispose();
powerShellInstance.Dispose();
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ public class PowerShellAccessorFactory : IPowerShellAccessorFactory
{
public IPowerShellAccessor Create()
{
#pragma warning disable CA2000 // Dispose objects before losing scope
return new PowerShellAccessor(System.Management.Automation.PowerShell.Create());
#pragma warning restore CA2000 // Dispose objects before losing scope
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,57 +9,46 @@

namespace Kysect.PowerShellRunner.Accessors;

public class PowerShellAccessorLoggingDecorator : IPowerShellAccessor
public class PowerShellAccessorLoggingDecorator(IPowerShellAccessor innerImplementation, ILogger logger)
: IPowerShellAccessor
{
private readonly IPowerShellAccessor _innerImplementation;
private readonly ILogger _logger;
private readonly PowerShellQueryFormatter _executionStringFormatter;

public PowerShellAccessorLoggingDecorator(IPowerShellAccessor innerImplementation, ILogger logger)
{
_innerImplementation = innerImplementation;
_logger = logger;

_executionStringFormatter = new PowerShellQueryFormatter();
}

public IPowerShellExecutionResult Execute(PowerShellQuery query)
{
if (query.ContainsSensitiveInfo)
{
_logger.LogDebug("Execute PowerShell command with sensitive data. Query will not be logged.");
logger.LogDebug("Execute PowerShell command with sensitive data. Query will not be logged.");
}
else
{
string executableQuery = _executionStringFormatter.Format(query);
_logger.LogDebug($"Execute PowerShell command: {executableQuery}");
string executableQuery = query.Format();
logger.LogDebug($"Execute PowerShell command: {executableQuery}");
}

IPowerShellExecutionResult result = _innerImplementation.Execute(query);
IPowerShellExecutionResult result = innerImplementation.Execute(query);
switch (result)
{
case PowerShellFailedExecutionResult failedPowerShellExecutionResult:
_logger.LogError("PS command executed failed.");
logger.LogError("PS command executed failed.");
if (failedPowerShellExecutionResult.Errors.Any())
{
_logger.LogError("Errors:");
logger.LogError("Errors:");
foreach (string error in failedPowerShellExecutionResult.Errors)
_logger.LogTabError(1, error);
logger.LogTabError(1, error);
}

if (failedPowerShellExecutionResult.OtherMessages.Any())
{
_logger.LogError("Other messages:");
logger.LogError("Other messages:");
foreach (string otherMessage in failedPowerShellExecutionResult.OtherMessages)
_logger.LogTabError(1, otherMessage);
logger.LogTabError(1, otherMessage);
}

break;

case PowerShellSuccessExecutionResult successPowerShellExecutionResult:
_logger.LogDebug("PS command executed successfully.");
logger.LogDebug("PS command executed successfully.");
foreach (IPowerShellObject powerShellObject in successPowerShellExecutionResult.Output)
_logger.LogPowerShellObject(powerShellObject);
logger.LogPowerShellObject(powerShellObject);
break;

default:
Expand All @@ -71,7 +60,7 @@ public IPowerShellExecutionResult Execute(PowerShellQuery query)

protected virtual void Dispose(bool disposing)
{
_innerImplementation.Dispose();
innerImplementation.Dispose();
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Kysect.PowerShellRunner.Abstractions.Accessors;
using Kysect.PowerShellRunner.Abstractions.Cmdlets;
using Kysect.PowerShellRunner.Abstractions.Objects;
using Kysect.PowerShellRunner.Abstractions.Queries;
using Kysect.PowerShellRunner.Abstractions.Variables;
using Kysect.PowerShellRunner.Executions;
using Kysect.PowerShellRunner.QueryBuilding;

namespace Kysect.PowerShellRunner.Cmdlets;

public class PowerShellCmdletExecutor(IPowerShellAccessor accessor, IPowerShellObjectMapper powerShellObjectMapper)
: IPowerShellCmdletExecutor
{
public IReadOnlyCollection<IPowerShellObject> Execute(IPowerShellCmdlet cmdlet)
{
PowerShellQuery powerShellQuery = cmdlet.BuildFromCmdlet();

return accessor.ExecuteAndGet(powerShellQuery).ToList();
}

public PowerShellVariable<IPowerShellObject> InitializeVariable(string variableName, IPowerShellCmdlet cmdlet)
{
var powerShellVariable = new PowerShellVariable(variableName);
PowerShellQuery powerShellQuery = cmdlet.BuildFromCmdlet();
return new PowerShellVariableInitializer(accessor, powerShellVariable, powerShellObjectMapper).With(powerShellQuery);
}

public IReadOnlyCollection<T> Execute<T>(IPowerShellCmdlet<T> cmdlet) where T : notnull
{
PowerShellQuery powerShellQuery = cmdlet.BuildFromCmdlet();

return accessor.ExecuteAndGet(powerShellQuery)
.Select(powerShellObjectMapper.Map<T>)
.ToList();
}

public PowerShellVariable<T> InitializeVariable<T>(string variableName, IPowerShellCmdlet<T> cmdlet) where T : notnull
{
var powerShellVariable = new PowerShellVariable(variableName);
PowerShellQuery powerShellQuery = cmdlet.BuildFromCmdlet();
return new PowerShellVariableInitializer(accessor, powerShellVariable, powerShellObjectMapper).With<T>(powerShellQuery);
}
}
Loading