Skip to content
This repository was archived by the owner on Jul 12, 2022. It is now read-only.

Commit b57e309

Browse files
committed
Merge pull request #47 from jaredpar/fixes
Several fixes
2 parents 3c16dd4 + 031b252 commit b57e309

19 files changed

+174
-152
lines changed

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ $ .\CodeFormatter.exe
2222
CodeFormatter <project or solution> [<rule types>] [/file <filename>]
2323
<rule types> - Rule types to use in addition to the default ones.
2424
Use ConvertTests to convert MSTest tests to xUnit.
25-
<filename> - Only apply changes to files with specified name.
25+
<filename> - Only apply changes to files with specified name.
26+
<configs> - Additional preprocessor configurations the formatter
27+
should run under.
28+
<copyright> - Specifies file containing copyright header.
2629
```
2730

2831
## Contributing

src/CodeFormatter/Program.cs

Lines changed: 54 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,21 @@ namespace CodeFormatter
1515
{
1616
internal static class Program
1717
{
18+
private const string FileSwitch = "/file:";
19+
private const string ConfigSwitch = "/c:";
20+
private const string CopyrightSwitch = "/copyright:";
21+
1822
private static int Main(string[] args)
1923
{
2024
if (args.Length < 1)
2125
{
22-
Console.WriteLine("CodeFormatter <project or solution> [<rule types>] [/file <filename>] [/nocopyright]");
26+
Console.WriteLine("CodeFormatter <project or solution> [<rule types>] [/file:<filename>] [/nocopyright] [/c:<config1,config2> [/copyright:file]");
2327
Console.WriteLine(" <rule types> - Rule types to use in addition to the default ones.");
2428
Console.WriteLine(" Use ConvertTests to convert MSTest tests to xUnit.");
25-
Console.WriteLine(" <filename> - Only apply changes to files with specified name.");
29+
Console.WriteLine(" <filename> - Only apply changes to files with specified name.");
30+
Console.WriteLine(" <configs> - Additional preprocessor configurations the formatter");
31+
Console.WriteLine(" should run under.");
32+
Console.WriteLine(" <copyright> - Specifies file containing copyright header.")
2633
return -1;
2734
}
2835

@@ -33,37 +40,48 @@ private static int Main(string[] args)
3340
return -1;
3441
}
3542

36-
var ruleTypes = new List<string>();
37-
var filenames = new List<string>();
38-
var disableCopyright = false;
43+
var fileNamesBuilder = ImmutableArray.CreateBuilder<string>();
44+
var ruleTypeBuilder = ImmutableArray.CreateBuilder<string>();
45+
var configBuilder = ImmutableArray.CreateBuilder<string[]>();
46+
var copyrightHeader = FormattingConstants.DefaultCopyrightHeader;
3947
var comparer = StringComparer.OrdinalIgnoreCase;
40-
var preprocessorConfigurations = new List<string[]>();
4148

4249
for (int i = 1; i < args.Length; i++)
4350
{
4451
string arg = args[i];
45-
if (comparer.Equals(arg, "/file"))
52+
if (arg.StartsWith(FileSwitch, StringComparison.OrdinalIgnoreCase))
53+
{
54+
var all = arg.Substring(FileSwitch.Length);
55+
var files = all.Split(new[] { ','}, StringSplitOptions.RemoveEmptyEntries);
56+
fileNamesBuilder.AddRange(files);
57+
}
58+
else if (arg.StartsWith(ConfigSwitch, StringComparison.OrdinalIgnoreCase))
4659
{
47-
if (i + 1 < args.Length)
60+
var all = arg.Substring(ConfigSwitch.Length);
61+
var configs = all.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
62+
configBuilder.Add(configs);
63+
}
64+
else if (arg.StartsWith(CopyrightSwitch, StringComparison.OrdinalIgnoreCase))
65+
{
66+
var fileName = arg.Substring(CopyrightSwitch.Length);
67+
try
68+
{
69+
copyrightHeader = ImmutableArray.CreateRange(File.ReadAllLines(fileName));
70+
}
71+
catch (Exception ex)
4872
{
49-
string param = args[i + 1];
50-
filenames.Add(param);
51-
i++;
73+
Console.Error.WriteLine("Could not read {0}", fileName);
74+
Console.Error.WriteLine(ex.Message);
75+
return -1;
5276
}
5377
}
5478
else if (comparer.Equals(arg, "/nocopyright"))
5579
{
56-
disableCopyright = true;
57-
}
58-
else if (arg.StartsWith("/c:", StringComparison.OrdinalIgnoreCase))
59-
{
60-
var all = arg.Substring(3);
61-
var configs = all.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
62-
preprocessorConfigurations.Add(configs);
80+
copyrightHeader = ImmutableArray<string>.Empty;
6381
}
6482
else
6583
{
66-
ruleTypes.Add(arg);
84+
ruleTypeBuilder.Add(arg);
6785
}
6886
}
6987

@@ -72,21 +90,30 @@ private static int Main(string[] args)
7290

7391
Console.CancelKeyPress += delegate { cts.Cancel(); };
7492

75-
RunAsync(projectOrSolutionPath, ruleTypes, filenames, disableCopyright, ImmutableArray.CreateRange(preprocessorConfigurations), ct).Wait(ct);
93+
RunAsync(
94+
projectOrSolutionPath,
95+
ruleTypeBuilder.ToImmutableArray(),
96+
fileNamesBuilder.ToImmutableArray(),
97+
configBuilder.ToImmutableArray(),
98+
copyrightHeader,
99+
ct).Wait(ct);
76100
Console.WriteLine("Completed formatting.");
77101
return 0;
78102
}
79103

80-
private static async Task RunAsync(string projectOrSolutionPath, IEnumerable<string> ruleTypes, IEnumerable<string> filenames, bool disableCopright, ImmutableArray<string[]> preprocessorConfigurations, CancellationToken cancellationToken)
104+
private static async Task RunAsync(
105+
string projectOrSolutionPath,
106+
ImmutableArray<string> ruleTypes,
107+
ImmutableArray<string> fileNames,
108+
ImmutableArray<string[]> preprocessorConfigurations,
109+
ImmutableArray<string> copyrightHeader,
110+
CancellationToken cancellationToken)
81111
{
82112
var workspace = MSBuildWorkspace.Create();
83-
var engine = FormattingEngine.Create(ruleTypes, filenames);
113+
var engine = FormattingEngine.Create(ruleTypes);
84114
engine.PreprocessorConfigurations = preprocessorConfigurations;
85-
86-
if (disableCopright)
87-
{
88-
engine.CopyrightHeader = ImmutableArray<string>.Empty;
89-
}
115+
engine.FileNames = fileNames;
116+
engine.CopyrightHeader = copyrightHeader;
90117

91118
string extension = Path.GetExtension(projectOrSolutionPath);
92119
if (StringComparer.OrdinalIgnoreCase.Equals(extension, ".sln"))

src/Microsoft.DotNet.CodeFormatting.Tests/Rules/CombinationTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public sealed class CombinationTest : CodeFormattingTestBase
1919

2020
static CombinationTest()
2121
{
22-
s_formattingEngine = (FormattingEngineImplementation)FormattingEngine.Create(Enumerable.Empty<string>(), Enumerable.Empty<string>());
22+
s_formattingEngine = (FormattingEngineImplementation)FormattingEngine.Create(ImmutableArray<string>.Empty);
2323
}
2424

2525
public CombinationTest()

src/Microsoft.DotNet.CodeFormatting.Tests/Rules/ExplicitVisibilityRuleTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,28 @@ private class N2 { }
360360
}
361361
362362
public partial class C { }
363+
";
364+
365+
Verify(text, expected, runFormatter: false);
366+
}
367+
368+
[Fact]
369+
public void IgnorePartialMethods()
370+
{
371+
var text = @"
372+
class C
373+
{
374+
void M1();
375+
partial void M2();
376+
}
377+
";
378+
379+
var expected = @"
380+
internal class C
381+
{
382+
private void M1();
383+
partial void M2();
384+
}
363385
";
364386

365387
Verify(text, expected, runFormatter: false);
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using Microsoft.CodeAnalysis;
2+
using Microsoft.CodeAnalysis.CSharp;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
using System.Text;
7+
using System.Threading.Tasks;
8+
9+
namespace Microsoft.DotNet.CodeFormatting
10+
{
11+
internal static class Extensions
12+
{
13+
internal static IEnumerable<SyntaxTrivia> AddTwoNewLines(this IEnumerable<SyntaxTrivia> trivia)
14+
{
15+
return trivia.Concat(new[] { SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.CarriageReturnLineFeed });
16+
}
17+
18+
internal static IEnumerable<SyntaxTrivia> AddNewLine(this IEnumerable<SyntaxTrivia> trivia)
19+
{
20+
return trivia.Concat(new[] { SyntaxFactory.CarriageReturnLineFeed });
21+
}
22+
}
23+
}

src/Microsoft.DotNet.CodeFormatting/Filters/FilenameFilter.cs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,27 +12,29 @@
1212

1313
namespace Microsoft.DotNet.CodeFormatting.Filters
1414
{
15+
[Export(typeof(IFormattingFilter))]
1516
internal sealed class FilenameFilter : IFormattingFilter
1617
{
17-
private IEnumerable<string> _filenames;
18+
private readonly Options _options;
1819

19-
public FilenameFilter(IEnumerable<string> filenames)
20+
[ImportingConstructor]
21+
public FilenameFilter(Options options)
2022
{
21-
_filenames = filenames;
23+
_options = options;
2224
}
2325

2426
public bool ShouldBeProcessed(Document document)
2527
{
26-
if (!_filenames.Any())
28+
var fileNames = _options.FileNames;
29+
if (fileNames.IsDefaultOrEmpty)
2730
{
2831
return true;
2932
}
3033

3134
string docFilename = Path.GetFileName(document.FilePath);
32-
33-
foreach (var filename in _filenames)
35+
foreach (var filename in fileNames)
3436
{
35-
if (filename.Equals(docFilename, StringComparison.InvariantCultureIgnoreCase))
37+
if (filename.Equals(docFilename, StringComparison.OrdinalIgnoreCase))
3638
{
3739
return true;
3840
}

src/Microsoft.DotNet.CodeFormatting/Filters/IgnoreDesignerGeneratedCodeFilter.cs renamed to src/Microsoft.DotNet.CodeFormatting/Filters/IgnoreGeneratedFilesFilter.cs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
namespace Microsoft.DotNet.CodeFormatting.Filters
1111
{
1212
[Export(typeof(IFormattingFilter))]
13-
internal sealed class IgnoreDesignerGeneratedCodeFilter : IFormattingFilter
13+
internal sealed class IgnoreGeneratedFilesFilter : IFormattingFilter
1414
{
1515
public bool ShouldBeProcessed(Document document)
1616
{
@@ -19,8 +19,13 @@ public bool ShouldBeProcessed(Document document)
1919
return true;
2020
}
2121

22-
var isDesignerGenerated = document.FilePath.EndsWith(".Designer.cs", StringComparison.OrdinalIgnoreCase);
23-
return !isDesignerGenerated;
22+
if (document.FilePath.EndsWith(".Designer.cs", StringComparison.OrdinalIgnoreCase) ||
23+
document.FilePath.EndsWith(".Generated.cs", StringComparison.OrdinalIgnoreCase))
24+
{
25+
return false;
26+
}
27+
28+
return true;
2429
}
2530
}
2631
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Collections.Immutable;
4+
using System.Linq;
5+
using System.Text;
6+
using System.Threading.Tasks;
7+
8+
namespace Microsoft.DotNet.CodeFormatting
9+
{
10+
public static class FormattingConstants
11+
{
12+
private static readonly string[] s_defaultCopyrightHeader =
13+
{
14+
"// Copyright (c) Microsoft. All rights reserved.",
15+
"// Licensed under the MIT license. See LICENSE file in the project root for full license information."
16+
};
17+
18+
public static readonly ImmutableArray<string> DefaultCopyrightHeader;
19+
20+
static FormattingConstants()
21+
{
22+
DefaultCopyrightHeader = ImmutableArray.CreateRange(s_defaultCopyrightHeader);
23+
}
24+
}
25+
}

src/Microsoft.DotNet.CodeFormatting/FormattingEngine.cs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,13 @@
88
using System.Collections.Generic;
99
using Microsoft.DotNet.CodeFormatting.Rules;
1010
using Microsoft.DotNet.CodeFormatting.Filters;
11+
using System.Collections.Immutable;
1112

1213
namespace Microsoft.DotNet.CodeFormatting
1314
{
1415
public static class FormattingEngine
1516
{
16-
public static IFormattingEngine Create(IEnumerable<string> ruleTypes, IEnumerable<string> filenames)
17+
public static IFormattingEngine Create(ImmutableArray<string> ruleTypes)
1718
{
1819
var catalog = new AssemblyCatalog(typeof(FormattingEngine).Assembly);
1920

@@ -46,12 +47,6 @@ public static IFormattingEngine Create(IEnumerable<string> ruleTypes, IEnumerabl
4647
});
4748

4849
var container = new CompositionContainer(filteredCatalog);
49-
50-
if (filenames.Any())
51-
{
52-
container.ComposeExportedValue<IFormattingFilter>(new FilenameFilter(filenames));
53-
}
54-
5550
var engine = container.GetExportedValue<IFormattingEngine>();
5651
var consoleFormatLogger = new ConsoleFormatLogger();
5752

src/Microsoft.DotNet.CodeFormatting/FormattingEngineImplementation.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ public ImmutableArray<string[]> PreprocessorConfigurations
4242
set { _options.PreprocessorConfigurations = value; }
4343
}
4444

45+
public ImmutableArray<string> FileNames
46+
{
47+
get { return _options.FileNames; }
48+
set { _options.FileNames = value; }
49+
}
50+
4551
public IFormatLogger FormatLogger
4652
{
4753
get { return _options.FormatLogger; }

0 commit comments

Comments
 (0)