Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Usage:
dotnet-format [options]

Options:
-f, --folder The folder to operate on. Cannot be used with the `--workspace` option.
-w, --workspace The solution or project file to operate on. If a file is not specified, the command will search
the current directory for one.
-v, --verbosity Set the verbosity level. Allowed values are q[uiet], m[inimal], n[ormal], d[etailed], and
Expand All @@ -56,6 +57,7 @@ Add `format` after `dotnet` and before the command arguments that you want to ru
| Examples | Description |
| -------------------------------------------------------- |---------------------------------------------------------------------------------------------- |
| dotnet **format** | Formats the project or solution in the current directory. |
| dotnet **format** -f <folder> | Formats a particular folder and subfolders.
| dotnet **format** -w <workspace> | Formats a specific project or solution. |
| dotnet **format** -v diag | Formats with very verbose logging. |
| dotnet **format** --files Programs.cs,Utility\Logging.cs | Formats the files Program.cs and Utility\Logging.cs |
Expand Down
16 changes: 8 additions & 8 deletions azure-pipelines-integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,35 +19,35 @@ jobs:
format:
_repo: "https://github.com/dotnet/format"
_repoName: "dotnet/format"
_sha: "b6db94c361b1ecd0558fc7429335ec01133773ed"
_sha: "4ff73616469a2aaa5ff07d11b7f6951eca83d76e"
roslyn:
_repo: "https://github.com/dotnet/roslyn"
_repoName: "dotnet/roslyn"
_sha: "665dc224dcfefb66dce215ca0204363172b611ad"
_sha: "1bd191ea896b19e3b06a152f815f3a998e87049a"
cli:
_repo: "https://github.com/dotnet/cli"
_repoName: "dotnet/cli"
_sha: "8d0f2a593ec98ccc1ef2141452d7dccadc34ac40"
_sha: "45f1c5f7f3275ff483c804e7c90bf61731a83e97"
project-system:
_repo: "https://github.com/dotnet/project-system"
_repoName: "dotnet/project-system"
_sha: "80580ad27c5544f00f4abb9db930e698ce305285"
_sha: "fc3b12e47adaad6e4813dc600acf190156fecc24"
msbuild:
_repo: "https://github.com/Microsoft/msbuild"
_repoName: "Microsoft/msbuild"
_sha: "d54d2e0180b99b7773f0fef2cdb03168f134d9aa"
_sha: "e92633a735b0e23e2cbf818d02ba89dd7a426f89"
Blazor:
_repo: "https://github.com/aspnet/Blazor"
_repoName: "aspnet/Blazor"
_sha: "3addb6169afcae1b5c6a64de4a7cd02bd270ffed"
_sha: "7eeab316fa122b69a9bd777c93dcc78bc6a68905"
EntityFrameworkCore:
_repo: "https://github.com/aspnet/EntityFrameworkCore"
_repoName: "aspnet/EntityFrameworkCore"
_sha: "090f385ffe4f2cd1a3e6b794523bdf574862c298"
_sha: "94f5bdf081f9a774f5d7f01bfa279bac26dab303"
EntityFramework6:
_repo: "https://github.com/aspnet/EntityFramework6"
_repoName: "aspnet/EntityFramework6"
_sha: "936befcd88a4b58be6f35038248cd5337aca4967"
_sha: "9099ad2f6e5936ecdf549f88394b5a59fa75c869"
timeoutInMinutes: 20
steps:
- script: eng\integration-test.cmd -repo '$(_repo)' -sha '$(_sha)' -testPath '$(Build.SourcesDirectory)\temp'
Expand Down
38 changes: 24 additions & 14 deletions eng/format-verifier.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,7 @@ Param(
[string]$testPath
)

function Clone-Repo([string]$repo, [string]$sha, [string]$repoPath) {
$currentLocation = Get-Location

git.exe clone $repo $repoPath

Set-Location $repoPath

git.exe checkout $sha

Set-Location $currentLocation
}
$currentLocation = Get-Location

if (!(Test-Path $testPath)) {
New-Item -ItemType Directory -Force -Path $testPath | Out-Null
Expand All @@ -27,19 +17,37 @@ try {
$repoPath = Join-Path $testPath $folderName

Write-Output "$(Get-Date) - Cloning $repoName."
Clone-Repo $repo $sha $repoPath
git.exe clone $repo $repoPath

Set-Location $repoPath

git.exe checkout $sha

Write-Output "$(Get-Date) - Finding solutions."
$solutions = Get-ChildItem -Path $repoPath -Filter *.sln -Recurse -Depth 2 | Select-Object -ExpandProperty FullName | Where-Object { $_ -match '.sln$' }
$solutions = Get-ChildItem -Filter *.sln -Recurse -Depth 2 | Select-Object -ExpandProperty FullName | Where-Object { $_ -match '.sln$' }

# We invoke build.ps1 ourselves because running `restore.cmd` invokes the build.ps1
# in a child process which means added .NET Core SDKs aren't visible to this process.
if (Test-Path '.\eng\Build.ps1') {
Write-Output "$(Get-Date) - Running Build.ps1 -restore"
.\eng\Build.ps1 -restore
}
elseif (Test-Path '.\eng\common\Build.ps1') {
Write-Output "$(Get-Date) - Running Build.ps1 -restore"
.\eng\common\Build.ps1 -restore
}

foreach ($solution in $solutions) {
$solutionPath = Split-Path $solution
$solutionFile = Split-Path $solution -leaf

Set-Location $solutionPath

Write-Output "$(Get-Date) - $solutionFile - Restoring"
dotnet.exe restore $solution

Write-Output "$(Get-Date) - $solutionFile - Formatting"
$output = dotnet.exe run -p .\src\dotnet-format.csproj -c Release -- -w $solution -v d --dry-run | Out-String
$output = dotnet.exe run -p "$currentLocation\src\dotnet-format.csproj" -c Release -- -w $solution -v d --dry-run | Out-String
Write-Output $output.TrimEnd()

if ($LastExitCode -ne 0) {
Expand All @@ -59,6 +67,8 @@ catch {
exit -1
}
finally {
Set-Location $currentLocation

Remove-Item $repoPath -Force -Recurse
Write-Output "$(Get-Date) - Deleted $repoName."
}
66 changes: 45 additions & 21 deletions src/CodeFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Tools.Utilities;
using Microsoft.CodeAnalysis.Tools.Formatters;
using Microsoft.CodeAnalysis.Tools.Workspaces;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.CodingConventions;

Expand All @@ -32,7 +33,7 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
ILogger logger,
CancellationToken cancellationToken)
{
var (workspaceFilePath, isSolution, logLevel, saveFormattedFiles, _, filesToFormat) = options;
var (workspaceFilePath, workspaceType, logLevel, saveFormattedFiles, _, filesToFormat) = options;
var logWorkspaceWarnings = logLevel == LogLevel.Trace;

logger.LogInformation(string.Format(Resources.Formatting_code_files_in_workspace_0, workspaceFilePath));
Expand All @@ -42,7 +43,7 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
var workspaceStopwatch = Stopwatch.StartNew();

using (var workspace = await OpenWorkspaceAsync(
workspaceFilePath, isSolution, logWorkspaceWarnings, logger, cancellationToken).ConfigureAwait(false))
workspaceFilePath, workspaceType, filesToFormat, logWorkspaceWarnings, logger, cancellationToken).ConfigureAwait(false))
{
if (workspace is null)
{
Expand All @@ -52,7 +53,7 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
var loadWorkspaceMS = workspaceStopwatch.ElapsedMilliseconds;
logger.LogTrace(Resources.Complete_in_0_ms, workspaceStopwatch.ElapsedMilliseconds);

var projectPath = isSolution ? string.Empty : workspaceFilePath;
var projectPath = workspaceType == WorkspaceType.Project ? workspaceFilePath : string.Empty;
var solution = workspace.CurrentSolution;

logger.LogTrace(Resources.Determining_formattable_files);
Expand Down Expand Up @@ -101,8 +102,26 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
}

private static async Task<Workspace> OpenWorkspaceAsync(
string workspacePath,
WorkspaceType workspaceType,
ImmutableHashSet<string> filesToFormat,
bool logWorkspaceWarnings,
ILogger logger,
CancellationToken cancellationToken)
{
if (workspaceType == WorkspaceType.Folder)
{
var folderWorkspace = FolderWorkspace.Create();
await folderWorkspace.OpenFolder(workspacePath, filesToFormat, cancellationToken);
return folderWorkspace;
}

return await OpenMSBuildWorkspaceAsync(workspacePath, workspaceType, logWorkspaceWarnings, logger, cancellationToken);
}

private static async Task<Workspace> OpenMSBuildWorkspaceAsync(
string solutionOrProjectPath,
bool isSolution,
WorkspaceType workspaceType,
bool logWorkspaceWarnings,
ILogger logger,
CancellationToken cancellationToken)
Expand All @@ -119,10 +138,8 @@ private static async Task<Workspace> OpenWorkspaceAsync(
};

var workspace = MSBuildWorkspace.Create(properties);
workspace.WorkspaceFailed += LogWorkspaceWarnings;

var projectPath = string.Empty;
if (isSolution)
if (workspaceType == WorkspaceType.Solution)
{
await workspace.OpenSolutionAsync(solutionOrProjectPath, cancellationToken: cancellationToken).ConfigureAwait(false);
}
Expand All @@ -131,7 +148,6 @@ private static async Task<Workspace> OpenWorkspaceAsync(
try
{
await workspace.OpenProjectAsync(solutionOrProjectPath, cancellationToken: cancellationToken).ConfigureAwait(false);
projectPath = solutionOrProjectPath;
}
catch (InvalidOperationException)
{
Expand All @@ -141,25 +157,33 @@ private static async Task<Workspace> OpenWorkspaceAsync(
}
}

workspace.WorkspaceFailed -= LogWorkspaceWarnings;
LogWorkspaceDiagnostics(logger, logWorkspaceWarnings, workspace.Diagnostics);

return workspace;
}

void LogWorkspaceWarnings(object sender, WorkspaceDiagnosticEventArgs args)
private static void LogWorkspaceDiagnostics(ILogger logger, bool logWorkspaceWarnings, ImmutableList<WorkspaceDiagnostic> diagnostics)
{
if (!logWorkspaceWarnings)
{
if (args.Diagnostic.Kind == WorkspaceDiagnosticKind.Failure)
if (diagnostics.Count > 0)
{
return;
logger.LogWarning(Resources.Warnings_were_encountered_while_loading_the_workspace_Set_the_verbosity_option_to_the_diagnostic_level_to_log_warnings);
}

if (!logWorkspaceWarnings)
return;
}

foreach (var diagnostic in diagnostics)
{
if (diagnostic.Kind == WorkspaceDiagnosticKind.Failure)
{
logger.LogWarning(Resources.Warnings_were_encountered_while_loading_the_workspace_Set_the_verbosity_option_to_the_diagnostic_level_to_log_warnings);
((MSBuildWorkspace)sender).WorkspaceFailed -= LogWorkspaceWarnings;
return;
logger.LogError(diagnostic.Message);
}
else
{
logger.LogWarning(diagnostic.Message);
}

logger.LogWarning(args.Diagnostic.Message);
}
}

Expand Down Expand Up @@ -212,8 +236,8 @@ private static async Task<Solution> RunCodeFormattersAsync(
fileCount += project.DocumentIds.Count;

// Get project documents and options with .editorconfig settings applied.
var getProjectDocuments = project.DocumentIds.Select(documentId => Task.Run(async () => await GetDocumentAndOptions(
project, documentId, filesToFormat, codingConventionsManager, optionsApplier, cancellationToken).ConfigureAwait(false), cancellationToken));
var getProjectDocuments = project.DocumentIds.Select(documentId => GetDocumentAndOptions(
project, documentId, filesToFormat, codingConventionsManager, optionsApplier, cancellationToken));
getDocumentsAndOptions.AddRange(getProjectDocuments);
}

Expand Down Expand Up @@ -248,7 +272,7 @@ private static async Task<Solution> RunCodeFormattersAsync(
return (fileCount, formattableFiles.ToImmutableArray());
}

private static async Task<(Document, OptionSet, ICodingConventionsSnapshot, bool)> GetDocumentAndOptions(
private static async Task<(Document, OptionSet, ICodingConventionsSnapshot, bool)> GetDocumentAndOptions(
Project project,
DocumentId documentId,
ImmutableHashSet<string> filesToFormat,
Expand Down
14 changes: 8 additions & 6 deletions src/FormatOptions.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
using System.Collections.Immutable;
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.

using System.Collections.Immutable;
using Microsoft.Extensions.Logging;

namespace Microsoft.CodeAnalysis.Tools
{
internal class FormatOptions
{
public string WorkspaceFilePath { get; }
public bool IsSolution { get; }
public WorkspaceType WorkspaceType { get; }
public LogLevel LogLevel { get; }
public bool SaveFormattedFiles { get; }
public bool ChangesAreErrors { get; }
public ImmutableHashSet<string> FilesToFormat { get; }

public FormatOptions(
string workspaceFilePath,
bool isSolution,
WorkspaceType workspaceType,
LogLevel logLevel,
bool saveFormattedFiles,
bool changesAreErrors,
ImmutableHashSet<string> filesToFormat)
{
WorkspaceFilePath = workspaceFilePath;
IsSolution = isSolution;
WorkspaceType = workspaceType;
LogLevel = logLevel;
SaveFormattedFiles = saveFormattedFiles;
ChangesAreErrors = changesAreErrors;
Expand All @@ -30,14 +32,14 @@ public FormatOptions(

public void Deconstruct(
out string workspaceFilePath,
out bool isSolution,
out WorkspaceType workspaceType,
out LogLevel logLevel,
out bool saveFormattedFiles,
out bool changesAreErrors,
out ImmutableHashSet<string> filesToFormat)
{
workspaceFilePath = WorkspaceFilePath;
isSolution = IsSolution;
workspaceType = WorkspaceType;
logLevel = LogLevel;
saveFormattedFiles = SaveFormattedFiles;
changesAreErrors = ChangesAreErrors;
Expand Down
4 changes: 1 addition & 3 deletions src/Formatters/DocumentFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,6 @@ protected abstract Task<SourceText> FormatFileAsync(
ILogger logger,
CancellationToken cancellationToken)
{
logger.LogTrace(Resources.Formatting_code_file_0, Path.GetFileName(document.FilePath));

var originalSourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var formattedSourceText = await FormatFileAsync(document, originalSourceText, options, codingConventions, formatOptions, logger, cancellationToken).ConfigureAwait(false);

Expand Down Expand Up @@ -113,7 +111,7 @@ private async Task<Solution> ApplyFileChangesAsync(
continue;
}

if (!formatOptions.SaveFormattedFiles)
if (!formatOptions.SaveFormattedFiles || formatOptions.LogLevel == LogLevel.Trace)
{
// Log formatting changes as errors when we are doing a dry-run.
LogFormattingChanges(formatOptions.WorkspaceFilePath, document.FilePath, originalText, formattedText, formatOptions.ChangesAreErrors, logger);
Expand Down
Loading