Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add implicit restore when running analysis. Adds --no-restore option. #1015

Merged
merged 5 commits into from Mar 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -97,6 +97,7 @@ Arguments:
<workspace> A path to a solution file, a project file, or a folder containing a solution or project file. If a path is not specified then the current directory is used.

Options:
--no-restore Doesn't execute an implicit restore before formatting.
--folder, -f Whether to treat the `<workspace>` argument as a simple folder of files.
--fix-whitespace, -w Run whitespace formatting. Run by default when not applying fixes.
--fix-style, -s <severity> Run code style analyzers and apply fixes.
Expand All @@ -118,6 +119,7 @@ Add `format` after `dotnet` and before the command arguments that you want to ru
| `dotnet format <workspace>` | Formats a specific project or solution. |
| `dotnet format <workspace> -f` | Formats a particular folder and subfolders. |
| `dotnet format <workspace> --fix-style warn` | Fixes only codestyle analyzer warnings. |
| `dotnet format <workspace> --fix-style --no-restore` | Fixes only codestyle analyzer errors without performing an implicit restore. |
| `dotnet format <workspace> --fix-style --diagnostics IDE0005` | Fixes only codestyle analyzer errors for the IDE0005 diagnostic. |
| `dotnet format <workspace> --fix-whitespace --fix-style` | Formats and fixes codestyle analyzer errors. |
| `dotnet format <workspace> --fix-analyzers` | Fixes only 3rd party analyzer errors. |
Expand Down
7 changes: 4 additions & 3 deletions docs/README.md
Expand Up @@ -10,6 +10,7 @@
A workspace path is needed when running dotnet-format. By default, the current folder will be used as the workspace path. The workspace path and type of workspace determines which code files are considered for formatting.

- Solutions and Projects - By default dotnet-format will open the workspace path as a MSBuild solution or project.
- `--no-restore` - When formatting a solution or project the no restore option will stop dotnet-format from performing an implicit package restore.
- `--folder` - When the folder options is specified the workspace path will be treated as a folder of code files.

*Example:*
Expand All @@ -34,7 +35,7 @@ dotnet-format ./src --folder

### Whitespace formatting

Whitespace formatting includes the core .editorconfig settings along with the placement of spaces and newlines. The whitespace formatter is run by default when not running analysis. When you want to run analysis and fix formatting issues you must specify both.
Whitespace formatting includes the core .editorconfig settings along with the placement of spaces and newlines. The whitespace formatter is run by default when not running analysis. When only performing whitespace formatting, an implicit restore is not perfomed. When you want to run analysis and fix formatting issues you must specify both.

Whitespace formatting run by default.

Expand All @@ -52,7 +53,7 @@ dotnet-format ./format.sln --fix-whitespace --fix-style

#### CodeStyle analysis

Running codestyle analysis requires the use of a MSBuild solution or project file as the workspace. Enforces the .NET [Language conventions](https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-language-conventions?view=vs-2019) and [Naming conventions](https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-naming-conventions?view=vs-2019).
Running codestyle analysis requires the use of a MSBuild solution or project file as the workspace. By default an implicit restore on the solution or project is performed. Enforces the .NET [Language conventions](https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-language-conventions?view=vs-2019) and [Naming conventions](https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-naming-conventions?view=vs-2019).

- `--fix-style <severity>` - Runs analysis and attempts to fix issues with severity equal or greater than specified. If severity is not specified then severity defaults to error.

Expand All @@ -78,7 +79,7 @@ dotnet-format ./src --folder --fix-style

#### 3rd party analysis

Running 3rd party analysis requires the use of a MSBuild solution or project file as the workspace. 3rd party analyzers are discovered from the `<PackageReferences>` specified in the workspace project files.
Running 3rd party analysis requires the use of a MSBuild solution or project file as the workspace. By default an implicit restore on the solution or project is performed. 3rd party analyzers are discovered from the `<PackageReferences>` specified in the workspace project files.

- `--fix-analyzers <severity>` - Runs analysis and attempts to fix issues with severity equal or greater than specified. If no severity is specified then this defaults to error.

Expand Down
2 changes: 1 addition & 1 deletion eng/format-verifier.ps1
Expand Up @@ -70,7 +70,7 @@ try {

if ($stage -eq "format-workspace") {
Write-Output "$(Get-Date) - $solutionFile - Formatting Workspace"
$output = dotnet.exe "$currentLocation/artifacts/bin/dotnet-format/Release/netcoreapp2.1/dotnet-format.dll" $solution -wsa -v diag --check | Out-String
$output = dotnet.exe "$currentLocation/artifacts/bin/dotnet-format/Release/netcoreapp2.1/dotnet-format.dll" $solution --no-restore -wsa -v diag --check | Out-String
Write-Output $output.TrimEnd()

# Ignore CheckFailedExitCode since we don't expect these repos to be properly formatted.
Expand Down
3 changes: 3 additions & 0 deletions perf/FormattedFiles.cs
Expand Up @@ -33,6 +33,7 @@ public void FilesFormattedFolder()
var options = new FormatOptions(
workspacePath,
workspaceType,
noRestore: false,
LogLevel.Error,
fixCategory: FixCategory.Whitespace,
codeStyleSeverity: DiagnosticSeverity.Error,
Expand All @@ -53,6 +54,7 @@ public void FilesFormattedProject()
var options = new FormatOptions(
workspacePath,
workspaceType,
noRestore: false,
LogLevel.Error,
fixCategory: FixCategory.Whitespace,
codeStyleSeverity: DiagnosticSeverity.Error,
Expand All @@ -73,6 +75,7 @@ public void FilesFormattedSolution()
var options = new FormatOptions(
workspacePath,
workspaceType,
noRestore: false,
LogLevel.Error,
fixCategory: FixCategory.Whitespace,
codeStyleSeverity: DiagnosticSeverity.Error,
Expand Down
3 changes: 3 additions & 0 deletions perf/NoFilesFormatted.cs
Expand Up @@ -33,6 +33,7 @@ public void NoFilesFormattedFolder()
var options = new FormatOptions(
workspacePath,
workspaceType,
noRestore: false,
LogLevel.Error,
fixCategory: FixCategory.Whitespace,
codeStyleSeverity: DiagnosticSeverity.Error,
Expand All @@ -53,6 +54,7 @@ public void NoFilesFormattedProject()
var options = new FormatOptions(
workspacePath,
workspaceType,
noRestore: false,
LogLevel.Error,
fixCategory: FixCategory.Whitespace,
codeStyleSeverity: DiagnosticSeverity.Error,
Expand All @@ -73,6 +75,7 @@ public void NoFilesFormattedSolution()
var options = new FormatOptions(
workspacePath,
workspaceType,
noRestore: false,
LogLevel.Error,
fixCategory: FixCategory.Whitespace,
codeStyleSeverity: DiagnosticSeverity.Error,
Expand Down
2 changes: 2 additions & 0 deletions perf/RealWorldSolution.cs
Expand Up @@ -35,6 +35,7 @@ public void FilesFormattedSolution()
var options = new FormatOptions(
workspacePath,
workspaceType,
noRestore: false,
LogLevel.Error,
fixCategory: FixCategory.Whitespace,
codeStyleSeverity: DiagnosticSeverity.Error,
Expand All @@ -55,6 +56,7 @@ public void FilesFormattedFolder()
var options = new FormatOptions(
workspacePath,
workspaceType,
noRestore: false,
LogLevel.Error,
fixCategory: FixCategory.Whitespace,
codeStyleSeverity: DiagnosticSeverity.Error,
Expand Down
16 changes: 13 additions & 3 deletions src/CodeFormatter.cs
Expand Up @@ -10,6 +10,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tools.Analyzers;
using Microsoft.CodeAnalysis.Tools.Formatters;
using Microsoft.CodeAnalysis.Tools.Tests.Utilities;
using Microsoft.CodeAnalysis.Tools.Utilities;
using Microsoft.CodeAnalysis.Tools.Workspaces;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -44,7 +45,7 @@ internal static class CodeFormatter

using var workspace = formatOptions.WorkspaceType == WorkspaceType.Folder
? OpenFolderWorkspace(formatOptions.WorkspaceFilePath, formatOptions.FileMatcher)
: await OpenMSBuildWorkspaceAsync(formatOptions.WorkspaceFilePath, formatOptions.WorkspaceType, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken).ConfigureAwait(false);
: await OpenMSBuildWorkspaceAsync(formatOptions.WorkspaceFilePath, formatOptions.WorkspaceType, formatOptions.NoRestore, formatOptions.FixCategory != FixCategory.Whitespace, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken).ConfigureAwait(false);

if (workspace is null)
{
Expand Down Expand Up @@ -120,15 +121,24 @@ private static Workspace OpenFolderWorkspace(string workspacePath, SourceFileMat
return folderWorkspace;
}

private static Task<Workspace?> OpenMSBuildWorkspaceAsync(
private static async Task<Workspace?> OpenMSBuildWorkspaceAsync(
string solutionOrProjectPath,
WorkspaceType workspaceType,
bool noRestore,
bool requiresSemantics,
string? binaryLogPath,
bool logWorkspaceWarnings,
ILogger logger,
CancellationToken cancellationToken)
{
return MSBuildWorkspaceLoader.LoadAsync(solutionOrProjectPath, workspaceType, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken);
if (requiresSemantics &&
!noRestore &&
await DotNetHelper.PerformRestoreAsync(solutionOrProjectPath, logger) != 0)
{
throw new Exception("Restore operation failed.");
}

return await MSBuildWorkspaceLoader.LoadAsync(solutionOrProjectPath, workspaceType, binaryLogPath, logWorkspaceWarnings, logger, cancellationToken);
}

private static async Task<Solution> RunCodeFormattersAsync(
Expand Down
12 changes: 12 additions & 0 deletions src/FormatCommand.cs
Expand Up @@ -14,6 +14,7 @@ internal static class FormatCommand
// so that values bind correctly.
internal delegate Task<int> Handler(
string? workspace,
bool noRestore,
bool folder,
bool fixWhitespace,
string? fixStyle,
Expand Down Expand Up @@ -41,6 +42,7 @@ internal static RootCommand CreateCommandLineOptions()
Arity = ArgumentArity.ZeroOrOne,
Description = Resources.A_path_to_a_solution_file_a_project_file_or_a_folder_containing_a_solution_or_project_file_If_a_path_is_not_specified_then_the_current_directory_is_used
}.LegalFilePathsOnly(),
new Option(new[] { "--no-restore" }, Resources.Doesnt_execute_an_implicit_restore_before_formatting),
new Option(new[] { "--folder", "-f" }, Resources.Whether_to_treat_the_workspace_argument_as_a_simple_folder_of_files),
new Option(new[] { "--fix-whitespace", "-w" }, Resources.Run_whitespace_formatting_Run_by_default_when_not_applying_fixes),
new Option(new[] { "--fix-style", "-s" }, Resources.Run_code_style_analyzers_and_apply_fixes)
Expand Down Expand Up @@ -85,6 +87,7 @@ internal static RootCommand CreateCommandLineOptions()
rootCommand.Description = "dotnet-format";
rootCommand.AddValidator(EnsureFolderNotSpecifiedWhenFixingStyle);
rootCommand.AddValidator(EnsureFolderNotSpecifiedWhenFixingAnalyzers);
rootCommand.AddValidator(EnsureFolderNotSpecifiedWithNoRestore);
rootCommand.AddValidator(EnsureFolderNotSpecifiedWhenLoggingBinlog);

return rootCommand;
Expand All @@ -108,6 +111,15 @@ internal static RootCommand CreateCommandLineOptions()
: null;
}

internal static string? EnsureFolderNotSpecifiedWithNoRestore(CommandResult symbolResult)
{
var folder = symbolResult.ValueForOption<bool>("--folder");
var noRestore = symbolResult.OptionResult("--no-restore");
return folder && noRestore != null
? Resources.Cannot_specify_the_folder_option_with_no_restore
: null;
}

internal static string? EnsureFolderNotSpecifiedWhenLoggingBinlog(CommandResult symbolResult)
{
var folder = symbolResult.ValueForOption<bool>("--folder");
Expand Down
5 changes: 5 additions & 0 deletions src/FormatOptions.cs
Expand Up @@ -10,6 +10,7 @@ internal class FormatOptions
{
public string WorkspaceFilePath { get; }
public WorkspaceType WorkspaceType { get; }
public bool NoRestore { get; }
public LogLevel LogLevel { get; }
public FixCategory FixCategory { get; }
public DiagnosticSeverity CodeStyleSeverity { get; }
Expand All @@ -24,6 +25,7 @@ internal class FormatOptions
public FormatOptions(
string workspaceFilePath,
WorkspaceType workspaceType,
bool noRestore,
LogLevel logLevel,
FixCategory fixCategory,
DiagnosticSeverity codeStyleSeverity,
Expand All @@ -37,6 +39,7 @@ internal class FormatOptions
{
WorkspaceFilePath = workspaceFilePath;
WorkspaceType = workspaceType;
NoRestore = noRestore;
LogLevel = logLevel;
FixCategory = fixCategory;
CodeStyleSeverity = codeStyleSeverity;
Expand All @@ -52,6 +55,7 @@ internal class FormatOptions
public void Deconstruct(
out string workspaceFilePath,
out WorkspaceType workspaceType,
out bool noRestore,
out LogLevel logLevel,
out FixCategory fixCategory,
out DiagnosticSeverity codeStyleSeverity,
Expand All @@ -65,6 +69,7 @@ internal class FormatOptions
{
workspaceFilePath = WorkspaceFilePath;
workspaceType = WorkspaceType;
noRestore = NoRestore;
logLevel = LogLevel;
fixCategory = FixCategory;
codeStyleSeverity = CodeStyleSeverity;
Expand Down
2 changes: 2 additions & 0 deletions src/Program.cs
Expand Up @@ -45,6 +45,7 @@ private static async Task<int> Main(string[] args)

public static async Task<int> Run(
string? workspace,
bool noRestore,
bool folder,
bool fixWhitespace,
string? fixStyle,
Expand Down Expand Up @@ -169,6 +170,7 @@ private static async Task<int> Main(string[] args)
var formatOptions = new FormatOptions(
workspacePath,
workspaceType,
noRestore,
logLevel,
fixType,
codeStyleSeverity: GetSeverity(fixStyle ?? FixSeverity.Error),
Expand Down
6 changes: 6 additions & 0 deletions src/Resources.resx
Expand Up @@ -312,6 +312,12 @@
<data name="Project_0_is_using_configuration_from_1" xml:space="preserve">
<value>Project {0} is using configuration from '{1}'.</value>
</data>
<data name="Doesnt_execute_an_implicit_restore_before_formatting" xml:space="preserve">
<value>Doesn't execute an implicit restore before formatting.</value>
</data>
<data name="Cannot_specify_the_folder_option_with_no_restore" xml:space="preserve">
<value>Cannot specify the '--folder' option with '--no-restore'.</value>
</data>
<data name="Delete_0_characters" xml:space="preserve">
<value>Delete {0} characters.</value>
</data>
Expand Down
24 changes: 24 additions & 0 deletions src/Utilities/DotNetHelper.cs
@@ -0,0 +1,24 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tools.Utilities;
using Microsoft.Extensions.Logging;

#nullable enable

namespace Microsoft.CodeAnalysis.Tools.Tests.Utilities
{
internal static class DotNetHelper
{
public static async Task<int> PerformRestoreAsync(string workspaceFilePath, ILogger logger)
{
var processInfo = ProcessRunner.CreateProcess("dotnet", $"restore \"{workspaceFilePath}\"", captureOutput: true, displayWindow: false);
var restoreResult = await processInfo.Result;

logger.LogDebug(string.Join(Environment.NewLine, restoreResult.OutputLines));

return restoreResult.ExitCode;
}
}
}
10 changes: 10 additions & 0 deletions src/xlf/Resources.cs.xlf
Expand Up @@ -52,6 +52,11 @@
<target state="new">Cannot specify the '--folder' option when running analyzers.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_specify_the_folder_option_with_no_restore">
<source>Cannot specify the '--folder' option with '--no-restore'.</source>
<target state="new">Cannot specify the '--folder' option with '--no-restore'.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_specify_the_folder_option_when_writing_a_binary_log">
<source>Cannot specify the '--folder' option when writing a binary log.</source>
<target state="new">Cannot specify the '--folder' option when writing a binary log.</target>
Expand Down Expand Up @@ -92,6 +97,11 @@
<target state="translated">Určují se soubory, které se dají formátovat.</target>
<note />
</trans-unit>
<trans-unit id="Doesnt_execute_an_implicit_restore_before_formatting">
<source>Doesn't execute an implicit restore before formatting.</source>
<target state="new">Doesn't execute an implicit restore before formatting.</target>
<note />
</trans-unit>
<trans-unit id="Failed_to_apply_code_fix_0_for_1_2">
<source>Failed to apply code fix {0} for {1}: {2}</source>
<target state="translated">Nepovedlo se použít opravu kódu {0} pro {1}: {2}</target>
Expand Down
10 changes: 10 additions & 0 deletions src/xlf/Resources.de.xlf
Expand Up @@ -52,6 +52,11 @@
<target state="new">Cannot specify the '--folder' option when running analyzers.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_specify_the_folder_option_with_no_restore">
<source>Cannot specify the '--folder' option with '--no-restore'.</source>
<target state="new">Cannot specify the '--folder' option with '--no-restore'.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_specify_the_folder_option_when_writing_a_binary_log">
<source>Cannot specify the '--folder' option when writing a binary log.</source>
<target state="new">Cannot specify the '--folder' option when writing a binary log.</target>
Expand Down Expand Up @@ -92,6 +97,11 @@
<target state="translated">Formatierbare Dateien werden ermittelt.</target>
<note />
</trans-unit>
<trans-unit id="Doesnt_execute_an_implicit_restore_before_formatting">
<source>Doesn't execute an implicit restore before formatting.</source>
<target state="new">Doesn't execute an implicit restore before formatting.</target>
<note />
</trans-unit>
<trans-unit id="Failed_to_apply_code_fix_0_for_1_2">
<source>Failed to apply code fix {0} for {1}: {2}</source>
<target state="translated">Fehler beim Anwenden der Codekorrektur "{0}" für "{1}": {2}</target>
Expand Down