From e3a0e6275d1dfbd788828bd2a70c4eda5d4c85a8 Mon Sep 17 00:00:00 2001 From: Hex Date: Sun, 1 Mar 2026 10:06:14 +0100 Subject: [PATCH 1/5] Added --framework arg to "dotnet format' to set TFM - Alias -f is set - does only work without --folder --- .../dotnet-format/CodeFormatter.cs | 9 +- .../Commands/FormatCommandCommon.cs | 12 +++ .../Commands/FormatWhitespaceCommand.cs | 11 +++ .../dotnet-format/FormatOptions.cs | 6 +- src/BuiltInTools/dotnet-format/Resources.resx | 6 ++ .../dotnet-format/Utilities/DotNetHelper.cs | 10 +- .../Workspaces/MSBuildWorkspaceLoader.cs | 8 +- .../dotnet-format/xlf/Resources.cs.xlf | 10 ++ .../dotnet-format/xlf/Resources.de.xlf | 10 ++ .../dotnet-format/xlf/Resources.es.xlf | 10 ++ .../dotnet-format/xlf/Resources.fr.xlf | 10 ++ .../dotnet-format/xlf/Resources.it.xlf | 10 ++ .../dotnet-format/xlf/Resources.ja.xlf | 10 ++ .../dotnet-format/xlf/Resources.ko.xlf | 10 ++ .../dotnet-format/xlf/Resources.pl.xlf | 10 ++ .../dotnet-format/xlf/Resources.pt-BR.xlf | 10 ++ .../dotnet-format/xlf/Resources.ru.xlf | 10 ++ .../dotnet-format/xlf/Resources.tr.xlf | 10 ++ .../dotnet-format/xlf/Resources.zh-Hans.xlf | 10 ++ .../dotnet-format/xlf/Resources.zh-Hant.xlf | 10 ++ .../CodeFormatterTests.cs | 3 +- .../Formatters/AbstractFormatterTests.cs | 3 +- .../Formatters/FormattedFilesTests.cs | 3 +- test/dotnet-format.UnitTests/ProgramTests.cs | 97 +++++++++++++++++++ 24 files changed, 286 insertions(+), 12 deletions(-) diff --git a/src/BuiltInTools/dotnet-format/CodeFormatter.cs b/src/BuiltInTools/dotnet-format/CodeFormatter.cs index e96f713593a1..5f7ee50f8651 100644 --- a/src/BuiltInTools/dotnet-format/CodeFormatter.cs +++ b/src/BuiltInTools/dotnet-format/CodeFormatter.cs @@ -38,7 +38,7 @@ public static async Task FormatWorkspaceAsync( using var workspace = formatOptions.WorkspaceType == WorkspaceType.Folder ? OpenFolderWorkspace(formatOptions.WorkspaceFilePath, formatOptions.FileMatcher) - : await OpenMSBuildWorkspaceAsync(formatOptions.WorkspaceFilePath, formatOptions.WorkspaceType, formatOptions.NoRestore, formatOptions.FixCategory != FixCategory.Whitespace, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken).ConfigureAwait(false); + : await OpenMSBuildWorkspaceAsync(formatOptions.WorkspaceFilePath, formatOptions.WorkspaceType, formatOptions.NoRestore, formatOptions.FixCategory != FixCategory.Whitespace, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken, formatOptions.TargetFramework).ConfigureAwait(false); if (workspace is null) { @@ -126,16 +126,17 @@ private static Workspace OpenFolderWorkspace(string workspacePath, SourceFileMat string? binaryLogPath, bool logWorkspaceWarnings, ILogger logger, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + string? targetFramework = null) { if (requiresSemantics && !noRestore && - await DotNetHelper.PerformRestoreAsync(solutionOrProjectPath, logger) != 0) + await DotNetHelper.PerformRestoreAsync(solutionOrProjectPath, logger, targetFramework) != 0) { throw new Exception("Restore operation failed."); } - return await MSBuildWorkspaceLoader.LoadAsync(solutionOrProjectPath, workspaceType, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken); + return await MSBuildWorkspaceLoader.LoadAsync(solutionOrProjectPath, workspaceType, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken, targetFramework); } private static async Task RunCodeFormattersAsync( diff --git a/src/BuiltInTools/dotnet-format/Commands/FormatCommandCommon.cs b/src/BuiltInTools/dotnet-format/Commands/FormatCommandCommon.cs index 269da41d2d41..d0035d6fbb13 100644 --- a/src/BuiltInTools/dotnet-format/Commands/FormatCommandCommon.cs +++ b/src/BuiltInTools/dotnet-format/Commands/FormatCommandCommon.cs @@ -34,6 +34,11 @@ internal static class FormatCommandCommon { Description = Resources.Doesnt_execute_an_implicit_restore_before_formatting, }; + internal static readonly Option FrameworkOption = new Option("--framework", "-f") + { + HelpName = "framework", + Description = Resources.The_target_framework_to_use_when_loading_the_workspace, + }; internal static readonly Option VerifyNoChanges = new("--verify-no-changes") { Description = Resources.Verify_no_formatting_changes_would_be_performed_Terminates_with_a_non_zero_exit_code_if_any_files_would_have_been_formatted, @@ -115,6 +120,7 @@ public static void AddCommonOptions(this Command command) { command.Arguments.Add(SlnOrProjectArgument); command.Options.Add(NoRestoreOption); + command.Options.Add(FrameworkOption); command.Options.Add(VerifyNoChanges); command.Options.Add(IncludeOption); command.Options.Add(ExcludeOption); @@ -211,6 +217,12 @@ public static FormatOptions ParseCommonOptions(this ParseResult parseResult, For } } + if (parseResult.GetResult(FrameworkOption) is not null && + parseResult.GetValue(FrameworkOption) is string { Length: > 0 } framework) + { + formatOptions = formatOptions with { TargetFramework = framework }; + } + return formatOptions; static void HandleStandardInput(ILogger logger, ref string[] include, ref string[] exclude) diff --git a/src/BuiltInTools/dotnet-format/Commands/FormatWhitespaceCommand.cs b/src/BuiltInTools/dotnet-format/Commands/FormatWhitespaceCommand.cs index 824038740604..40cf5379fe9b 100644 --- a/src/BuiltInTools/dotnet-format/Commands/FormatWhitespaceCommand.cs +++ b/src/BuiltInTools/dotnet-format/Commands/FormatWhitespaceCommand.cs @@ -22,6 +22,7 @@ internal static Command GetCommand() command.AddCommonOptions(); command.Validators.Add(EnsureFolderNotSpecifiedWithNoRestore); command.Validators.Add(EnsureFolderNotSpecifiedWhenLoggingBinlog); + command.Validators.Add(EnsureFolderNotSpecifiedWithFramework); command.Action = s_formattingHandler; return command; } @@ -46,6 +47,16 @@ internal static void EnsureFolderNotSpecifiedWhenLoggingBinlog(CommandResult sym } } + internal static void EnsureFolderNotSpecifiedWithFramework(CommandResult symbolResult) + { + var folder = symbolResult.GetValue(FolderOption); + var framework = symbolResult.GetResult(FrameworkOption); + if (folder && framework is not null && !framework.Implicit) + { + symbolResult.AddError(Resources.Cannot_specify_the_folder_option_with_framework); + } + } + private class FormatWhitespaceHandler : AsynchronousCommandLineAction { public override async Task InvokeAsync(ParseResult parseResult, CancellationToken cancellationToken) diff --git a/src/BuiltInTools/dotnet-format/FormatOptions.cs b/src/BuiltInTools/dotnet-format/FormatOptions.cs index 7db0069bb474..0d291512680d 100644 --- a/src/BuiltInTools/dotnet-format/FormatOptions.cs +++ b/src/BuiltInTools/dotnet-format/FormatOptions.cs @@ -22,7 +22,8 @@ internal record FormatOptions( SourceFileMatcher FileMatcher, string? ReportPath, string? BinaryLogPath, - bool IncludeGeneratedFiles) + bool IncludeGeneratedFiles, + string? TargetFramework) { public static FormatOptions Instance = new( WorkspaceFilePath: null!, // must be supplied @@ -39,6 +40,7 @@ internal record FormatOptions( FileMatcher: SourceFileMatcher.CreateMatcher(Array.Empty(), Array.Empty()), ReportPath: null, BinaryLogPath: null, - IncludeGeneratedFiles: false); + IncludeGeneratedFiles: false, + TargetFramework: null); } } diff --git a/src/BuiltInTools/dotnet-format/Resources.resx b/src/BuiltInTools/dotnet-format/Resources.resx index ec627d90ce53..b54bf224c6a8 100644 --- a/src/BuiltInTools/dotnet-format/Resources.resx +++ b/src/BuiltInTools/dotnet-format/Resources.resx @@ -330,6 +330,12 @@ Cannot specify the '--folder' option when writing a binary log. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + + + Cannot specify the '--folder' option with '--framework'. + PROJECT | SOLUTION diff --git a/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs b/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs index 6c8d18544f9b..8ec73289e38b 100644 --- a/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs +++ b/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs @@ -7,9 +7,15 @@ namespace Microsoft.CodeAnalysis.Tools.Utilities { internal static class DotNetHelper { - public static async Task PerformRestoreAsync(string workspaceFilePath, ILogger logger) + internal static string BuildRestoreArguments(string workspaceFilePath, string? targetFramework) { - var processInfo = ProcessRunner.CreateProcess("dotnet", $"restore \"{workspaceFilePath}\"", captureOutput: true, displayWindow: false); + var frameworkArg = targetFramework is not null ? $" -p:TargetFramework={targetFramework}" : string.Empty; + return $"restore \"{workspaceFilePath}\"{frameworkArg}"; + } + + public static async Task PerformRestoreAsync(string workspaceFilePath, ILogger logger, string? targetFramework = null) + { + var processInfo = ProcessRunner.CreateProcess("dotnet", BuildRestoreArguments(workspaceFilePath, targetFramework), captureOutput: true, displayWindow: false); var restoreResult = await processInfo.Result; logger.LogDebug(string.Join(Environment.NewLine, restoreResult.OutputLines)); diff --git a/src/BuiltInTools/dotnet-format/Workspaces/MSBuildWorkspaceLoader.cs b/src/BuiltInTools/dotnet-format/Workspaces/MSBuildWorkspaceLoader.cs index 1ece23a46734..fac3978c1f6e 100644 --- a/src/BuiltInTools/dotnet-format/Workspaces/MSBuildWorkspaceLoader.cs +++ b/src/BuiltInTools/dotnet-format/Workspaces/MSBuildWorkspaceLoader.cs @@ -18,7 +18,8 @@ internal static class MSBuildWorkspaceLoader string? binaryLogPath, bool logWorkspaceWarnings, ILogger logger, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + string? targetFramework = null) { var properties = new Dictionary(StringComparer.Ordinal) { @@ -28,6 +29,11 @@ internal static class MSBuildWorkspaceLoader { "AlwaysCompileMarkupFilesInSeparateDomain", bool.FalseString }, }; + if (targetFramework is not null) + { + properties["TargetFramework"] = targetFramework; + } + var workspace = MSBuildWorkspace.Create(properties); Build.Framework.ILogger? binlog = null; diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.cs.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.cs.xlf index f3a21d499b4d..7cfc748737eb 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.cs.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.cs.xlf @@ -62,6 +62,11 @@ Při spouštění analyzátorů není možné zadat možnost --folder. + + Cannot specify the '--folder' option with '--framework'. + Není možné zadat možnost --folder s parametrem --framework. + + Cannot specify the '--folder' option with '--no-restore'. Není možné zadat možnost --folder s parametrem --no-restore. @@ -352,6 +357,11 @@ Naformátoval se soubor kódu {0}. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + Cílová architektura (TFM), která se má použít při načítání pracovního prostoru. Omezuje obnovení a analýzu pouze na zadanou architekturu. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. Nepovedlo se opravit {0}. Oprava kódu {1} nevrátila akci Opravit vše. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.de.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.de.xlf index 40a49347e259..350a307398d0 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.de.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.de.xlf @@ -62,6 +62,11 @@ Die Option „--Ordner“ kann beim Ausführen von Analysetools nicht angegeben werden. + + Cannot specify the '--folder' option with '--framework'. + Die Option „--folder" kann nicht mit „--framework" angegeben werden. + + Cannot specify the '--folder' option with '--no-restore'. Die Option „--Ordner“ kann nicht mit „--keine-Wiederherstellung“ angegeben werden. @@ -352,6 +357,11 @@ Codedatei "{0}" wurde formatiert. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + Das Zielframework (TFM), das beim Laden des Arbeitsbereichs verwendet werden soll. Beschränkt Wiederherstellung und Analyse nur auf das angegebene Framework. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. {0} kann nicht behoben werden. Codefix {1} hat keine Aktion „Alle korrigieren“ zurückgegeben. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.es.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.es.xlf index 775cdef7cdf3..af8dbf6e5258 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.es.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.es.xlf @@ -62,6 +62,11 @@ No se puede especificar la opción "--folder" al ejecutar analizadores. + + Cannot specify the '--folder' option with '--framework'. + No se puede especificar la opción '--folder' con '--framework'. + + Cannot specify the '--folder' option with '--no-restore'. No se puede especificar la opción "--folder" con "--no-restore". @@ -352,6 +357,11 @@ Archivo de código "{0}" con formato aplicado. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + El marco de destino (TFM) que se utilizará al cargar el área de trabajo. Restringe la restauración y el análisis solo al marco especificado. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. No se puede corregir {0}. La corrección de código {1} no devolvió ninguna acción Corregir todo. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf index c29da3ec3b44..dfefd3bba47d 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf @@ -62,6 +62,11 @@ Impossible de spécifier l’option « --folder » lors de l’exécution des analyseurs. + + Cannot specify the '--folder' option with '--framework'. + Impossible de spécifier l'option « --folder » avec « --framework ». + + Cannot specify the '--folder' option with '--no-restore'. Impossible de spécifier l’option « --folder » avec « --no-restore ». @@ -352,6 +357,11 @@ Fichier de code '{0}' mis en forme. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + Le framework cible (TFM) à utiliser lors du chargement de l'espace de travail. Restreint la restauration et l'analyse au framework spécifié uniquement. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. Impossible de corriger {0}. Le correctif de code {1} n’a pas retourné d’action Corriger tout. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.it.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.it.xlf index 2aeb29336f18..4294df19e7eb 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.it.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.it.xlf @@ -62,6 +62,11 @@ Impossibile specificare l'opzione '--folder' durante l'esecuzione degli analizzatori. + + Cannot specify the '--folder' option with '--framework'. + Non è possibile specificare l'opzione '--folder' con '--framework'. + + Cannot specify the '--folder' option with '--no-restore'. Non è possibile specificare l'opzione '--folder' con '--no-restore'. @@ -352,6 +357,11 @@ Il file di codice '{0}' è stato formattato. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + Il framework di destinazione (TFM) da usare durante il caricamento dell'area di lavoro. Limita il ripristino e l'analisi solo al framework specificato. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. Impossibile correggere {0}. La correzione del codice {1} non ha restituito un'azione Correggi tutto. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.ja.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.ja.xlf index 4cf225955ceb..528ac9cfe81e 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.ja.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.ja.xlf @@ -62,6 +62,11 @@ アナライザーの実行時に '--folder' オプションを指定することはできません。 + + Cannot specify the '--folder' option with '--framework'. + '--framework' では '--folder' オプションを指定できません。 + + Cannot specify the '--folder' option with '--no-restore'. '--folder' オプションを '--no-restore' と共に指定することはできません。 @@ -352,6 +357,11 @@ コード ファイル '{0}' がフォーマットされました。 + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + ワークスペースの読み込み時に使用するターゲット フレームワーク (TFM)。復元と分析を指定されたフレームワークのみに制限します。 + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. {0} を修正できません。コード修正 {1} は、[すべて修正] アクションを返しませんでした。 diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.ko.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.ko.xlf index 5fe1286052e1..537a706825c5 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.ko.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.ko.xlf @@ -62,6 +62,11 @@ 분석기를 실행할 때는 '--folder' 옵션을 지정할 수 없습니다. + + Cannot specify the '--folder' option with '--framework'. + '--framework'와 함께 '--folder' 옵션을 지정할 수 없습니다. + + Cannot specify the '--folder' option with '--no-restore'. '--no-restore'와 함께 '--folder' 옵션을 지정할 수 없습니다. @@ -352,6 +357,11 @@ 코드 파일 '{0}'의 서식을 지정했습니다. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + 작업 영역을 로드할 때 사용할 대상 프레임워크(TFM)입니다. 복원 및 분석을 지정된 프레임워크로만 제한합니다. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. {0}을(를) 수정할 수 없습니다. 코드 수정 {1}에서 모두 수정 작업을 반환하지 않았습니다. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.pl.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.pl.xlf index 37b8a4e1f484..a7a2ce64eeb9 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.pl.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.pl.xlf @@ -62,6 +62,11 @@ Nie można określić opcji „--folder” podczas uruchamiania analizatorów. + + Cannot specify the '--folder' option with '--framework'. + Nie można określić opcji „--folder" razem z parametrem „--framework". + + Cannot specify the '--folder' option with '--no-restore'. Nie można określić opcji „--folder” z parametrem „--no-restore”. @@ -352,6 +357,11 @@ Sformatowano plik kodu „{0}”. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + Docelowa platforma (TFM) do użycia podczas ładowania obszaru roboczego. Ogranicza przywracanie i analizę tylko do określonej platformy. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. Nie można naprawić kodu {0}. Poprawka kodu {1} nie zwróciła akcji Napraw wszystko. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.pt-BR.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.pt-BR.xlf index b57c3e3b44f4..cf6aa503dc02 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.pt-BR.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.pt-BR.xlf @@ -62,6 +62,11 @@ Não é possível especificar a opção '--folder' ao executar analisadores. + + Cannot specify the '--folder' option with '--framework'. + Não é possível especificar a opção '--folder' com '--framework'. + + Cannot specify the '--folder' option with '--no-restore'. Não é possível especificar a opção '--folder' com '--no-restore'. @@ -352,6 +357,11 @@ Arquivo de código '{0}' formatado. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + A estrutura de destino (TFM) a ser usada ao carregar o espaço de trabalho. Restringe a restauração e a análise somente à estrutura especificada. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. Não é possível corrigir {0}. A correção de código {1} não retornou uma ação "Corrigir tudo". diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.ru.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.ru.xlf index 876497b11b1e..83e77966c890 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.ru.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.ru.xlf @@ -62,6 +62,11 @@ Невозможно указать параметр "--folder" при запуске анализаторов. + + Cannot specify the '--folder' option with '--framework'. + Невозможно указать параметр "--folder" с "--framework". + + Cannot specify the '--folder' option with '--no-restore'. Невозможно указать параметр "--folder" с "--no-restore". @@ -352,6 +357,11 @@ Отформатированный файл кода "{0}". + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + Целевая платформа (TFM), используемая при загрузке рабочей области. Ограничивает восстановление и анализ только указанной платформой. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. Не удалось исправить {0}. Исправление кода {1} не возвратило действие "Исправить все". diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.tr.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.tr.xlf index c20259208904..989cde48277b 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.tr.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.tr.xlf @@ -62,6 +62,11 @@ Çözümleyiciler çalıştırılırken '--folder' seçeneği belirtilemiyor. + + Cannot specify the '--folder' option with '--framework'. + '--framework' seçeneği ile '--folder' seçeneği belirtilemiyor. + + Cannot specify the '--folder' option with '--no-restore'. '--no-restore' seçeneği ile '--folder' seçeneği belirtilemiyor. @@ -352,6 +357,11 @@ '{0}' kod dosyası biçimlendirildi. + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + Çalışma alanı yüklenirken kullanılacak hedef çerçeve (TFM). Geri yükleme ve analizi yalnızca belirtilen çerçeveyle sınırlandırır. + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. {0} düzeltilemiyor. Kod düzeltmesi ({1}), Tümünü Düzelt eylemi döndürmedi. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hans.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hans.xlf index 88482781e59c..746fda34fec7 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hans.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hans.xlf @@ -62,6 +62,11 @@ 运行分析器时无法指定 '--folder' 选项。 + + Cannot specify the '--folder' option with '--framework'. + 无法使用 '--framework' 指定 '--folder' 选项。 + + Cannot specify the '--folder' option with '--no-restore'. 无法使用 '--no-restore' 指定 '--folder' 选项。 @@ -352,6 +357,11 @@ 已将代码文件“{0}”格式化。 + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + 加载工作区时要使用的目标框架 (TFM)。将还原和分析限制为仅指定的框架。 + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. 无法修复 {0}。代码修复 {1} 未返回全部修复操作。 diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hant.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hant.xlf index 10d7cfa16699..a9cd85457190 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hant.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hant.xlf @@ -62,6 +62,11 @@ 執行分析器時無法指定 '--folder' 選項。 + + Cannot specify the '--folder' option with '--framework'. + 無法指定 '--folder' 選項搭配 '--framework'。 + + Cannot specify the '--folder' option with '--no-restore'. 無法指定 '--folder' 選項搭配 '--no-restore'。 @@ -352,6 +357,11 @@ 正在將程式碼檔案 '{0}' 格式化。 + + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. + 載入工作區時使用的目標架構 (TFM)。將還原和分析限制為僅指定的架構。 + + Unable to fix {0}. Code fix {1} didn't return a Fix All action. 無法修正 {0}。程式碼修正 {1} 未傳回全部修正動作。 diff --git a/test/dotnet-format.UnitTests/CodeFormatterTests.cs b/test/dotnet-format.UnitTests/CodeFormatterTests.cs index 235aab421456..8cc7da220915 100644 --- a/test/dotnet-format.UnitTests/CodeFormatterTests.cs +++ b/test/dotnet-format.UnitTests/CodeFormatterTests.cs @@ -696,7 +696,8 @@ internal async Task TestFormatWorkspaceAsync( fileMatcher, ReportPath: string.Empty, IncludeGeneratedFiles: includeGenerated, - BinaryLogPath: null); + BinaryLogPath: null, + TargetFramework: null); var formatResult = await CodeFormatter.FormatWorkspaceAsync(formatOptions, logger, CancellationToken.None); Environment.CurrentDirectory = currentDirectory; diff --git a/test/dotnet-format.UnitTests/Formatters/AbstractFormatterTests.cs b/test/dotnet-format.UnitTests/Formatters/AbstractFormatterTests.cs index 324c091956cb..29c24ac8dbf0 100644 --- a/test/dotnet-format.UnitTests/Formatters/AbstractFormatterTests.cs +++ b/test/dotnet-format.UnitTests/Formatters/AbstractFormatterTests.cs @@ -230,7 +230,8 @@ private protected async Task AssertCodeChangedAsync( fileMatcher, ReportPath: string.Empty, IncludeGeneratedFiles: false, - BinaryLogPath: null); + BinaryLogPath: null, + TargetFramework: null); var pathsToFormat = GetOnlyFileToFormat(solution); diff --git a/test/dotnet-format.UnitTests/Formatters/FormattedFilesTests.cs b/test/dotnet-format.UnitTests/Formatters/FormattedFilesTests.cs index a90554bbe170..7b615d43624b 100644 --- a/test/dotnet-format.UnitTests/Formatters/FormattedFilesTests.cs +++ b/test/dotnet-format.UnitTests/Formatters/FormattedFilesTests.cs @@ -72,7 +72,8 @@ private async Task> TestFormattedFiles(string testCode) fileMatcher, ReportPath: string.Empty, IncludeGeneratedFiles: false, - BinaryLogPath: null); + BinaryLogPath: null, + TargetFramework: null); var pathsToFormat = GetOnlyFileToFormat(solution); diff --git a/test/dotnet-format.UnitTests/ProgramTests.cs b/test/dotnet-format.UnitTests/ProgramTests.cs index c82189a13b09..f64863e7cef1 100644 --- a/test/dotnet-format.UnitTests/ProgramTests.cs +++ b/test/dotnet-format.UnitTests/ProgramTests.cs @@ -4,6 +4,8 @@ #nullable disable using Microsoft.CodeAnalysis.Tools.Commands; +using Microsoft.CodeAnalysis.Tools.Tests.Utilities; +using ProductionDotNetHelper = Microsoft.CodeAnalysis.Tools.Utilities.DotNetHelper; namespace Microsoft.CodeAnalysis.Tools.Tests { @@ -246,5 +248,100 @@ public void CommandLine_Diagnostics_DoesNotFailIfMultipleDiagnosticAreSpecified( // Assert Assert.Empty(result.Errors); } + + [Fact] + public void CommandLine_FrameworkOption_IsParsedCorrectly() + { + // Arrange + var sut = RootFormatCommand.GetCommand(); + + // Act + var result = sut.Parse(new[] { "--framework", "net8.0" }); + + // Assert + Assert.Empty(result.Errors); + Assert.Equal("net8.0", result.GetValue(FormatCommandCommon.FrameworkOption)); + } + + [Fact] + public void CommandLine_FrameworkOption_ShortAlias_IsParsedCorrectly() + { + // Arrange + var sut = RootFormatCommand.GetCommand(); + + // Act + var result = sut.Parse(new[] { "-f", "net8.0" }); + + // Assert + Assert.Empty(result.Errors); + Assert.Equal("net8.0", result.GetValue(FormatCommandCommon.FrameworkOption)); + } + + [Fact] + public void CommandLine_FolderValidation_FailsIfFrameworkSpecified() + { + // Arrange + var sut = RootFormatCommand.GetCommand(); + + // Act + var result = sut.Parse(new[] { "whitespace", "--folder", "--framework", "net8.0" }); + + // Assert + Assert.Single(result.Errors); + } + + [Fact] + public void ParseCommonOptions_FrameworkOption_SetsTargetFramework() + { + // Arrange + var sut = RootFormatCommand.GetCommand(); + var result = sut.Parse(new[] { "--framework", "net8.0" }); + var logger = new TestLogger(); + + // Act + var formatOptions = result.ParseCommonOptions(FormatOptions.Instance, logger); + + // Assert + Assert.Equal("net8.0", formatOptions.TargetFramework); + } + + [Fact] + public void ParseCommonOptions_NoFrameworkOption_LeavesTargetFrameworkNull() + { + // Arrange + var sut = RootFormatCommand.GetCommand(); + var result = sut.Parse(Array.Empty()); + var logger = new TestLogger(); + + // Act + var formatOptions = result.ParseCommonOptions(FormatOptions.Instance, logger); + + // Assert + Assert.Null(formatOptions.TargetFramework); + } + + [Fact] + public void DotNetHelper_BuildRestoreArguments_WithoutFramework_OmitsProperty() + { + var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj", targetFramework: null); + + Assert.Equal("restore \"my.csproj\"", args); + } + + [Fact] + public void DotNetHelper_BuildRestoreArguments_WithFramework_UsesMSBuildProperty() + { + var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj", targetFramework: "net8.0"); + + Assert.Equal("restore \"my.csproj\" -p:TargetFramework=net8.0", args); + } + + [Fact] + public void DotNetHelper_BuildRestoreArguments_WithFramework_DoesNotUseDashDashFramework() + { + var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj", targetFramework: "net8.0"); + + Assert.DoesNotContain("--framework", args); + } } } From 693f1c55cdcdde45b37845a3efc28f8d5241b9d6 Mon Sep 17 00:00:00 2001 From: Hex Date: Sun, 1 Mar 2026 14:04:37 +0100 Subject: [PATCH 2/5] Fix dotnet-format restore failing when --framework is specified Passing a target framework to `dotnet restore` causes the dotnet CLI in SDK 10.0.x to emit a bare --framework switch in its internal MSBuild.dll invocation. MSBuild does not recognise that switch and exits with MSB1001. The framework argument is unnecessary for restore: dotnet restore on a solution or project already restores all target frameworks. Framework filtering is handled downstream by MSBuildWorkspaceLoader, which sets the TargetFramework MSBuild property when opening the workspace. --- .../dotnet-format/CodeFormatter.cs | 4 ++-- .../dotnet-format/Utilities/DotNetHelper.cs | 11 +++++----- test/dotnet-format.UnitTests/ProgramTests.cs | 20 ++++++------------- 3 files changed, 13 insertions(+), 22 deletions(-) diff --git a/src/BuiltInTools/dotnet-format/CodeFormatter.cs b/src/BuiltInTools/dotnet-format/CodeFormatter.cs index 5f7ee50f8651..b5144626c7cd 100644 --- a/src/BuiltInTools/dotnet-format/CodeFormatter.cs +++ b/src/BuiltInTools/dotnet-format/CodeFormatter.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Immutable; @@ -131,7 +131,7 @@ private static Workspace OpenFolderWorkspace(string workspacePath, SourceFileMat { if (requiresSemantics && !noRestore && - await DotNetHelper.PerformRestoreAsync(solutionOrProjectPath, logger, targetFramework) != 0) + await DotNetHelper.PerformRestoreAsync(solutionOrProjectPath, logger) != 0) { throw new Exception("Restore operation failed."); } diff --git a/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs b/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs index 8ec73289e38b..787c96efec18 100644 --- a/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs +++ b/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Extensions.Logging; @@ -7,15 +7,14 @@ namespace Microsoft.CodeAnalysis.Tools.Utilities { internal static class DotNetHelper { - internal static string BuildRestoreArguments(string workspaceFilePath, string? targetFramework) + internal static string BuildRestoreArguments(string workspaceFilePath) { - var frameworkArg = targetFramework is not null ? $" -p:TargetFramework={targetFramework}" : string.Empty; - return $"restore \"{workspaceFilePath}\"{frameworkArg}"; + return $"restore \"{workspaceFilePath}\""; } - public static async Task PerformRestoreAsync(string workspaceFilePath, ILogger logger, string? targetFramework = null) + public static async Task PerformRestoreAsync(string workspaceFilePath, ILogger logger) { - var processInfo = ProcessRunner.CreateProcess("dotnet", BuildRestoreArguments(workspaceFilePath, targetFramework), captureOutput: true, displayWindow: false); + var processInfo = ProcessRunner.CreateProcess("dotnet", BuildRestoreArguments(workspaceFilePath), captureOutput: true, displayWindow: false); var restoreResult = await processInfo.Result; logger.LogDebug(string.Join(Environment.NewLine, restoreResult.OutputLines)); diff --git a/test/dotnet-format.UnitTests/ProgramTests.cs b/test/dotnet-format.UnitTests/ProgramTests.cs index f64863e7cef1..e47b5a8b4977 100644 --- a/test/dotnet-format.UnitTests/ProgramTests.cs +++ b/test/dotnet-format.UnitTests/ProgramTests.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -321,27 +321,19 @@ public void ParseCommonOptions_NoFrameworkOption_LeavesTargetFrameworkNull() } [Fact] - public void DotNetHelper_BuildRestoreArguments_WithoutFramework_OmitsProperty() + public void DotNetHelper_BuildRestoreArguments_ProducesRestoreCommand() { - var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj", targetFramework: null); + var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj"); Assert.Equal("restore \"my.csproj\"", args); } [Fact] - public void DotNetHelper_BuildRestoreArguments_WithFramework_UsesMSBuildProperty() + public void DotNetHelper_BuildRestoreArguments_DoesNotPassFrameworkToRestore() { - var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj", targetFramework: "net8.0"); + var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj"); - Assert.Equal("restore \"my.csproj\" -p:TargetFramework=net8.0", args); - } - - [Fact] - public void DotNetHelper_BuildRestoreArguments_WithFramework_DoesNotUseDashDashFramework() - { - var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj", targetFramework: "net8.0"); - - Assert.DoesNotContain("--framework", args); + Assert.DoesNotContain("framework", args, StringComparison.OrdinalIgnoreCase); } } } From 61e6c2da5916d7a5f4306c49d6e6b9b9a7ff16b4 Mon Sep 17 00:00:00 2001 From: Hex Date: Mon, 2 Mar 2026 21:00:22 +0100 Subject: [PATCH 3/5] Removed BuildRestoreArguments and unwanted translations --- .../dotnet-format/Utilities/DotNetHelper.cs | 6 +----- .../dotnet-format/xlf/Resources.cs.xlf | 4 ++-- .../dotnet-format/xlf/Resources.de.xlf | 4 ++-- .../dotnet-format/xlf/Resources.es.xlf | 4 ++-- .../dotnet-format/xlf/Resources.fr.xlf | 4 ++-- .../dotnet-format/xlf/Resources.it.xlf | 4 ++-- .../dotnet-format/xlf/Resources.ja.xlf | 4 ++-- .../dotnet-format/xlf/Resources.ko.xlf | 4 ++-- .../dotnet-format/xlf/Resources.pl.xlf | 4 ++-- .../dotnet-format/xlf/Resources.pt-BR.xlf | 4 ++-- .../dotnet-format/xlf/Resources.ru.xlf | 4 ++-- .../dotnet-format/xlf/Resources.tr.xlf | 4 ++-- .../dotnet-format/xlf/Resources.zh-Hans.xlf | 4 ++-- .../dotnet-format/xlf/Resources.zh-Hant.xlf | 4 ++-- test/dotnet-format.UnitTests/ProgramTests.cs | 16 ---------------- 15 files changed, 27 insertions(+), 47 deletions(-) diff --git a/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs b/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs index 787c96efec18..394e58ad2585 100644 --- a/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs +++ b/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs @@ -7,14 +7,10 @@ namespace Microsoft.CodeAnalysis.Tools.Utilities { internal static class DotNetHelper { - internal static string BuildRestoreArguments(string workspaceFilePath) - { - return $"restore \"{workspaceFilePath}\""; - } public static async Task PerformRestoreAsync(string workspaceFilePath, ILogger logger) { - var processInfo = ProcessRunner.CreateProcess("dotnet", BuildRestoreArguments(workspaceFilePath), captureOutput: true, displayWindow: false); + var processInfo = ProcessRunner.CreateProcess("dotnet", $"restore \"{workspaceFilePath}\"", captureOutput: true, displayWindow: false); var restoreResult = await processInfo.Result; logger.LogDebug(string.Join(Environment.NewLine, restoreResult.OutputLines)); diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.cs.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.cs.xlf index 7cfc748737eb..bff1473b47a3 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.cs.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.cs.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - Není možné zadat možnost --folder s parametrem --framework. + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - Cílová architektura (TFM), která se má použít při načítání pracovního prostoru. Omezuje obnovení a analýzu pouze na zadanou architekturu. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.de.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.de.xlf index 350a307398d0..3076b304bc15 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.de.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.de.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - Die Option „--folder" kann nicht mit „--framework" angegeben werden. + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - Das Zielframework (TFM), das beim Laden des Arbeitsbereichs verwendet werden soll. Beschränkt Wiederherstellung und Analyse nur auf das angegebene Framework. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.es.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.es.xlf index af8dbf6e5258..66c03769e6de 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.es.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.es.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - No se puede especificar la opción '--folder' con '--framework'. + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - El marco de destino (TFM) que se utilizará al cargar el área de trabajo. Restringe la restauración y el análisis solo al marco especificado. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf index dfefd3bba47d..9c73f26606c8 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - Impossible de spécifier l'option « --folder » avec « --framework ». + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - Le framework cible (TFM) à utiliser lors du chargement de l'espace de travail. Restreint la restauration et l'analyse au framework spécifié uniquement. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.it.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.it.xlf index 4294df19e7eb..fffc9751af7b 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.it.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.it.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - Non è possibile specificare l'opzione '--folder' con '--framework'. + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - Il framework di destinazione (TFM) da usare durante il caricamento dell'area di lavoro. Limita il ripristino e l'analisi solo al framework specificato. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.ja.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.ja.xlf index 528ac9cfe81e..94261f079d21 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.ja.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.ja.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - '--framework' では '--folder' オプションを指定できません。 + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - ワークスペースの読み込み時に使用するターゲット フレームワーク (TFM)。復元と分析を指定されたフレームワークのみに制限します。 + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.ko.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.ko.xlf index 537a706825c5..82065400c1b8 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.ko.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.ko.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - '--framework'와 함께 '--folder' 옵션을 지정할 수 없습니다. + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - 작업 영역을 로드할 때 사용할 대상 프레임워크(TFM)입니다. 복원 및 분석을 지정된 프레임워크로만 제한합니다. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.pl.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.pl.xlf index a7a2ce64eeb9..b9d39f2b54cb 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.pl.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.pl.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - Nie można określić opcji „--folder" razem z parametrem „--framework". + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - Docelowa platforma (TFM) do użycia podczas ładowania obszaru roboczego. Ogranicza przywracanie i analizę tylko do określonej platformy. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.pt-BR.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.pt-BR.xlf index cf6aa503dc02..55d09806aade 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.pt-BR.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.pt-BR.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - Não é possível especificar a opção '--folder' com '--framework'. + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - A estrutura de destino (TFM) a ser usada ao carregar o espaço de trabalho. Restringe a restauração e a análise somente à estrutura especificada. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.ru.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.ru.xlf index 83e77966c890..01b87364661c 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.ru.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.ru.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - Невозможно указать параметр "--folder" с "--framework". + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - Целевая платформа (TFM), используемая при загрузке рабочей области. Ограничивает восстановление и анализ только указанной платформой. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.tr.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.tr.xlf index 989cde48277b..591a716f4bb5 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.tr.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.tr.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - '--framework' seçeneği ile '--folder' seçeneği belirtilemiyor. + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - Çalışma alanı yüklenirken kullanılacak hedef çerçeve (TFM). Geri yükleme ve analizi yalnızca belirtilen çerçeveyle sınırlandırır. + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hans.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hans.xlf index 746fda34fec7..46bd577ef432 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hans.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hans.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - 无法使用 '--framework' 指定 '--folder' 选项。 + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - 加载工作区时要使用的目标框架 (TFM)。将还原和分析限制为仅指定的框架。 + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hant.xlf b/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hant.xlf index a9cd85457190..92a98b25e489 100644 --- a/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hant.xlf +++ b/src/BuiltInTools/dotnet-format/xlf/Resources.zh-Hant.xlf @@ -64,7 +64,7 @@ Cannot specify the '--folder' option with '--framework'. - 無法指定 '--folder' 選項搭配 '--framework'。 + Cannot specify the '--folder' option with '--framework'. @@ -359,7 +359,7 @@ The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. - 載入工作區時使用的目標架構 (TFM)。將還原和分析限制為僅指定的架構。 + The target framework (TFM) to use when loading the workspace. Restricts restore and analysis to the specified framework only. diff --git a/test/dotnet-format.UnitTests/ProgramTests.cs b/test/dotnet-format.UnitTests/ProgramTests.cs index e47b5a8b4977..04b7a49cfc80 100644 --- a/test/dotnet-format.UnitTests/ProgramTests.cs +++ b/test/dotnet-format.UnitTests/ProgramTests.cs @@ -319,21 +319,5 @@ public void ParseCommonOptions_NoFrameworkOption_LeavesTargetFrameworkNull() // Assert Assert.Null(formatOptions.TargetFramework); } - - [Fact] - public void DotNetHelper_BuildRestoreArguments_ProducesRestoreCommand() - { - var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj"); - - Assert.Equal("restore \"my.csproj\"", args); - } - - [Fact] - public void DotNetHelper_BuildRestoreArguments_DoesNotPassFrameworkToRestore() - { - var args = ProductionDotNetHelper.BuildRestoreArguments("my.csproj"); - - Assert.DoesNotContain("framework", args, StringComparison.OrdinalIgnoreCase); - } } } From fbc517e73ccfa5c07474bb4cef65e254ffea7017 Mon Sep 17 00:00:00 2001 From: Hex Date: Tue, 3 Mar 2026 21:30:20 +0100 Subject: [PATCH 4/5] Refactored parameter so cancellationToken is last --- src/BuiltInTools/dotnet-format/CodeFormatter.cs | 11 +++++------ .../dotnet-format/Commands/FormatCommandCommon.cs | 3 +-- .../dotnet-format/Utilities/DotNetHelper.cs | 1 - .../Workspaces/MSBuildWorkspaceLoader.cs | 4 ++-- .../Analyzers/ThirdPartyAnalyzerFormatterTests.cs | 2 +- .../MSBuild/MSBuildWorkspaceLoaderTests.cs | 2 +- 6 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/BuiltInTools/dotnet-format/CodeFormatter.cs b/src/BuiltInTools/dotnet-format/CodeFormatter.cs index b5144626c7cd..bd0382c5c885 100644 --- a/src/BuiltInTools/dotnet-format/CodeFormatter.cs +++ b/src/BuiltInTools/dotnet-format/CodeFormatter.cs @@ -25,8 +25,7 @@ internal static class CodeFormatter public static async Task FormatWorkspaceAsync( FormatOptions formatOptions, ILogger logger, - CancellationToken cancellationToken, - string? binaryLogPath = null) + CancellationToken cancellationToken) { var logWorkspaceWarnings = formatOptions.LogLevel == LogLevel.Trace; @@ -38,7 +37,7 @@ public static async Task FormatWorkspaceAsync( using var workspace = formatOptions.WorkspaceType == WorkspaceType.Folder ? OpenFolderWorkspace(formatOptions.WorkspaceFilePath, formatOptions.FileMatcher) - : await OpenMSBuildWorkspaceAsync(formatOptions.WorkspaceFilePath, formatOptions.WorkspaceType, formatOptions.NoRestore, formatOptions.FixCategory != FixCategory.Whitespace, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken, formatOptions.TargetFramework).ConfigureAwait(false); + : await OpenMSBuildWorkspaceAsync(formatOptions.WorkspaceFilePath, formatOptions.WorkspaceType, formatOptions.NoRestore, formatOptions.FixCategory != FixCategory.Whitespace, formatOptions.BinaryLogPath, logWorkspaceWarnings, logger, formatOptions.TargetFramework, cancellationToken).ConfigureAwait(false); if (workspace is null) { @@ -126,8 +125,8 @@ private static Workspace OpenFolderWorkspace(string workspacePath, SourceFileMat string? binaryLogPath, bool logWorkspaceWarnings, ILogger logger, - CancellationToken cancellationToken, - string? targetFramework = null) + string? targetFramework, + CancellationToken cancellationToken) { if (requiresSemantics && !noRestore && @@ -136,7 +135,7 @@ await DotNetHelper.PerformRestoreAsync(solutionOrProjectPath, logger) != 0) throw new Exception("Restore operation failed."); } - return await MSBuildWorkspaceLoader.LoadAsync(solutionOrProjectPath, workspaceType, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken, targetFramework); + return await MSBuildWorkspaceLoader.LoadAsync(solutionOrProjectPath, workspaceType, binaryLogPath, logWorkspaceWarnings, logger, targetFramework, cancellationToken); } private static async Task RunCodeFormattersAsync( diff --git a/src/BuiltInTools/dotnet-format/Commands/FormatCommandCommon.cs b/src/BuiltInTools/dotnet-format/Commands/FormatCommandCommon.cs index d0035d6fbb13..603e1f3e9eec 100644 --- a/src/BuiltInTools/dotnet-format/Commands/FormatCommandCommon.cs +++ b/src/BuiltInTools/dotnet-format/Commands/FormatCommandCommon.cs @@ -111,8 +111,7 @@ internal static async Task FormatAsync(FormatOptions formatOptions, ILogger var formatResult = await CodeFormatter.FormatWorkspaceAsync( formatOptions, logger, - cancellationToken, - binaryLogPath: formatOptions.BinaryLogPath).ConfigureAwait(false); + cancellationToken).ConfigureAwait(false); return formatResult.GetExitCode(formatOptions.ChangesAreErrors); } diff --git a/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs b/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs index 394e58ad2585..99818ee139b2 100644 --- a/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs +++ b/src/BuiltInTools/dotnet-format/Utilities/DotNetHelper.cs @@ -7,7 +7,6 @@ namespace Microsoft.CodeAnalysis.Tools.Utilities { internal static class DotNetHelper { - public static async Task PerformRestoreAsync(string workspaceFilePath, ILogger logger) { var processInfo = ProcessRunner.CreateProcess("dotnet", $"restore \"{workspaceFilePath}\"", captureOutput: true, displayWindow: false); diff --git a/src/BuiltInTools/dotnet-format/Workspaces/MSBuildWorkspaceLoader.cs b/src/BuiltInTools/dotnet-format/Workspaces/MSBuildWorkspaceLoader.cs index fac3978c1f6e..57bb28a91ec5 100644 --- a/src/BuiltInTools/dotnet-format/Workspaces/MSBuildWorkspaceLoader.cs +++ b/src/BuiltInTools/dotnet-format/Workspaces/MSBuildWorkspaceLoader.cs @@ -18,8 +18,8 @@ internal static class MSBuildWorkspaceLoader string? binaryLogPath, bool logWorkspaceWarnings, ILogger logger, - CancellationToken cancellationToken, - string? targetFramework = null) + string? targetFramework, + CancellationToken cancellationToken) { var properties = new Dictionary(StringComparer.Ordinal) { diff --git a/test/dotnet-format.UnitTests/Analyzers/ThirdPartyAnalyzerFormatterTests.cs b/test/dotnet-format.UnitTests/Analyzers/ThirdPartyAnalyzerFormatterTests.cs index 7063df88ef44..4066fdc325d8 100644 --- a/test/dotnet-format.UnitTests/Analyzers/ThirdPartyAnalyzerFormatterTests.cs +++ b/test/dotnet-format.UnitTests/Analyzers/ThirdPartyAnalyzerFormatterTests.cs @@ -38,7 +38,7 @@ public async Task InitializeAsync() // Load the analyzer_project into a MSBuildWorkspace. var workspacePath = Path.Combine(TestProjectsPathHelper.GetProjectsDirectory(), s_analyzerProjectFilePath); - var analyzerWorkspace = await MSBuildWorkspaceLoader.LoadAsync(workspacePath, WorkspaceType.Project, binaryLogPath: null, logWorkspaceWarnings: true, logger, CancellationToken.None); + var analyzerWorkspace = await MSBuildWorkspaceLoader.LoadAsync(workspacePath, WorkspaceType.Project, binaryLogPath: null, logWorkspaceWarnings: true, logger, null, CancellationToken.None); TestOutputHelper.WriteLine(logger.GetLog()); diff --git a/test/dotnet-format.UnitTests/MSBuild/MSBuildWorkspaceLoaderTests.cs b/test/dotnet-format.UnitTests/MSBuild/MSBuildWorkspaceLoaderTests.cs index 552401c2708e..9d4c903cb089 100644 --- a/test/dotnet-format.UnitTests/MSBuild/MSBuildWorkspaceLoaderTests.cs +++ b/test/dotnet-format.UnitTests/MSBuild/MSBuildWorkspaceLoaderTests.cs @@ -134,7 +134,7 @@ private static async Task AssertProjectLoadsCleanlyAsync(string projectFilePath, { var binaryLogPath = Path.ChangeExtension(projectFilePath, ".binlog"); - using var workspace = (MSBuildWorkspace)await MSBuildWorkspaceLoader.LoadAsync(projectFilePath, WorkspaceType.Project, binaryLogPath, logWorkspaceWarnings: true, logger, CancellationToken.None); + using var workspace = (MSBuildWorkspace)await MSBuildWorkspaceLoader.LoadAsync(projectFilePath, WorkspaceType.Project, binaryLogPath, logWorkspaceWarnings: true, logger, null, CancellationToken.None); Assert.Empty(workspace.Diagnostics); From 9579af8c4b515d486360df6c2378fde946f4f7b7 Mon Sep 17 00:00:00 2001 From: Joey Robichaud Date: Tue, 3 Mar 2026 14:11:13 -0800 Subject: [PATCH 5/5] Use named parameters --- .../Analyzers/ThirdPartyAnalyzerFormatterTests.cs | 2 +- .../MSBuild/MSBuildWorkspaceLoaderTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/dotnet-format.UnitTests/Analyzers/ThirdPartyAnalyzerFormatterTests.cs b/test/dotnet-format.UnitTests/Analyzers/ThirdPartyAnalyzerFormatterTests.cs index 4066fdc325d8..07fae27e9946 100644 --- a/test/dotnet-format.UnitTests/Analyzers/ThirdPartyAnalyzerFormatterTests.cs +++ b/test/dotnet-format.UnitTests/Analyzers/ThirdPartyAnalyzerFormatterTests.cs @@ -38,7 +38,7 @@ public async Task InitializeAsync() // Load the analyzer_project into a MSBuildWorkspace. var workspacePath = Path.Combine(TestProjectsPathHelper.GetProjectsDirectory(), s_analyzerProjectFilePath); - var analyzerWorkspace = await MSBuildWorkspaceLoader.LoadAsync(workspacePath, WorkspaceType.Project, binaryLogPath: null, logWorkspaceWarnings: true, logger, null, CancellationToken.None); + var analyzerWorkspace = await MSBuildWorkspaceLoader.LoadAsync(workspacePath, WorkspaceType.Project, binaryLogPath: null, logWorkspaceWarnings: true, logger, targetFramework: null, CancellationToken.None); TestOutputHelper.WriteLine(logger.GetLog()); diff --git a/test/dotnet-format.UnitTests/MSBuild/MSBuildWorkspaceLoaderTests.cs b/test/dotnet-format.UnitTests/MSBuild/MSBuildWorkspaceLoaderTests.cs index 9d4c903cb089..d7bfa76f5d68 100644 --- a/test/dotnet-format.UnitTests/MSBuild/MSBuildWorkspaceLoaderTests.cs +++ b/test/dotnet-format.UnitTests/MSBuild/MSBuildWorkspaceLoaderTests.cs @@ -134,7 +134,7 @@ private static async Task AssertProjectLoadsCleanlyAsync(string projectFilePath, { var binaryLogPath = Path.ChangeExtension(projectFilePath, ".binlog"); - using var workspace = (MSBuildWorkspace)await MSBuildWorkspaceLoader.LoadAsync(projectFilePath, WorkspaceType.Project, binaryLogPath, logWorkspaceWarnings: true, logger, null, CancellationToken.None); + using var workspace = (MSBuildWorkspace)await MSBuildWorkspaceLoader.LoadAsync(projectFilePath, WorkspaceType.Project, binaryLogPath, logWorkspaceWarnings: true, logger, targetFramework: null, CancellationToken.None); Assert.Empty(workspace.Diagnostics);