Format CSharp files: add `dotnet format` to `rush format` (#490)

This commit is contained in:
Timothee Guerin 2022-04-29 09:46:23 -07:00 коммит произвёл GitHub
Родитель 6504701fee
Коммит b3ea529128
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
9 изменённых файлов: 157 добавлений и 96 удалений

Просмотреть файл

@ -8,9 +8,4 @@ insert_final_newline = true
charset = utf-8 charset = utf-8
[*.cs] [*.cs]
csharp_new_line_before_open_brace = none indent_size = 4
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

Просмотреть файл

@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@cadl-lang/internal-build-utils",
"comment": "Add new util `runDotnetFormat`",
"type": "minor"
}
],
"packageName": "@cadl-lang/internal-build-utils"
}

Просмотреть файл

@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "cadl-vs",
"comment": "",
"type": "none"
}
],
"packageName": "cadl-vs"
}

Просмотреть файл

@ -15,6 +15,10 @@ jobs:
versionSpec: 16.x versionSpec: 16.x
displayName: Install Node.js displayName: Install Node.js
- task: UseDotNet@2
inputs:
version: 6.0.x
- script: echo '##vso[task.setvariable variable=CADL_VS_CI_BUILD;]true' - script: echo '##vso[task.setvariable variable=CADL_VS_CI_BUILD;]true'
displayName: Enable official Visual Studio extension build displayName: Enable official Visual Studio extension build

Просмотреть файл

@ -8,6 +8,10 @@ steps:
versionSpec: ${{ parameters.nodeVersion }} versionSpec: ${{ parameters.nodeVersion }}
displayName: Install Node.js displayName: Install Node.js
- task: UseDotNet@2
inputs:
version: 6.0.x
- script: node common/scripts/install-run-rush.js install - script: node common/scripts/install-run-rush.js install
displayName: Install JavaScript Dependencies displayName: Install JavaScript Dependencies

Просмотреть файл

@ -1,7 +1,10 @@
// @ts-check
import { runDotnetFormat } from "../../packages/internal-build-utils/dist/src/index.js";
import { CommandFailedError, runPrettier } from "./helpers.js"; import { CommandFailedError, runPrettier } from "./helpers.js";
try { try {
runPrettier("--list-different"); runPrettier("--list-different");
runDotnetFormat("--verify-no-changes");
} catch (err) { } catch (err) {
if (err instanceof CommandFailedError) { if (err instanceof CommandFailedError) {
console.error( console.error(

Просмотреть файл

@ -1,2 +1,5 @@
// @ts-check
import { runDotnetFormat } from "../../packages/internal-build-utils/dist/src/index.js";
import { runPrettier } from "./helpers.js"; import { runPrettier } from "./helpers.js";
runPrettier("--write"); runPrettier("--write");
await runDotnetFormat();

Просмотреть файл

@ -17,63 +17,69 @@ using Microsoft.VisualStudio.Utilities;
using Task = System.Threading.Tasks.Task; using Task = System.Threading.Tasks.Task;
using System.Linq; using System.Linq;
namespace Microsoft.Cadl.VisualStudio { namespace Microsoft.Cadl.VisualStudio
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] {
[Guid("88b9492f-c019-492c-8aeb-f325a7e4cf23")] [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
public sealed class Package : AsyncPackage { } [Guid("88b9492f-c019-492c-8aeb-f325a7e4cf23")]
public sealed class Package : AsyncPackage { }
public sealed class ContentDefinition { public sealed class ContentDefinition
[Export] {
[Name("cadl")] [Export]
[BaseDefinition(CodeRemoteContentDefinition.CodeRemoteContentTypeName)] [Name("cadl")]
public ContentTypeDefinition? CadlContentTypeDefinition => null; [BaseDefinition(CodeRemoteContentDefinition.CodeRemoteContentTypeName)]
public ContentTypeDefinition? CadlContentTypeDefinition => null;
[Export] [Export]
[FileExtension(".cadl")] [FileExtension(".cadl")]
[ContentType("cadl")] [ContentType("cadl")]
public FileExtensionToContentTypeDefinition? CadlFileExtensionDefinition => null; public FileExtensionToContentTypeDefinition? CadlFileExtensionDefinition => null;
}
[Export(typeof(ILanguageClient))]
[ContentType("cadl")]
public sealed class LanguageClient : ILanguageClient {
public string Name => "Cadl";
public IEnumerable<string>? ConfigurationSections { get; } = new[] { "cadl" };
public object? InitializationOptions => null;
public bool ShowNotificationOnInitializeFailed => true;
public IEnumerable<string> FilesToWatch { get; } = new[] { "**/*.cadl", "**/cadl-project.yaml", "**/package.json" };
public event AsyncEventHandler<EventArgs>? StartAsync;
public event AsyncEventHandler<EventArgs>? StopAsync { add { } remove { } } // unused
private readonly IVsFolderWorkspaceService workspaceService;
[ImportingConstructor]
public LanguageClient([Import] IVsFolderWorkspaceService workspaceService) {
this.workspaceService = workspaceService;
} }
public async Task<Connection?> ActivateAsync(CancellationToken token) { [Export(typeof(ILanguageClient))]
await Task.Yield(); [ContentType("cadl")]
public sealed class LanguageClient : ILanguageClient
{
var workspace = workspaceService.CurrentWorkspace; public string Name => "Cadl";
var settingsManager = workspace?.GetSettingsManager(); public IEnumerable<string>? ConfigurationSections { get; } = new[] { "cadl" };
var settings = settingsManager?.GetAggregatedSettings(SettingsTypes.Generic);
var options = Environment.GetEnvironmentVariable("CADL_SERVER_NODE_OPTIONS"); public object? InitializationOptions => null;
var (serverCommand, serverArgs) = resolveCadlServer(settings); public bool ShowNotificationOnInitializeFailed => true;
var info = new ProcessStartInfo { public IEnumerable<string> FilesToWatch { get; } = new[] { "**/*.cadl", "**/cadl-project.yaml", "**/package.json" };
// Use cadl-server on PATH in production public event AsyncEventHandler<EventArgs>? StartAsync;
FileName = serverCommand, public event AsyncEventHandler<EventArgs>? StopAsync { add { } remove { } } // unused
Arguments = string.Join(" ", serverArgs),
RedirectStandardInput = true, private readonly IVsFolderWorkspaceService workspaceService;
RedirectStandardOutput = true,
RedirectStandardError = true, [ImportingConstructor]
UseShellExecute = false, public LanguageClient([Import] IVsFolderWorkspaceService workspaceService)
CreateNoWindow = true, {
Environment = { new("NODE_OPTIONS", options) }, this.workspaceService = workspaceService;
WorkingDirectory = settings?.ScopePath, }
};
public async Task<Connection?> 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 #if DEBUG
// Use local build of cadl-server in development (lauched from F5 in VS) // Use local build of cadl-server in development (lauched from F5 in VS)
@ -83,21 +89,23 @@ namespace Microsoft.Cadl.VisualStudio {
} }
#endif #endif
var process = Process.Start(info); var process = Process.Start(info);
process.BeginErrorReadLine(); process.BeginErrorReadLine();
process.ErrorDataReceived += (_, e) => LogStderrMessage(e.Data); process.ErrorDataReceived += (_, e) => LogStderrMessage(e.Data);
return new Connection( return new Connection(
process.StandardOutput.BaseStream, process.StandardOutput.BaseStream,
process.StandardInput.BaseStream); process.StandardInput.BaseStream);
} }
public async Task OnLoadedAsync() { public async Task OnLoadedAsync()
var start = StartAsync; {
if (start is not null) { var start = StartAsync;
await start.InvokeAsync(this, EventArgs.Empty); if (start is not null)
} {
} await start.InvokeAsync(this, EventArgs.Empty);
}
}
#if VS2019 #if VS2019
public Task OnServerInitializeFailedAsync(Exception e) { public Task OnServerInitializeFailedAsync(Exception e) {
@ -119,17 +127,20 @@ namespace Microsoft.Cadl.VisualStudio {
} }
#endif #endif
public Task OnServerInitializedAsync() { public Task OnServerInitializedAsync()
return Task.CompletedTask; {
} return Task.CompletedTask;
}
private void LogStderrMessage(string? message) { private void LogStderrMessage(string? message)
if (message is null || message.Length == 0) { {
return; 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 #if DEBUG
private static bool InDevelopmentMode() { private static bool InDevelopmentMode() {
@ -150,8 +161,9 @@ namespace Microsoft.Cadl.VisualStudio {
} }
#endif #endif
private (string, string[]) resolveCadlServer(IWorkspaceSettings? settings) { private (string, string[]) resolveCadlServer(IWorkspaceSettings? settings)
var args = new string[] { "--stdio" }; {
var args = new string[] { "--stdio" };
#if DEBUG #if DEBUG
// Use local build of cadl-server in development (lauched from F5 in VS) // Use local build of cadl-server in development (lauched from F5 in VS)
@ -162,22 +174,27 @@ namespace Microsoft.Cadl.VisualStudio {
} }
#endif #endif
var serverPath = settings?.Property<string>("cadl.cadl-server.path"); var serverPath = settings?.Property<string>("cadl.cadl-server.path");
if (serverPath == null) { if (serverPath == null)
return ("cadl-server.cmd", args); {
} 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());
} }
}
} }

Просмотреть файл

@ -58,3 +58,18 @@ export async function ensureDotnetVersionOrExit() {
validatedDotnet = true; validatedDotnet = true;
} }
/**
* Runs the dotnet formatter.
*/
export async function runDotnetFormat(...args: string[]) {
return runDotnetOrExit([
"format",
"whitespace",
".",
`--exclude`,
"**/node_modules/**/*",
"--folder",
...args,
]);
}