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

Replace mono with .NET 8 support #120

Open
wants to merge 3 commits into
base: release-1.7
Choose a base branch
from
Open
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
111 changes: 2 additions & 109 deletions MedallionShell.Tests/CommandLineSyntaxTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class CommandLineSyntaxTest
[Test]
public void TestArgumentValidation([Values] bool isWindowsSyntax)
{
var syntax = isWindowsSyntax ? new WindowsCommandLineSyntax() : new MonoUnixCommandLineSyntax().As<CommandLineSyntax>();
var syntax = new WindowsCommandLineSyntax().As<CommandLineSyntax>();
Assert.Throws<ArgumentNullException>(() => syntax.CreateArgumentString(null!));
Assert.Throws<ArgumentException>(() => syntax.CreateArgumentString(["a", null!, "b"]));
}
Expand All @@ -29,7 +29,7 @@ public void TestArgumentValidation([Values] bool isWindowsSyntax)
[TestCase("\r", "\n", "\r\n")]
[TestCase("", "\"", "\\", "")]
[TestCase("abc", "a\\b", "a\\ b\"")]
// these chars are treated specially on mono unix
// these chars are treated specially on mono unix, so keeping.
Copy link
Author

@Bartleby2718 Bartleby2718 May 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whenever I wasn't sure what to do about Mono-related comments, I either deleted it or modified it so that it shows up in the diff.

[TestCase("`,\\`", "`", "$ $", "$", "\\", "\\$\r\n")]
// cases from https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments?view=vs-2019
[TestCase("abc", "d", "e")]
Expand All @@ -49,7 +49,6 @@ private void TestArgumentsRoundTripHelper(string[] arguments)
{
this.TestRealRoundTrip(arguments);
this.TestAgainstNetCoreArgumentParser(arguments);
this.TestAgainstMonoUnixArgumentParser(arguments);
}

private void TestRealRoundTrip(string[] arguments)
Expand All @@ -67,13 +66,6 @@ private void TestAgainstNetCoreArgumentParser(string[] arguments)
CollectionAssert.AreEqual(actual: result, expected: arguments);
}

private void TestAgainstMonoUnixArgumentParser(string[] arguments)
{
var argumentString = new MonoUnixCommandLineSyntax().CreateArgumentString(arguments);
var result = SplitCommandLine(argumentString);
CollectionAssert.AreEqual(actual: result, expected: arguments);
}

#region ---- .NET Core Arguments Parser ----
// copied from https://github.com/dotnet/corefx/blob/ccb68c0602656cea9a2a33f35f54dccba9eef784/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs#L785

Expand Down Expand Up @@ -182,104 +174,5 @@ private static string GetNextArgument(string arguments, ref int i)
return currentArgument.ToString();
}
#endregion

#region ---- Mono Unix Arguments Parser ----
// based on https://github.com/mono/mono/blob/c114ff59d96baba4479361b2679b7de602517877/mono/eglib/gshell.c

public static List<string> SplitCommandLine(string commandLine)
{
var escaped = false;
var fresh = true;
var quoteChar = '\0';
var str = new StringBuilder();
var result = new List<string>();

for (var i = 0; i < commandLine.Length; ++i)
{
var c = commandLine[i];
if (escaped)
{
/*
* \CHAR is only special inside a double quote if CHAR is
* one of: $`"\ and newline
*/
if (quoteChar == '"')
{
if (!(c == '$' || c == '`' || c == '"' || c == '\\'))
{
str.Append('\\');
}
str.Append(c);
}
else
{
if (!char.IsWhiteSpace(c))
{
str.Append(c);
}
}
escaped = false;
}
else if (quoteChar != '\0')
{
if (c == quoteChar)
{
quoteChar = '\0';
if (fresh && (i + 1 == commandLine.Length || char.IsWhiteSpace(commandLine[i + 1])))
{
result.Add(str.ToString());
str.Clear();
}
}
else if (c == '\\')
{
escaped = true;
}
else
{
str.Append(c);
}
}
else if (char.IsWhiteSpace(c))
{
if (str.Length > 0)
{
result.Add(str.ToString());
str.Clear();
}
}
else if (c == '\\')
{
escaped = true;
}
else if (c == '\'' || c == '"')
{
fresh = str.Length == 0;
quoteChar = c;
}
else
{
str.Append(c);
}
}

if (escaped)
{
throw new FormatException($"Unfinished escape: '{commandLine}'");
}

if (quoteChar != '\0')
{
throw new FormatException($"Unfinished quote: '{commandLine}'");
}

if (str.Length > 0)
{
result.Add(str.ToString());
}

return result;
}
#endregion
}
}
24 changes: 5 additions & 19 deletions MedallionShell.Tests/GeneralTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ public void TestEncoding()
var bytes = new byte[] { 255 };
var inputEncoded = Console.InputEncoding.GetString(bytes);
inputEncoded.ShouldEqual(Console.OutputEncoding.GetString(bytes)); // sanity check
// mono and .NET Core will default to UTF8
// .NET Core will default to UTF8
var defaultsToUtf8 = Console.InputEncoding.WebName == Encoding.UTF8.WebName;
if (!defaultsToUtf8)
{
Expand Down Expand Up @@ -582,25 +582,11 @@ public void TestProcessKeepsWritingAfterOutputIsClosed()
command.StandardInput.WriteLine(new string('a', i));
}

// workaround for https://github.com/mono/mono/issues/18279; so far
// I've encountered this only on Mono Linux
if (PlatformCompatibilityHelper.IsMono
&& !RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
command.StandardInput.Dispose();
command.Task.Wait(TimeSpan.FromSeconds(1000)).ShouldEqual(true);
command.Result.ExitCode.ShouldEqual(1);
// SampleCommand fails because it's attempt to write to Console.Out fails hard
Assert.That(command.Result.StandardError, Does.Contain("System.IO.IOException: Write fault"));
}
else
{
command.Task.IsCompleted.ShouldEqual(false);
command.Task.IsCompleted.ShouldEqual(false);

command.StandardInput.Dispose();
command.Task.Wait(TimeSpan.FromSeconds(1000)).ShouldEqual(true);
command.Result.Success.ShouldEqual(true);
}
command.StandardInput.Dispose();
command.Task.Wait(TimeSpan.FromSeconds(1000)).ShouldEqual(true);
command.Result.Success.ShouldEqual(true);
}

[Test]
Expand Down
24 changes: 13 additions & 11 deletions MedallionShell.Tests/MedallionShell.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,34 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<!-- NOTE: must be net46, not net472 to run Mono tests -->
<TargetFrameworks>net6.0;net462</TargetFrameworks>
<!-- net462 is currently the oldest .NET Framework version supported per https://learn.microsoft.com/en-us/lifecycle/products/microsoft-net-framework -->
<!-- net6.0 and net8.0 are the only .NET Core versions supported per https://learn.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core -->
<!-- Should stay in sync with SampleCommand.csproj -->
<TargetFrameworks>net8.0;net6.0;net462</TargetFrameworks>
<IsPackable>false</IsPackable>
<LangVersion>Latest</LangVersion>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<CodeAnalysisRuleSet>..\stylecop.analyzers.ruleset</CodeAnalysisRuleSet>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<CodeAnalysisRuleSet>..\stylecop.analyzers.ruleset</CodeAnalysisRuleSet>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>1591</NoWarn>
<RootNamespace>Medallion.Shell.Tests</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="nunit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.4.0-beta.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.1" />
<PackageReference Include="Moq" Version="4.7.63" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435">
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="Moq" Version="4.7.63" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\MedallionShell\MedallionShell.csproj" />
<ProjectReference Include="..\SampleCommand\SampleCommand.csproj" />
<ProjectReference Include="..\SampleCommand\SampleCommand.csproj" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net462'">
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This way, we don't have to update this line when we change from net462 to net472. You can see that this technique is being used in https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/dev/src/Microsoft.IdentityModel.Protocols/Microsoft.IdentityModel.Protocols.csproj#L29.

<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Management" />
<Reference Include="System.ServiceModel" />
Expand Down
38 changes: 3 additions & 35 deletions MedallionShell.Tests/PlatformCompatibilityTest.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using SampleCommand;

namespace Medallion.Shell.Tests
{
using System.IO;
using static UnitTestHelpers;

public class PlatformCompatibilityTest
{
[Test]
public Task TestReadAfterExit() => RunTestAsync(() => PlatformCompatibilityTests.TestReadAfterExit());

[Test]
public Task TestWriteAfterExit() => RunTestAsync(() => PlatformCompatibilityTests.TestWriteAfterExit());
// TODO: fix in https://github.com/madelson/MedallionShell/issues/117
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is fine for now because this must be fixed before 1.7 is released.

//[Test]
//public Task TestWriteAfterExit() => RunTestAsync(() => PlatformCompatibilityTests.TestWriteAfterExit());

[Test]
public Task TestFlushAfterExit() => RunTestAsync(() => PlatformCompatibilityTests.TestFlushAfterExit());
Expand Down Expand Up @@ -50,33 +44,7 @@ private static async Task RunTestAsync(Expression<Action> testMethod)
var compiled = testMethod.Compile();
Assert.DoesNotThrow(() => compiled(), "should run on current platform");

// don't bother testing running Mono from .NET Core or Mono itself
#if NETFRAMEWORK
if (!PlatformCompatibilityHelper.IsMono)
{
var methodName = ((MethodCallExpression)testMethod.Body).Method.Name;

var monoPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\Program Files\Mono\bin\mono.exe" : "/usr/bin/mono";
if (!File.Exists(monoPath))
{
// https://www.appveyor.com/docs/environment-variables/
if (Environment.GetEnvironmentVariable("APPVEYOR")?.ToLowerInvariant() == "true")
{
// not on VS2017 VM yet: https://www.appveyor.com/docs/windows-images-software/
Console.WriteLine("On APPVEYOR with no Mono installed; skipping mono test");
return;
}

Assert.Fail($"Could not find mono install at {monoPath}");
}

var command = Command.Run(monoPath, SampleCommand, nameof(PlatformCompatibilityTests), methodName);
await command.Task;
command.Result.Success.ShouldEqual(true, "should run on Mono. Got: " + command.Result.StandardError);
}
#else
await Task.CompletedTask; // make the compiler happy
#endif
}
}
}
4 changes: 2 additions & 2 deletions MedallionShell/ErrorExitCodeException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ namespace Medallion.Shell
public sealed class ErrorExitCodeException : Exception
{
internal ErrorExitCodeException(Process process)
: base(string.Format("Process {0} ({1} {2}) exited with non-zero value {3}", process.Id, process.StartInfo.FileName, process.StartInfo.Arguments, process.SafeGetExitCode()))
: base(string.Format("Process {0} ({1} {2}) exited with non-zero value {3}", process.Id, process.StartInfo.FileName, process.StartInfo.Arguments, process.ExitCode))
{
this.ExitCode = process.SafeGetExitCode();
this.ExitCode = process.ExitCode;
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion MedallionShell/MedallionShell.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;netstandard1.3;netstandard2.0;net45;net46;net471</TargetFrameworks>
<TargetFrameworks>net8.0;net6.0;netstandard1.3;netstandard2.0;net45;net46;net471</TargetFrameworks>
</PropertyGroup>

<PropertyGroup>
Expand Down
68 changes: 0 additions & 68 deletions MedallionShell/MonoUnixCommandLineSyntax.cs

This file was deleted.

Loading