Skip to content
Closed
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
21 changes: 12 additions & 9 deletions src/Dotnet.Format/dotnet-format/CodeFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(

var workspaceStopwatch = Stopwatch.StartNew();

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

if (workspace is null)
if (loadedWorkspace is null)
{
return new WorkspaceFormatResult(filesFormatted: 0, fileCount: 0, exitCode: 1);
}

var workspace = loadedWorkspace.Workspace;

if (formatOptions.LogLevel <= LogLevel.Debug)
{
foreach (var project in workspace.CurrentSolution.Projects)
Expand All @@ -58,13 +60,12 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
var loadWorkspaceMS = workspaceStopwatch.ElapsedMilliseconds;
logger.LogTrace(Resources.Complete_in_0_ms, loadWorkspaceMS);

var projectPath = formatOptions.WorkspaceType == WorkspaceType.Project ? formatOptions.WorkspaceFilePath : string.Empty;
var solution = workspace.CurrentSolution;

logger.LogTrace(Resources.Determining_formattable_files);

var (fileCount, formatableFiles) = await DetermineFormattableFilesAsync(
solution, projectPath, formatOptions, logger, cancellationToken);
solution, loadedWorkspace.ProjectId, formatOptions, logger, cancellationToken);

var determineFilesMS = workspaceStopwatch.ElapsedMilliseconds - loadWorkspaceMS;
logger.LogTrace(Resources.Complete_in_0_ms, determineFilesMS);
Expand Down Expand Up @@ -110,14 +111,14 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
return new WorkspaceFormatResult(documentIdsWithErrors.Length, fileCount, exitCode);
}

private static Workspace OpenFolderWorkspace(string workspacePath, SourceFileMatcher fileMatcher)
private static LoadedWorkspace OpenFolderWorkspace(string workspacePath, SourceFileMatcher fileMatcher)
{
var folderWorkspace = FolderWorkspace.Create();
folderWorkspace.OpenFolder(workspacePath, fileMatcher);
return folderWorkspace;
return new LoadedWorkspace(folderWorkspace, ProjectId: null);
}

private static async Task<Workspace?> OpenMSBuildWorkspaceAsync(
private static async Task<LoadedWorkspace?> OpenMSBuildWorkspaceAsync(
string solutionOrProjectPath,
WorkspaceType workspaceType,
bool noRestore,
Expand Down Expand Up @@ -165,11 +166,13 @@ private static async Task<Solution> RunCodeFormattersAsync(

internal static async Task<(int, ImmutableArray<DocumentId>)> DetermineFormattableFilesAsync(
Solution solution,
string projectPath,
ProjectId? projectId,
FormatOptions formatOptions,
ILogger logger,
CancellationToken cancellationToken)
{
Debug.Assert((formatOptions.WorkspaceType is WorkspaceType.Project) == (projectId is not null));

var totalFileCount = solution.Projects.Sum(project => project.DocumentIds.Count);
var projectFileCount = 0;

Expand All @@ -187,7 +190,7 @@ private static async Task<Solution> RunCodeFormattersAsync(
}

// If a project is used as a workspace, then ignore other referenced projects.
if (!string.IsNullOrEmpty(projectPath) && !project.FilePath.Equals(projectPath, StringComparison.OrdinalIgnoreCase))
if (projectId != null && project.Id != projectId)
{
logger.LogDebug(Resources.Skipping_referenced_project_0, project.Name);
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ internal static class FormatCommandCommon
private static string[] VerbosityLevels => new[] { "q", "quiet", "m", "minimal", "n", "normal", "d", "detailed", "diag", "diagnostic" };
private static string[] SeverityLevels => new[] { "info", "warn", "error", "hidden" };

public static readonly Argument<string> SlnOrProjectArgument = new Argument<string>(Resources.SolutionOrProjectArgumentName)
public static readonly Argument<string> SlnOrProjectArgument = new Argument<string>(Resources.SolutionOrProjectOrFileArgumentName)
{
Description = Resources.SolutionOrProjectArgumentDescription,
Description = Resources.SolutionOrProjectOrFileArgumentDescription,
Arity = ArgumentArity.ZeroOrOne
}.DefaultToCurrentDirectory();

Expand Down
12 changes: 6 additions & 6 deletions src/Dotnet.Format/dotnet-format/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,8 @@
<data name="Failed_to_save_formatting_changes" xml:space="preserve">
<value>Failed to save formatting changes.</value>
</data>
<data name="The_file_0_does_not_appear_to_be_a_valid_project_or_solution_file" xml:space="preserve">
<value>The file '{0}' does not appear to be a valid project or solution file.</value>
<data name="The_file_0_does_not_appear_to_be_a_valid_project_solution_file_or_file_based_app" xml:space="preserve">
<value>The file '{0}' does not appear to be a valid project, solution file, or file-based app.</value>
</data>
<data name="Multiple_MSBuild_project_files_found_in_0_Specify_which_to_use_with_the_workspace_argument" xml:space="preserve">
<value>Multiple MSBuild project files found in '{0}'. Specify which to use with the &lt;workspace&gt; argument.</value>
Expand Down Expand Up @@ -336,11 +336,11 @@
<data name="Cannot_specify_the_folder_option_with_framework" xml:space="preserve">
<value>Cannot specify the '--folder' option with '--framework'.</value>
</data>
<data name="SolutionOrProjectArgumentName" xml:space="preserve">
<value>PROJECT | SOLUTION</value>
<data name="SolutionOrProjectOrFileArgumentName" xml:space="preserve">
<value>PROJECT | SOLUTION | FILE</value>
</data>
<data name="SolutionOrProjectArgumentDescription" xml:space="preserve">
<value>The project or solution file to operate on. If a file is not specified, the command will search the current directory for one.</value>
<data name="SolutionOrProjectOrFileArgumentDescription" xml:space="preserve">
<value>The project or solution or C# (file-based program) file to operate on. If a file is not specified, the command will search the current directory for a project or solution.</value>
</data>
<data name="Accepts_a_file_path_which_if_provided_will_produce_a_json_report_in_the_given_directory" xml:space="preserve">
<value>Accepts a file path which if provided will produce a json report in the given directory.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// See https://github.com/aspnet/DotNetTools/blob/261b27b70027871143540af10a5cba57ce07ff97/src/dotnet-watch/Internal/MsBuildProjectFinder.cs

using Microsoft.DotNet.FileBasedPrograms;

namespace Microsoft.CodeAnalysis.Tools.Workspaces
{
internal class MSBuildWorkspaceFinder
Expand Down Expand Up @@ -62,10 +64,12 @@ private static (bool isSolution, string workspacePath) FindFile(string workspace
var isProject = !isSolution
&& workspaceExtension.EndsWith("proj", StringComparison.OrdinalIgnoreCase)
&& !workspaceExtension.Equals(DnxProjectExtension, StringComparison.OrdinalIgnoreCase);
var isFileBasedApp = !isSolution && !isProject
&& VirtualProjectBuilder.IsValidEntryPointPath(workspacePath);

if (!isSolution && !isProject)
if (!isSolution && !isProject && !isFileBasedApp)
{
throw new FileNotFoundException(string.Format(Resources.The_file_0_does_not_appear_to_be_a_valid_project_or_solution_file, Path.GetFileName(workspacePath)));
throw new FileNotFoundException(string.Format(Resources.The_file_0_does_not_appear_to_be_a_valid_project_solution_file_or_file_based_app, Path.GetFileName(workspacePath)));
}

if (!File.Exists(workspacePath))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal static class MSBuildWorkspaceLoader
// Used in tests for locking around MSBuild invocations
internal static readonly SemaphoreSlim Guard = new SemaphoreSlim(1, 1);

public static async Task<Workspace?> LoadAsync(
public static async Task<LoadedWorkspace?> LoadAsync(
string solutionOrProjectPath,
WorkspaceType workspaceType,
string? binaryLogPath,
Expand All @@ -35,6 +35,7 @@ internal static class MSBuildWorkspaceLoader
}

var workspace = MSBuildWorkspace.Create(properties);
ProjectId? projectId = null;

Build.Framework.ILogger? binlog = null;
if (binaryLogPath is not null)
Expand All @@ -54,7 +55,8 @@ internal static class MSBuildWorkspaceLoader
{
try
{
await workspace.OpenProjectAsync(solutionOrProjectPath, msbuildLogger: binlog, cancellationToken: cancellationToken);
var project = await workspace.OpenProjectAsync(solutionOrProjectPath, msbuildLogger: binlog, cancellationToken: cancellationToken);
projectId = project.Id;
}
catch (InvalidOperationException)
{
Expand All @@ -66,7 +68,7 @@ internal static class MSBuildWorkspaceLoader

LogWorkspaceDiagnostics(logger, logWorkspaceWarnings, workspace.Diagnostics);

return workspace;
return new LoadedWorkspace(workspace, projectId);

static void LogWorkspaceDiagnostics(ILogger logger, bool logWorkspaceWarnings, ImmutableList<WorkspaceDiagnostic> diagnostics)
{
Expand Down Expand Up @@ -94,4 +96,10 @@ static void LogWorkspaceDiagnostics(ILogger logger, bool logWorkspaceWarnings, I
}
}
}

/// <param name="ProjectId">Set to the project if the workspace is loaded in "project" mode.</param>
internal sealed record LoadedWorkspace(Workspace Workspace, ProjectId? ProjectId) : IDisposable
{
public void Dispose() => Workspace.Dispose();
}
}
4 changes: 4 additions & 0 deletions src/Dotnet.Format/dotnet-format/dotnet-format.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@
<PackageReference Include="System.CommandLine" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Microsoft.DotNet.ProjectTools\Microsoft.DotNet.ProjectTools.csproj" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="dotnet-format.UnitTests" />
<InternalsVisibleTo Include="dotnet-format.PerformanceTests" />
Expand Down
18 changes: 9 additions & 9 deletions src/Dotnet.Format/dotnet-format/xlf/Resources.cs.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 9 additions & 9 deletions src/Dotnet.Format/dotnet-format/xlf/Resources.de.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 9 additions & 9 deletions src/Dotnet.Format/dotnet-format/xlf/Resources.es.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading