Created
January 7, 2019 14:13
-
-
Save aolszowka/7c7f374a5e1adf927d4113b2bec12fc3 to your computer and use it in GitHub Desktop.
Using Roslyn to Mass Format a Solution (No .editorconfig support)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace TestRosylnFormatter | |
{ | |
using Microsoft.Build.Locator; | |
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp.Formatting; | |
using Microsoft.CodeAnalysis.Formatting; | |
using Microsoft.CodeAnalysis.MSBuild; | |
using Microsoft.CodeAnalysis.Options; | |
using System; | |
using System.IO; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
MSBuildLocator.RegisterDefaults(); | |
string solutionPath = @"S:\Code\Client.sln"; | |
using (MSBuildWorkspace msWorkspace = MSBuildWorkspace.Create()) | |
{ | |
Solution solution = msWorkspace.OpenSolutionAsync(solutionPath).Result; | |
// Really wish I could get this to load options from .editorconfig | |
OptionSet formattingOptions = | |
msWorkspace.Options | |
.WithChangedOption(CSharpFormattingOptions.SpaceAfterComma, true) | |
.WithChangedOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, false) | |
.WithChangedOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, true) | |
.WithChangedOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, true) | |
.WithChangedOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, true) | |
.WithChangedOption(CSharpFormattingOptions.SpaceAfterMethodCallName, false) | |
.WithChangedOption(CSharpFormattingOptions.SpaceAfterCast, false) | |
.WithChangedOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, false) | |
.WithChangedOption(FormattingOptions.IndentationSize, LanguageNames.CSharp, 4) | |
.WithChangedOption(FormattingOptions.TabSize, LanguageNames.CSharp, 4) | |
.WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, true); | |
foreach (Project project in solution.Projects) | |
{ | |
//Parallel.ForEach(project.Documents, document => | |
foreach (Document document in project.Documents) | |
{ | |
if (!document.Name.EndsWith("designer.cs", StringComparison.InvariantCultureIgnoreCase)) | |
{ | |
Console.WriteLine($"Formatting {document.Name} in {project.Name}"); | |
SyntaxNode formattedDocument = Formatter.Format(document.GetSyntaxRootAsync().Result, msWorkspace, formattingOptions); | |
// Its unclear how to make Roslyn save the source documents; this feels really hacky | |
using (StreamWriter sw = new StreamWriter(document.FilePath, false, new System.Text.UTF8Encoding(true))) | |
{ | |
formattedDocument.WriteTo(sw); | |
} | |
} | |
} | |
//); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment