From b3ea529128f0c9996b89fe65aef6f6c180028d33 Mon Sep 17 00:00:00 2001 From: Timothee Guerin Date: Fri, 29 Apr 2022 09:46:23 -0700 Subject: [PATCH] Format CSharp files: add `dotnet format` to `rush format` (#490) --- .editorconfig | 7 +- ...eature-dotnet-format_2022-04-28-22-09.json | 10 + ...eature-dotnet-format_2022-04-28-22-09.json | 10 + eng/pipelines/ci.yml | 4 + eng/pipelines/pull-request-common.yml | 4 + eng/scripts/check-format.js | 3 + eng/scripts/format.js | 3 + packages/cadl-vs/src/VSExtension.cs | 197 ++++++++++-------- packages/internal-build-utils/src/dotnet.ts | 15 ++ 9 files changed, 157 insertions(+), 96 deletions(-) create mode 100644 common/changes/@cadl-lang/internal-build-utils/feature-dotnet-format_2022-04-28-22-09.json create mode 100644 common/changes/cadl-vs/feature-dotnet-format_2022-04-28-22-09.json diff --git a/.editorconfig b/.editorconfig index bc6f7c251..91c5b6721 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,9 +8,4 @@ insert_final_newline = true charset = utf-8 [*.cs] -csharp_new_line_before_open_brace = none -csharp_new_line_before_catch = false -csharp_new_line_before_else = false -csharp_new_line_before_finally = false -csharp_new_line_before_members_in_anonymous_types = false -csharp_new_line_before_members_in_object_initializers = false +indent_size = 4 diff --git a/common/changes/@cadl-lang/internal-build-utils/feature-dotnet-format_2022-04-28-22-09.json b/common/changes/@cadl-lang/internal-build-utils/feature-dotnet-format_2022-04-28-22-09.json new file mode 100644 index 000000000..5a375a83a --- /dev/null +++ b/common/changes/@cadl-lang/internal-build-utils/feature-dotnet-format_2022-04-28-22-09.json @@ -0,0 +1,10 @@ +{ + "changes": [ + { + "packageName": "@cadl-lang/internal-build-utils", + "comment": "Add new util `runDotnetFormat`", + "type": "minor" + } + ], + "packageName": "@cadl-lang/internal-build-utils" +} \ No newline at end of file diff --git a/common/changes/cadl-vs/feature-dotnet-format_2022-04-28-22-09.json b/common/changes/cadl-vs/feature-dotnet-format_2022-04-28-22-09.json new file mode 100644 index 000000000..a4cdce0da --- /dev/null +++ b/common/changes/cadl-vs/feature-dotnet-format_2022-04-28-22-09.json @@ -0,0 +1,10 @@ +{ + "changes": [ + { + "packageName": "cadl-vs", + "comment": "", + "type": "none" + } + ], + "packageName": "cadl-vs" +} \ No newline at end of file diff --git a/eng/pipelines/ci.yml b/eng/pipelines/ci.yml index aefeef9a8..639f65ded 100644 --- a/eng/pipelines/ci.yml +++ b/eng/pipelines/ci.yml @@ -15,6 +15,10 @@ jobs: versionSpec: 16.x displayName: Install Node.js + - task: UseDotNet@2 + inputs: + version: 6.0.x + - script: echo '##vso[task.setvariable variable=CADL_VS_CI_BUILD;]true' displayName: Enable official Visual Studio extension build diff --git a/eng/pipelines/pull-request-common.yml b/eng/pipelines/pull-request-common.yml index 929d3a432..b4f870709 100644 --- a/eng/pipelines/pull-request-common.yml +++ b/eng/pipelines/pull-request-common.yml @@ -8,6 +8,10 @@ steps: versionSpec: ${{ parameters.nodeVersion }} displayName: Install Node.js + - task: UseDotNet@2 + inputs: + version: 6.0.x + - script: node common/scripts/install-run-rush.js install displayName: Install JavaScript Dependencies diff --git a/eng/scripts/check-format.js b/eng/scripts/check-format.js index 167994775..8adfc3e27 100644 --- a/eng/scripts/check-format.js +++ b/eng/scripts/check-format.js @@ -1,7 +1,10 @@ +// @ts-check +import { runDotnetFormat } from "../../packages/internal-build-utils/dist/src/index.js"; import { CommandFailedError, runPrettier } from "./helpers.js"; try { runPrettier("--list-different"); + runDotnetFormat("--verify-no-changes"); } catch (err) { if (err instanceof CommandFailedError) { console.error( diff --git a/eng/scripts/format.js b/eng/scripts/format.js index be82e90e6..38c1b8349 100644 --- a/eng/scripts/format.js +++ b/eng/scripts/format.js @@ -1,2 +1,5 @@ +// @ts-check +import { runDotnetFormat } from "../../packages/internal-build-utils/dist/src/index.js"; import { runPrettier } from "./helpers.js"; runPrettier("--write"); +await runDotnetFormat(); diff --git a/packages/cadl-vs/src/VSExtension.cs b/packages/cadl-vs/src/VSExtension.cs index 582601fcf..a6679754d 100644 --- a/packages/cadl-vs/src/VSExtension.cs +++ b/packages/cadl-vs/src/VSExtension.cs @@ -17,63 +17,69 @@ using Microsoft.VisualStudio.Utilities; using Task = System.Threading.Tasks.Task; using System.Linq; -namespace Microsoft.Cadl.VisualStudio { - [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] - [Guid("88b9492f-c019-492c-8aeb-f325a7e4cf23")] - public sealed class Package : AsyncPackage { } +namespace Microsoft.Cadl.VisualStudio +{ + [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] + [Guid("88b9492f-c019-492c-8aeb-f325a7e4cf23")] + public sealed class Package : AsyncPackage { } - public sealed class ContentDefinition { - [Export] - [Name("cadl")] - [BaseDefinition(CodeRemoteContentDefinition.CodeRemoteContentTypeName)] - public ContentTypeDefinition? CadlContentTypeDefinition => null; + public sealed class ContentDefinition + { + [Export] + [Name("cadl")] + [BaseDefinition(CodeRemoteContentDefinition.CodeRemoteContentTypeName)] + public ContentTypeDefinition? CadlContentTypeDefinition => null; - [Export] - [FileExtension(".cadl")] - [ContentType("cadl")] - public FileExtensionToContentTypeDefinition? CadlFileExtensionDefinition => null; - } - - [Export(typeof(ILanguageClient))] - [ContentType("cadl")] - public sealed class LanguageClient : ILanguageClient { - - public string Name => "Cadl"; - public IEnumerable? ConfigurationSections { get; } = new[] { "cadl" }; - - public object? InitializationOptions => null; - public bool ShowNotificationOnInitializeFailed => true; - public IEnumerable FilesToWatch { get; } = new[] { "**/*.cadl", "**/cadl-project.yaml", "**/package.json" }; - public event AsyncEventHandler? StartAsync; - public event AsyncEventHandler? StopAsync { add { } remove { } } // unused - - private readonly IVsFolderWorkspaceService workspaceService; - - [ImportingConstructor] - public LanguageClient([Import] IVsFolderWorkspaceService workspaceService) { - this.workspaceService = workspaceService; + [Export] + [FileExtension(".cadl")] + [ContentType("cadl")] + public FileExtensionToContentTypeDefinition? CadlFileExtensionDefinition => null; } - public async Task ActivateAsync(CancellationToken token) { - await Task.Yield(); + [Export(typeof(ILanguageClient))] + [ContentType("cadl")] + public sealed class LanguageClient : ILanguageClient + { - var workspace = workspaceService.CurrentWorkspace; - var settingsManager = workspace?.GetSettingsManager(); - var settings = settingsManager?.GetAggregatedSettings(SettingsTypes.Generic); - var options = Environment.GetEnvironmentVariable("CADL_SERVER_NODE_OPTIONS"); - var (serverCommand, serverArgs) = resolveCadlServer(settings); - var info = new ProcessStartInfo { - // Use cadl-server on PATH in production - FileName = serverCommand, - Arguments = string.Join(" ", serverArgs), - RedirectStandardInput = true, - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - Environment = { new("NODE_OPTIONS", options) }, - WorkingDirectory = settings?.ScopePath, - }; + public string Name => "Cadl"; + public IEnumerable? ConfigurationSections { get; } = new[] { "cadl" }; + + public object? InitializationOptions => null; + public bool ShowNotificationOnInitializeFailed => true; + public IEnumerable FilesToWatch { get; } = new[] { "**/*.cadl", "**/cadl-project.yaml", "**/package.json" }; + public event AsyncEventHandler? StartAsync; + public event AsyncEventHandler? StopAsync { add { } remove { } } // unused + + private readonly IVsFolderWorkspaceService workspaceService; + + [ImportingConstructor] + public LanguageClient([Import] IVsFolderWorkspaceService workspaceService) + { + this.workspaceService = workspaceService; + } + + public async Task ActivateAsync(CancellationToken token) + { + await Task.Yield(); + + var workspace = workspaceService.CurrentWorkspace; + var settingsManager = workspace?.GetSettingsManager(); + var settings = settingsManager?.GetAggregatedSettings(SettingsTypes.Generic); + var options = Environment.GetEnvironmentVariable("CADL_SERVER_NODE_OPTIONS"); + var (serverCommand, serverArgs) = resolveCadlServer(settings); + var info = new ProcessStartInfo + { + // Use cadl-server on PATH in production + FileName = serverCommand, + Arguments = string.Join(" ", serverArgs), + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + Environment = { new("NODE_OPTIONS", options) }, + WorkingDirectory = settings?.ScopePath, + }; #if DEBUG // Use local build of cadl-server in development (lauched from F5 in VS) @@ -83,21 +89,23 @@ namespace Microsoft.Cadl.VisualStudio { } #endif - var process = Process.Start(info); - process.BeginErrorReadLine(); - process.ErrorDataReceived += (_, e) => LogStderrMessage(e.Data); + var process = Process.Start(info); + process.BeginErrorReadLine(); + process.ErrorDataReceived += (_, e) => LogStderrMessage(e.Data); - return new Connection( - process.StandardOutput.BaseStream, - process.StandardInput.BaseStream); - } + return new Connection( + process.StandardOutput.BaseStream, + process.StandardInput.BaseStream); + } - public async Task OnLoadedAsync() { - var start = StartAsync; - if (start is not null) { - await start.InvokeAsync(this, EventArgs.Empty); - } - } + public async Task OnLoadedAsync() + { + var start = StartAsync; + if (start is not null) + { + await start.InvokeAsync(this, EventArgs.Empty); + } + } #if VS2019 public Task OnServerInitializeFailedAsync(Exception e) { @@ -119,17 +127,20 @@ namespace Microsoft.Cadl.VisualStudio { } #endif - public Task OnServerInitializedAsync() { - return Task.CompletedTask; - } + public Task OnServerInitializedAsync() + { + return Task.CompletedTask; + } - private void LogStderrMessage(string? message) { - if (message is null || message.Length == 0) { - return; - } + private void LogStderrMessage(string? message) + { + if (message is null || message.Length == 0) + { + return; + } - Debugger.Log(0, null, "cadl-server (stderr): " + message); - } + Debugger.Log(0, null, "cadl-server (stderr): " + message); + } #if DEBUG private static bool InDevelopmentMode() { @@ -150,8 +161,9 @@ namespace Microsoft.Cadl.VisualStudio { } #endif - private (string, string[]) resolveCadlServer(IWorkspaceSettings? settings) { - var args = new string[] { "--stdio" }; + private (string, string[]) resolveCadlServer(IWorkspaceSettings? settings) + { + var args = new string[] { "--stdio" }; #if DEBUG // Use local build of cadl-server in development (lauched from F5 in VS) @@ -162,22 +174,27 @@ namespace Microsoft.Cadl.VisualStudio { } #endif - var serverPath = settings?.Property("cadl.cadl-server.path"); - if (serverPath == null) { - return ("cadl-server.cmd", args); - } + var serverPath = settings?.Property("cadl.cadl-server.path"); + if (serverPath == null) + { + return ("cadl-server.cmd", args); + } + + if (!serverPath.EndsWith(".js")) + { + if (File.Exists(serverPath)) + { + var command = serverPath.EndsWith(".cmd") ? serverPath : $"${serverPath}.cmd"; + return (command, args); + } + else + { + serverPath = Path.Combine(serverPath, "cmd/cadl-server.js"); + } + } + return ("node.exe", new string[] { serverPath }.Concat(args).ToArray()); - if (!serverPath.EndsWith(".js")) { - if (File.Exists(serverPath)) { - var command = serverPath.EndsWith(".cmd") ? serverPath : $"${serverPath}.cmd"; - return (command, args); - } else { - serverPath = Path.Combine(serverPath, "cmd/cadl-server.js"); } - } - return ("node.exe", new string[] { serverPath }.Concat(args).ToArray()); - } - } } diff --git a/packages/internal-build-utils/src/dotnet.ts b/packages/internal-build-utils/src/dotnet.ts index 607a3ceee..f521e768b 100644 --- a/packages/internal-build-utils/src/dotnet.ts +++ b/packages/internal-build-utils/src/dotnet.ts @@ -58,3 +58,18 @@ export async function ensureDotnetVersionOrExit() { validatedDotnet = true; } + +/** + * Runs the dotnet formatter. + */ +export async function runDotnetFormat(...args: string[]) { + return runDotnetOrExit([ + "format", + "whitespace", + ".", + `--exclude`, + "**/node_modules/**/*", + "--folder", + ...args, + ]); +}