diff --git a/build/Tasks/FormatCode.cs b/build/Tasks/FormatCode.cs new file mode 100644 index 0000000000..02729c12e8 --- /dev/null +++ b/build/Tasks/FormatCode.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using System.Linq; +using Cake.Common; +using Cake.Common.Diagnostics; +using Cake.Core; +using Cake.Core.IO; +using Cake.Frosting; + +public class FormatCode : FrostingTask +{ + public override void Run(BuildContext context) + { + var codeFormatterExe = context.FileSystem + .GetDirectory("tools") + .GetFiles("CodeFormatter.exe", SearchScope.Recursive) + .First() + .Path + .MakeAbsolute(context.Environment); + + foreach (var project in context.Projects) + { + context.Information("Formatting code of {0}", project.Name); + + var tempCsprojFile = CreateTempCsproj(context, project.Name); + context.Information("Generated temporary {0} file to run the formatter", new FilePath(tempCsprojFile).GetFilename()); + + var exitCode = context.StartProcess( + codeFormatterExe, + $"{tempCsprojFile} /nocopyright /nounicode"); + + if (exitCode != 0) + { + throw new CakeException($"An error occured while formatting code of {project.Name}"); + } + } + + context.Information("Successfully formatted code of all the projects"); + } + + public override bool ShouldRun(BuildContext context) + { + return context.IsRunningOnWindows(); + } + + private static string CreateTempCsproj(BuildContext context, string projectName) + { + DirectoryPath tempFolder = System.IO.Path.GetTempPath(); + var projectCsproj = tempFolder.CombineWithFilePath($"{projectName}.csproj").FullPath; + + var files = context.FileSystem + .GetDirectory(projectName) + .GetFiles("*.cs", SearchScope.Recursive) + .Select(x => x.Path.MakeAbsolute(context.Environment)) + .ToArray(); + + var compileElements = files + .Select(x => $"") + .ToArray(); + + var csprojContent = +$@" + + + {string.Join(Environment.NewLine, compileElements)} + + +"; + + File.WriteAllText(projectCsproj, csprojContent); + + return projectCsproj; + } +} diff --git a/build/tools.project.json b/build/tools.project.json index fc95712dc5..3ab6ce6a4c 100644 --- a/build/tools.project.json +++ b/build/tools.project.json @@ -1,7 +1,8 @@ { "dependencies": { "GitVersion.CommandLine": "3.6.2", - "PdbGit": "3.0.38" + "PdbGit": "3.0.38", + "Octokit.CodeFormatter": "1.0.0-preview" }, "frameworks": { "net45": {