Skip to content

Commit

Permalink
Support for basic if/elif directives
Browse files Browse the repository at this point in the history
Adding some basic validation support for disabled text
closes #15
  • Loading branch information
belav committed Aug 20, 2021
1 parent 8c72621 commit 242dec0
Show file tree
Hide file tree
Showing 19 changed files with 660 additions and 27 deletions.
8 changes: 7 additions & 1 deletion Src/CSharpier.Benchmarks/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace CSharpier.Benchmarks
[MemoryDiagnoser]
public class Benchmarks
{
[Benchmark]
//[Benchmark]
public void Default_CodeFormatter()
{
var codeFormatter = new CodeFormatter();
Expand All @@ -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
39 changes: 39 additions & 0 deletions Src/CSharpier.Tests/CommandLineFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,45 @@ public void File_With_Mismatched_Line_Endings_In_Verbatim_String_Should_Pass_Val
exitCode.Should().Be(0);
}

[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
27 changes: 25 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,43 @@ 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[]> { new[] { "1", "2" }, new[] { "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[]> { new[] { "1", "2" }, new[] { "3" } });
}

[TestCase("{ \"printWidth\": 10 }")]
Expand Down Expand Up @@ -115,6 +137,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
24 changes: 24 additions & 0 deletions Src/CSharpier.Tests/DisabledTextComparerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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;
"";
using var stringReader = new StringReader(jsontext);";

DisabledTextComparer.IsCodeBasicallyEqual(before, after).Should().BeTrue();
}
}
}
11 changes: 11 additions & 0 deletions Src/CSharpier.Tests/Samples/Samples.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.IO;
using System.Text;
using System.Threading;
using FluentAssertions;
using NUnit.Framework;

namespace CSharpier.Tests.Samples
Expand Down Expand Up @@ -34,6 +36,15 @@ public void RunTest(string fileName)
new PrinterOptions { IncludeDocTree = true, IncludeAST = true, }
);

var syntaxNodeComparer = new SyntaxNodeComparer(
code,
result.Code,
CancellationToken.None
);

var compareResult = syntaxNodeComparer.CompareSource();
compareResult.Should().BeEmpty();

File.WriteAllText(file.Replace(".cst", ".actual.cst"), result.Code, Encoding.UTF8);
File.WriteAllText(file.Replace(".cst", ".doctree.txt"), result.DocTree, Encoding.UTF8);
}
Expand Down
86 changes: 74 additions & 12 deletions Src/CSharpier.Tests/Samples/Scratch.cst
Original file line number Diff line number Diff line change
@@ -1,15 +1,77 @@
public class FunctionParameter : EntityBase
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

#if (NET45 || NET50)
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using System.Collections;
using System;
using System.IO;
using Newtonsoft.Json.Linq;

namespace Newtonsoft.Json.Tests.Issues
{
[TestFixture]
public class Issue2492
{
public Function Function

[Required]
[UniqueIndex(AdditionalColumns = nameof(Name))]
public Guid FunctionId { get; set; }

public string Name { get; set; }

public override string GetDisplayName()
[Test]
public void Test_Object()
{
return this.Name;

string jsontext = @"{ ""ABC"": //DEF
{}}";

using var stringReader = new StringReader(jsontext);
using var jsonReader = new JsonTextReader(stringReader);

JsonSerializer serializer = JsonSerializer.Create();
var x = serializer.Deserialize<JToken>(jsonReader);

Assert.AreEqual(JTokenType.Object, x["ABC"].Type);
}

[Test]
public void Test_Integer()
{
string jsontext = "{ \"ABC\": /*DEF*/ 1}";

using var stringReader = new StringReader(jsontext);
using var jsonReader = new JsonTextReader(stringReader);

JsonSerializer serializer = JsonSerializer.Create();
var x = serializer.Deserialize<JToken>(jsonReader);

Assert.AreEqual(JTokenType.Integer, x["ABC"].Type);
}
}
}
#endif
23 changes: 23 additions & 0 deletions Src/CSharpier.Tests/SyntaxNodeComparerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,29 @@ public void Mismatched_Line_Endings_In_Verbatim_String_Should_Not_Print_Error(st
result.Should().BeEmpty();
}

[Test]
public void Mismatched_Disabled_Text_Should_Not_Print_Error()
{
var left =
@"class ClassName
{
#if DEBUG
public string Tester;
#endif
}";
var right =
@"class ClassName
{
#if DEBUG
public string Tester;
#endif
}
";

var result = this.AreEqual(left, right);
result.Should().BeEmpty();
}

private void ResultShouldBe(string result, string be)
{
if (Environment.GetEnvironmentVariable("NormalizeLineEndings") != null)
Expand Down
80 changes: 80 additions & 0 deletions Src/CSharpier.Tests/SyntaxPrinter/PreprocessorSymbolsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using System;
using System.Linq;
using CSharpier.SyntaxPrinter;
using FluentAssertions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Framework;

namespace CSharpier.Tests.SyntaxPrinter
{
public class PreprocessorSymbolsTests
{
[TestCase("BASIC_IF", "BASIC_IF")]
[TestCase("!NOT_IF", "NOT_IF")]
[TestCase("EQUALS_TRUE == true", "EQUALS_TRUE")]
[TestCase("EQUALS_FALSE == false", "EQUALS_FALSE")]
[TestCase("true == TRUE_EQUALS", "TRUE_EQUALS")]
[TestCase("false == FALSE_EQUALS", "FALSE_EQUALS")]
[TestCase("LEFT_OR || RIGHT_OR", "LEFT_OR")]
[TestCase("LEFT_AND && RIGHT_AND", "LEFT_AND", "RIGHT_AND")]
[TestCase("(EQUALS_TRUE_IN_PARENS == true)", "EQUALS_TRUE_IN_PARENS")]
public void AddSymbolSet_For_If(string condition, params string[] symbols)
{
var trivia = WhenIfDirectiveHasCondition(condition);

var result = AddSymbolSet(trivia);

result.Should().ContainInOrder(symbols);
}

[Test]
public void AddSymbolSet_For_Basic_Elif_Adds_Symbol()
{
var trivia = WhenElifDirectiveHasCondition("DEBUG");

var result = AddSymbolSet(trivia);

result.Should().ContainInOrder("DEBUG");
}

private string[] AddSymbolSet(ConditionalDirectiveTriviaSyntax trivia)
{
TestablePreprocessorSymbols.Reset();

TestablePreprocessorSymbols.AddSymbolSet(trivia);

return TestablePreprocessorSymbols.GetSymbolSets().FirstOrDefault()
?? Array.Empty<string>();
}

private IfDirectiveTriviaSyntax WhenIfDirectiveHasCondition(string condition)
{
return SyntaxFactory.IfDirectiveTrivia(
SyntaxFactory.ParseExpression(condition),
true,
true,
true
);
}

private ElifDirectiveTriviaSyntax WhenElifDirectiveHasCondition(string condition)
{
return SyntaxFactory.ElifDirectiveTrivia(
SyntaxFactory.ParseExpression(condition),
true,
true,
true
);
}

private class TestablePreprocessorSymbols : PreprocessorSymbols
{
public static void AddSymbolSet(
ConditionalDirectiveTriviaSyntax conditionalDirectiveTriviaSyntax
) {
AddSymbolSetForConditional(conditionalDirectiveTriviaSyntax);
}
}
}
}
3 changes: 3 additions & 0 deletions Src/CSharpier.Tests/TestFiles/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,6 +35,8 @@ protected void RunTest(string folderName, 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,
Expand Down
Loading

0 comments on commit 242dec0

Please sign in to comment.