Skip to content

Commit

Permalink
Support for basic if/elif directives (#405)
Browse files Browse the repository at this point in the history
* Support for basic if/elif directives

Adding some basic validation support for disabled text
closes #15

* Fixing unit tests

* Making some progress on edge cases

* Self code review

* Change format of PreprocessorSymbols

* Self code review

* Cleanup after rebase

* Cleaning up some edge cases around new lines
  • Loading branch information
belav authored Aug 23, 2021
1 parent 4755e96 commit d7ca975
Show file tree
Hide file tree
Showing 20 changed files with 790 additions and 38 deletions.
6 changes: 6 additions & 0 deletions Src/CSharpier.Benchmarks/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ public void Default_SyntaxNodeComparer()
syntaxNodeComparer.CompareSource();
}

[Benchmark]
public void IsCodeBasicallyEqual_SyntaxNodeComparer()
{
DisabledTextComparer.IsCodeBasicallyEqual(code, code);
}

private string code =
@"using System;
using System.Collections.Generic;
Expand Down
66 changes: 64 additions & 2 deletions Src/CSharpier.Tests/CommandLineFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public void Format_Writes_Failed_To_Compile()
{
WhenAFileExists("Invalid.cs", "asdfasfasdf");

var result = this.Format();
var (_, lines) = this.Format();

result.lines.First()
lines.First()
.Should()
.Be(
$"Warn {Path.DirectorySeparatorChar}Invalid.cs - Failed to compile so was not formatted."
Expand Down Expand Up @@ -248,6 +248,68 @@ public void File_With_Mismatched_Line_Endings_In_Verbatim_String_Should_Pass_Val
exitCode.Should().Be(0);
}

[Test]
public void File_With_Compilation_Error_In_If_Should_Not_Lose_Code()
{
var contents =
@"#if DEBUG
?using System;
#endif
";
WhenAFileExists("Invalid.cs", contents);

var (_, lines) = this.Format();

var result = GetFileContent("Invalid.cs");

result.Should().Be(contents);

lines.First()
.Should()
.Be(
$"Warn {Path.DirectorySeparatorChar}Invalid.cs - Failed to compile so was not formatted."
);
}

[Test]
public void File_Should_Format_With_Supplied_Symbols()
{
WhenAFileExists(".csharpierrc", @"{ ""preprocessorSymbolSets"": [""FORMAT""] }");
WhenAFileExists(
"file1.cs",
@"public class ClassName
{
#if FORMAT
public string ShortPropertyName;
#elif NO_FORMAT
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif
}
"
);

this.Format();

var result = GetFileContent("file1.cs");

result.Should()
.Be(
@"public class ClassName
{
#if FORMAT
public string ShortPropertyName;
#elif NO_FORMAT
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif
}
"
);
}

private (int exitCode, IList<string> lines) Format(
bool skipWrite = false,
bool check = false,
Expand Down
22 changes: 20 additions & 2 deletions Src/CSharpier.Tests/ConfigurationFileOptionsTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Generic;
using System.IO.Abstractions.TestingHelpers;
using FluentAssertions;
using NUnit.Framework;
Expand Down Expand Up @@ -36,22 +37,38 @@ public void Should_Return_Default_Options_With_No_File()
[Test]
public void Should_Return_Json_Extension_Options()
{
WhenAFileExists("c:/test/.csharpierrc.json", "{ \"printWidth\": 10 }");
WhenAFileExists(
"c:/test/.csharpierrc.json",
@"{
""printWidth"": 10,
""preprocessorSymbolSets"": [""1,2"", ""3""]
}"
);

var result = CreateConfigurationOptions("c:/test");

result.PrintWidth.Should().Be(10);
result.PreprocessorSymbolSets.Should().BeEquivalentTo(new List<string> { "1,2", "3" });
}

[TestCase("yaml")]
[TestCase("yml")]
public void Should_Return_Yaml_Extension_Options(string extension)
{
WhenAFileExists($"c:/test/.csharpierrc.{extension}", "printWidth: 10");
WhenAFileExists(
$"c:/test/.csharpierrc.{extension}",
@"
printWidth: 10
preprocessorSymbolSets:
- 1,2
- 3
"
);

var result = CreateConfigurationOptions("c:/test");

result.PrintWidth.Should().Be(10);
result.PreprocessorSymbolSets.Should().BeEquivalentTo(new List<string> { "1,2", "3" });
}

[TestCase("{ \"printWidth\": 10 }")]
Expand Down Expand Up @@ -115,6 +132,7 @@ public void Should_Return_PrintWidth_With_Yaml()
private void ShouldHaveDefaultOptions(ConfigurationFileOptions configurationFileOptions)
{
configurationFileOptions.PrintWidth.Should().Be(100);
configurationFileOptions.PreprocessorSymbolSets.Should().BeNull();
}

private ConfigurationFileOptions CreateConfigurationOptions(string baseDirectoryPath)
Expand Down
115 changes: 115 additions & 0 deletions Src/CSharpier.Tests/DisabledTextComparerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
using FluentAssertions;
using NUnit.Framework;

namespace CSharpier.Tests
{
[TestFixture]
public class DisabledTextComparerTests
{
[Test]
public void IsCodeBasicallyEqual_Should_Return_True_For_Basic_Case()
{
var before = "public string Tester;";

var after =
@"public
string Tester;
";

DisabledTextComparer.IsCodeBasicallyEqual(before, after).Should().BeTrue();
}

[Test]
public void Squash_Should_Work_With_Pointer_Stuff()
{
var before =
@" [MethodImpl (MethodImplOptions.InternalCall)]
private static unsafe extern void ApplyUpdate_internal (IntPtr base_assm, byte* dmeta_bytes, int dmeta_length, byte *dil_bytes, int dil_length, byte *dpdb_bytes, int dpdb_length);";

var after =
@"[MethodImpl(MethodImplOptions.InternalCall)]
private static unsafe extern void ApplyUpdate_internal(
IntPtr base_assm,
byte* dmeta_bytes,
int dmeta_length,
byte* dil_bytes,
int dil_length,
byte* dpdb_bytes,
int dpdb_length
);
";
Squash(before).Should().Be(Squash(after));
}

[Test]
public void Squash_Should_Work_With_Commas()
{
var before =
@"
TypeBuilder typeBuilder = moduleBuilder.DefineType(assemblyName.FullName
, TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout
, null);
";

var after =
@"
TypeBuilder typeBuilder = moduleBuilder.DefineType(
assemblyName.FullName,
TypeAttributes.Public
| TypeAttributes.Class
| TypeAttributes.AutoClass
| TypeAttributes.AnsiClass
| TypeAttributes.BeforeFieldInit
| TypeAttributes.AutoLayout,
null
);
";
Squash(before).Should().Be(Squash(after));
}

[Test]
public void Squash_Should_Work_With_Period()
{
var before =
@"
var options2 = (ProxyGenerationOptions)proxy.GetType().
GetField(""proxyGenerationOptions"", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
";

var after =
@"
var options2 = (ProxyGenerationOptions)proxy.GetType()
.GetField(""proxyGenerationOptions"", BindingFlags.Static | BindingFlags.NonPublic)
.GetValue(null);
";
Squash(before).Should().Be(Squash(after));
}

[Test]
public void Squash_Should_Work_With_Starting_Indent()
{
var before = @"array = new ulong[] { (ulong)dy.Property_ulong };";

var after = @" array = new ulong[] { (ulong)dy.Property_ulong };";
Squash(before).Should().Be(Squash(after));
}

private static string Squash(string value)
{
return TestableDisabledTextComparer.TestSquash(value);
}

private class TestableDisabledTextComparer : DisabledTextComparer
{
public static string TestSquash(string value)
{
return Squash(value);
}
}
}
}
15 changes: 10 additions & 5 deletions Src/CSharpier.Tests/FormattingTests/BaseTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.IO.Abstractions;
using System.Text;
using System.Threading;
using CSharpier.SyntaxPrinter;
using DiffEngine;
using FluentAssertions;
using NUnit.Framework;
Expand Down Expand Up @@ -34,10 +35,12 @@ protected void RunTest(string fileName, bool useTabs = false)
var fileReaderResult =
FileReader.ReadFile(filePath, new FileSystem(), CancellationToken.None).Result;

PreprocessorSymbols.Reset();

var formatter = new CodeFormatter();
var result = formatter.Format(
fileReaderResult.FileContents,
new PrinterOptions() { Width = PrinterOptions.WidthUsedByTests, UseTabs = useTabs }
new PrinterOptions { Width = PrinterOptions.WidthUsedByTests, UseTabs = useTabs }
);

var actualFilePath = filePath.Replace(".cst", ".actual.cst");
Expand All @@ -54,26 +57,28 @@ protected void RunTest(string fileName, bool useTabs = false)
filePathToChange = expectedFilePath;
}

var normalizedCode = result.Code;

if (Environment.GetEnvironmentVariable("NormalizeLineEndings") != null)
{
expectedCode = expectedCode.Replace("\r\n", "\n");
result.Code = result.Code.Replace("\r\n", "\n");
normalizedCode = normalizedCode.Replace("\r\n", "\n");
}

var comparer = new SyntaxNodeComparer(
expectedCode,
result.Code,
normalizedCode,
CancellationToken.None
);

result.Errors.Should().BeEmpty();
result.FailureMessage.Should().BeEmpty();

if (result.Code != expectedCode && !BuildServerDetector.Detected)
if (normalizedCode != expectedCode && !BuildServerDetector.Detected)
{
DiffRunner.Launch(filePathToChange, actualFilePath);
}
result.Code.Should().Be(expectedCode);
normalizedCode.Should().Be(expectedCode);

var compareResult = comparer.CompareSource();
compareResult.Should().BeNullOrEmpty();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
public class ClassName
{
#if BASIC_IF
public string ShortPropertyName;
#elif BASIC_ELIF
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif

#if !NOT_IF
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif

#if EQUALS_TRUE == true
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif

#if true == TRUE_EQUALS
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif

#if NOT_EQUALS_TRUE != true
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif

#if true != TRUE_NOT_EQUALS
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif

#if LEFT_AND && RIGHT_AND
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif

#if (LEFT_PAREN && RIGHT_PAREN)
public string ShortPropertyName;
#else
public string ShortPropertyName;
#endif
}
Loading

0 comments on commit d7ca975

Please sign in to comment.