Git Product home page Git Product logo

format's Introduction

Repository Consolidation

Going forward, the .NET format team is using the dotnet/sdk repository for further development and respond to issues formerly in that repository.

For finding the dotnet format usage, check the SDK repo.

format's People

Contributors

adamsitnik avatar alexperovich avatar am11 avatar arkalyanms avatar chcosta avatar chriselion avatar cosifne avatar dibarbet avatar dmonroym avatar dotnet-bot avatar dotnet-maestro-int[bot] avatar dotnet-maestro[bot] avatar ellahathaway avatar jeffhandley avatar jjonescz avatar jmarolf avatar joerobich avatar jonfortescue avatar leotsarev avatar mastr11 avatar michaelsimons avatar mmitche avatar mslukebo avatar nikolamilosavljevic avatar riarenas avatar sharwell avatar styxxy avatar viktorhofer avatar weihanli avatar wojciechcibor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

format's Issues

[Feature Request] Detailed logging to include line number and code violation details

I'd like to be able to run this tool on a codebase and have it give me a list of the files + associated line numbers and the rule violation, we'd use this information to plumb back into our CI reports.

At the moment all we know is that a particular file needed modifying, nothing more specific.

It looks like the changes are applied at a document level currently so I'm not sure if this level of fidelity is possible. Presumably as VS can offer it up however, then there must be a way.

`insert_final_newline=false` always wants to reformat files that end in multi-line comment

Running dotnet-format -w ConsoleFormatTest.sln always reports that it needs to format the file. changing final comment to \\ does not show this behavior. Also if there are no valid content it runs fine. I ran into having doxygen comments at the end of a file.

Minimal case

.editorconfig

# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true

# C# files
[*.cs]
insert_final_newline = false

minimal_case.cs

using System;

/**/
Version details
dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   2.1.701
 Commit:    8cf7278aa1

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.18362
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.1.701\

Host (useful for support):
  Version: 2.1.12
  Commit:  ccea2e606d

.NET Core SDKs installed:
  2.1.700 [C:\Program Files\dotnet\sdk]
  2.1.701 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download
dotnet format --version
4.0.40103+07078c3be865ad9e1ed2e02054e920dd0fd94628

dotnet-format doesn't find any files in legacy ASP.NET project

dotnet-format doesn't format anything in an ASP .NET non-Core project because it doesn't find any files. I can even reproduce this with a newly created empty project in Visual Studio 2019.

# dotnet-format -v diag
Formatting code files in workspace '....\WebApplication6.csproj'
Loading workspace.
Workspace loaded in 1277ms.
Formatting code files in project 'WebApplication6'.
Formatted 0 of 0 files in 263ms.
Format complete.

I narrowed it down to the following line in the csproj file. If I remove it, everything works as expected:

<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />

# dotnet-format -v diag
Formatting code files in workspace '....\WebApplication6.csproj'.
Loading workspace.
Workspace loaded in 2164ms.
Formatting code files in project 'WebApplication6'.
Formatting code file 'AssemblyInfo.cs'.
Formatting code file 'Class1.cs'.
Formatted code file 'Class1.cs'.
Formatted 1 of 3 files in 1535ms.
Format complete.

Version: 3.0.5-prerelease.19203.5+a138a5548eaa97c73d530260487fe8d3bec772a5

GitHub Action or GitHub App/Bot to Lint PRs

Does the DotNet team have any plans of making this a GitHub Action or GitHub Bot?

As it would be good to have this available to lint PRs automatically for us with GitHub Checks API and highlight the items in the GitHub diff view of a PR with using the dry-run option

Where finally you could use the Checks API to Automatically fix the errors & do a commit on a users behalf if they choose that they want to correct it.

https://developer.github.com/apps/quickstart-guides/creating-ci-tests-with-the-checks-api/#step-26-automatically-fixing-rubocop-errors

EOF newline not added

I have insert_final_newline = true in my .editorconfig but dotnet-format doesn't insert it.

FWIW, VS Code inserts it no matter what insert_final_newline is set to.

Format tool ends in error

Recently added format tool (v 3.1.37601) had been working in our solution workflow on a testing basis without issue for over a week, until this error showed up half-way through a build run:

Unhandled exception: System.AggregateException: One or more errors occurred. (Specified argument was out of the range of valid values.
Parameter name: start) ---> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: start
   at Microsoft.CodeAnalysis.Text.TextSpan..ctor(Int32 start, Int32 length)
   at Microsoft.CodeAnalysis.Text.ChangedText.Merge(ImmutableArray`1 oldChanges, ImmutableArray`1 newChanges)
   at Microsoft.CodeAnalysis.Text.ChangedText.Merge(IReadOnlyList`1 changeSets)
   at Microsoft.CodeAnalysis.Text.ChangedText.GetChangeRanges(SourceText oldText)
   at Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.WithChangedText(SourceText newText)
   at Microsoft.CodeAnalysis.DocumentState.IncrementallyParse(TextAndVersion newTextAndVersion, TreeAndVersion oldTreeAndVersion, CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.DocumentState.IncrementallyParseTreeAsync(ValueSource`1 oldTreeSource, ValueSource`1 newTextSource, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Microsoft.CodeAnalysis.DocumentState.GetSyntaxTreeAsync(CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.Document.GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken)
   at Roslyn.Utilities.TaskExtensions.WaitAndGetResult_CanCallOnBackground[T](Task`1 task, CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.Workspace.ApplyChangedDocument(ProjectChanges projectChanges, DocumentId documentId)
   at Microsoft.CodeAnalysis.Workspace.ApplyProjectChanges(ProjectChanges projectChanges)
   at Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.ApplyProjectChanges(ProjectChanges projectChanges)
   at Microsoft.CodeAnalysis.Workspace.TryApplyChanges(Solution newSolution, IProgressTracker progressTracker)
   at Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.TryApplyChanges(Solution newSolution, IProgressTracker progressTracker)
   at Microsoft.CodeAnalysis.Tools.CodeFormatter.FormatWorkspaceAsync(FormatOptions options, ILogger logger, CancellationToken cancellationToken) in /_/src/CodeFormatter.cs:line 88
   at Microsoft.CodeAnalysis.Tools.Program.Run(String workspace, String verbosity, Boolean dryRun, Boolean check, String files, IConsole console) in /_/src/Program.cs:line 99
   at System.CommandLine.Invocation.CommandHandler.GetResultCodeAsync(Object value, InvocationContext context)
   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass3_0.<<InvokeAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseErrorReporting>b__16_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass3_0.<<UseVersionOption>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseSuggestDirective>b__7_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseDebugDirective>b__4_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseHelp>b__14_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseDirective>b__6_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<RegisterWithDotnetSuggest>b__17_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseExceptionHandler>b__5_0>d.MoveNext()
---> (Inner Exception #0) System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: start
   at Microsoft.CodeAnalysis.Text.TextSpan..ctor(Int32 start, Int32 length)
   at Microsoft.CodeAnalysis.Text.ChangedText.Merge(ImmutableArray`1 oldChanges, ImmutableArray`1 newChanges)
   at Microsoft.CodeAnalysis.Text.ChangedText.Merge(IReadOnlyList`1 changeSets)
   at Microsoft.CodeAnalysis.Text.ChangedText.GetChangeRanges(SourceText oldText)
   at Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.WithChangedText(SourceText newText)
   at Microsoft.CodeAnalysis.DocumentState.IncrementallyParse(TextAndVersion newTextAndVersion, TreeAndVersion oldTreeAndVersion, CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.DocumentState.IncrementallyParseTreeAsync(ValueSource`1 oldTreeSource, ValueSource`1 newTextSource, CancellationToken cancellationToken)<---

and ends with:
Failed exitCode=1, command=dotnet format -w {sln-name} -v diag

Several attempts resulted in the same result, including with the --check flag.

First guess is that this is an error within dotnet-format, as none of the files currently being processed have a method with a parameter named 'start'.

Dropping the version back to v3.0.4 resolved the issue for us but wanted to make sure this issue got logged.

Running as a build event

If I open up a project properties in Visual Studio, go to "Build Events"
and add a pre-build or post-build step of "dotnet format"

Then the output that I get is:

1>------ Rebuild All started: Project: MyApp, Configuration: Debug Any CPU ------
1>MyApp -> C:\Code\MyApp\src\bin\Debug\netcoreapp2.2\MyApp.dll
1>Unhandled exception: System.AggregateException: An error occurred while writing to logger(s). (Object reference not set to an instance of an object.) ---> System.NullReferenceException: Object reference not set to an instance of an object.
1>   at Microsoft.CodeAnalysis.Tools.Logging.SimpleConsoleLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) in /_/src/Logging/SimpleConsoleLogger.cs:line 43
1>   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
1>   --- End of inner exception stack trace ---
1>   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
1>   at Microsoft.Extensions.Logging.Logger`1.Microsoft.Extensions.Logging.ILogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
1>   at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args)
1>   at Microsoft.CodeAnalysis.Tools.CodeFormatter.CodeFormatter.FormatWorkspaceAsync(ILogger logger, String solutionOrProjectPath, Boolean isSolution, Boolean logAllWorkspaceWarnings, Boolean saveFormattedFiles, CancellationToken cancellationToken) in /_/src/CodeFormatter.cs:line 30
1>   at Microsoft.CodeAnalysis.Tools.CodeFormatter.Program.Run(String workspace, String verbosity, Boolean dryRun, IConsole console) in /_/src/Program.cs:line 68
1>   at System.CommandLine.Invocation.CommandHandler.GetResultCodeAsync(Object value, InvocationContext context)
1>   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass3_0.<<InvokeAsync>b__0>d.MoveNext()
1>--- End of stack trace from previous location where exception was thrown ---
1>   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseErrorReporting>b__16_0>d.MoveNext()
1>--- End of stack trace from previous location where exception was thrown ---
1>   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass3_0.<<UseVersionOption>b__0>d.MoveNext()
1>--- End of stack trace from previous location where exception was thrown ---
1>   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseSuggestDirective>b__7_0>d.MoveNext()
1>--- End of stack trace from previous location where exception was thrown ---
1>   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseDebugDirective>b__4_0>d.MoveNext()
1>--- End of stack trace from previous location where exception was thrown ---
1>   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseHelp>b__14_0>d.MoveNext()
1>--- End of stack trace from previous location where exception was thrown ---
1>   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseDirective>b__6_0>d.MoveNext()
1>--- End of stack trace from previous location where exception was thrown ---
1>   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<RegisterWithDotnetSuggest>b__17_0>d.MoveNext()
1>--- End of stack trace from previous location where exception was thrown ---
1>   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseExceptionHandler>b__5_0>d.MoveNext()
1>---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
1>   at Microsoft.CodeAnalysis.Tools.Logging.SimpleConsoleLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) in /_/src/Logging/SimpleConsoleLogger.cs:line 43
1>   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)<---
1>
1>C:\Code\MyApp\src\MyApp.csproj(34,5): error MSB3073: The command "dotnet format" exited with code 1.
1>Done building project "MyApp.csproj" -- FAILED.
2>------ Rebuild All started: Project: MyApp.Tests, Configuration: Debug Any CPU ------
2>MyApp.Tests -> C:\Code\MyApp\test\bin\Debug\netcoreapp2.2\MyApp.Tests.dll
========== Rebuild All: 1 succeeded, 1 failed, 0 skipped ==========

If I'm doing the wrong thing here, what are other suggestions on how to run format very regularly,?

Support more .editorconfig code styles

I was quite happy when I stumbled across this article by Scott Hanselman, I installed dotnet-format globally and ran it. However it does not apply all rules, and I can't figure out if I'm missing something or if it's not intended to do so.

For example, it cleaned out some trailing whitespace which was great and moved curly braces to new lines.
It did not apply any rules regarding var vs types. Is this intended to be skipped, and if so is it planned to be supported?

indentation and blank line

please add consistent cleanup for blank lines and indentation. it would help a lot to enforce consistent code style.

InvalidOperationException: Sequence contains no elements

I get an InvalidOperationException when I run dotnet-format in a scheduled task. It works normally when I run the same command on the command line outside of a scheduled task.

I tried with the latest release and preview version 3.0.5-prerelease.19219.2.

Command line

dotnet-format --dry-run --workspace "C:\Users\User\Solution\Solution.sln"

Stacktrace

Unhandled exception: System.InvalidOperationException: Sequence contains no elements
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at Microsoft.CodeAnalysis.Tools.Program.Run(String workspace, String verbosity, Boolean dryRun, Boolean check, String files, IConsole console) in /_/src/Program.cs:line 79
   at System.CommandLine.Invocation.CommandHandler.GetResultCodeAsync(Object value, InvocationContext context)
   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass3_0.<<InvokeAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseErrorReporting>b__16_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass3_0.<<UseVersionOption>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseSuggestDirective>b__7_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseDebugDirective>b__4_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseHelp>b__14_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseDirective>b__6_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<RegisterWithDotnetSuggest>b__17_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseExceptionHandler>b__5_0>d.MoveNext()

Support formatting .cshtml and .razor files

I just tried
dotnet-format --files Home/Home.cshtml on my razor template but seems it does not read it at all.
(But tried on other filetypes and works great).
Is razor templates supported?

Option to align attribute arguments

In tests it can be nice to align attribute arguments for a table style format:

[TestCase("text.Equals(null)",         "text", "null", true,  true)]
[TestCase("text?.Equals(null)",        "text", "null", true,  true)]
[TestCase("Equals(text, null)",        null,   null,   false, false)]
[TestCase("object.Equals(text, null)", null,   null,   false, false)]
public void IsInstanceEquals(string check, string expectedLeft, string expectedRight, bool syntaxExpected, bool symbolExpected)
{
   ...
}

Don't know which files are formatted

I noticed when running the tool, there's no way to tell which files were actually formatted just from reading the output. If I'm reading the code correctly, it prints 'Formatting file x' before it knows if changes will be made. It also looks like those messages are only available with verbosity of diagnostic. It would be nice to be able to run --check or --dry-run and know which files I need to address.

Cannot write problem matcher for VS Code custom task

I'm trying to run dotnet format in a VS Code custom task. But, there's not enough detail in the output to write a decent problem matcher.

tasks.json

"problemMatcher": {
    "fileLocation": ["relative", "${workspaceFolder}"],
    "pattern": {
        "regexp": "^\\s*Formatted code file '(.*)'.$",
        "file": 1,
        "line": 2,
        "column": 3,
        "severity": 4,
        "message": 5
    }
}

The output doesn't provide enough of a file path for fileLocation. It doesn't provide line or column numbers. And it doesn't provide a specific message.

$ dotnet format --check --dry-run
  Formatting code files in workspace 'C:\Users\anthony\example\src\Example\Example.csproj'.
  Formatting code files in project 'Example'.
  Formatted code file 'Startup.cs'.
  Format complete.

Considerations

The important points to consider when redesigning the output:

  • The output should include workspace relative paths, no matter how I specify the --workspace
  • The output should include line and column number where the violation occurs
  • The output should not include severity, since that's not a relevant concept; the user can choose whichever is appropriate for their project: warning or error
  • The output should include not just the rule name, but whether the rule was required or not and how it was violated (more thought on this is probably required.. maybe append "not required" for false rules and "required" for true rules?)

Simple Problem Matcher

https://code.visualstudio.com/Docs/editor/tasks#_defining-a-problem-matcher

template

[workspace relative file path](line,col): [rule name]

output

$ dotnet format --check --dry-run
Formatting code files in workspace 'C:\Users\anthony\example\Example.sln'.
  src\Example\Startup.cs(26,22): space between parentheses not required
  src\Example\Controllers\ExampleController.cs(100,31): new line before open brace required
Format complete.

tasks.json (regex101)

{
    "label": "format",
    "command": "dotnet",
    "type": "process",
    "args": ["format", "--check", "--dry-run"],
    "problemMatcher": {
        "fileLocation": ["relative", "${workspaceFolder}"],
        "severity": "warning",
        "source": "dotnet format",
        "pattern": {
            "regexp": "^\\s+(.*)\\((\\d+),(\\d+)\\):\\s+(.*)$",
            "file": 1,
            "line": 2,
            "column": 3,
            "message": 4,
        }
    }
}

Multiline Problem Matcher

https://code.visualstudio.com/Docs/editor/tasks#_defining-a-multiline-problem-matcher

It's possible for a single file to have multiple violations and even for a single line in that file to have multiple violations. So, we need to output text that can be matched properly. I wonder if repeated lines and matches are simply added up in the problem windows. If so, then flat repeated output, not "stylish" nested output, might be best.

output

$ dotnet format --check --dry-run
Formatting code files in workspace 'C:\Users\anthony\example\Example.sln'.
  src\Example\Startup.cs(26,22): space between parentheses not required
  src\Example\Startup.cs(26,42): new line before open brace required
  src\Example\Controllers\ExampleController.cs(100,31): new line before open brace required
Format complete.

tasks.json
No change necessary! Repeated lines worked! I tested using a text file containing the expected output and a fake cmd.exe task.

{
    "label": "format",
    "command": "cmd",
    "type": "process",
    "args": ["/c", "type", "example.txt"],
    "problemMatcher": {
        "fileLocation": ["relative", "${workspaceFolder}"],
        "severity": "warning",
        "source": "dotnet format",
        "pattern": {
            "regexp": "^\\s+(.*)\\((\\d+),(\\d+)\\):\\s+(.*)$",
            "file": 1,
            "line": 2,
            "column": 3,
            "message": 4,
        }
    }
}

Background/Watching Problem Matcher

https://code.visualstudio.com/Docs/editor/tasks#_background-watching-tasks

What about when we want to run formatting constantly in the background? Maybe via dotnet watch? We need to implement the task slightly differently. Luckily, dotnet format already outputs a begin and end statement.

tasks.json

I tweaked the fake cmd.exe task to output the contents of that file in a loop. You can modify the contents during the wait time. The problem matcher seems to have some trouble clearing out the last problem for a given file, but if you stack up multiple problems and remove them one-by-one, you can see the general behavior.

{
    "label": "format",
    "command": "cmd",
    "type": "process",
    "args": ["/c", "FOR /L %G IN (1,1,100) DO timeout /T 10 & type example.txt"],
    "isBackground": true,
    "problemMatcher": {
        "fileLocation": ["relative", "${workspaceFolder}"],
        "severity": "warning",
        "source": "dotnet format",
        "pattern": {
            "regexp": "^\\s+(.*)\\((\\d+),(\\d+)\\):\\s+(.*)$",
            "file": 1,
            "line": 2,
            "column": 3,
            "message": 4,
        },
        "background": {
            "activeOnStart": true,
            "beginsPattern": "^Formatting code files in workspace\\s+'(.*)'\\.$",
            "endsPattern": "^Format complete\\.$"
        },
    }
}

Formatting not Working for Webapplication

The formatter is not working for web application project. I am seeing the following output. The version that I am using is "4.0.40103+07078c3be865ad9e1ed2e02054e920dd0fd94628"
C:\code>dotnet-format --files "presentation\web\proj\about.aspx.cs" -w presentation\web\proj\webapplication.csproj -v diag -fs Formatting code files in workspace 'C:\code\prism\presentation\web\proj\webapplication.csproj'. Loading workspace. Complete in 1498ms. Determining formattable files. Complete in 14ms. Running formatters. Analyzing code style. Analysis complete in 592ms. Complete in 677ms. Formatted 0 of 0 files. Format complete in 2194ms.

Dry run output format options

I'm working on a tool that takes the output from a dry run and reports on it. Right now I'm having to parse this with a regex to get the file path, line number, and message. Is there a way to output this as json, or to write my own output formatter and use it as a plugin?

The files option doesn't allow to format files wants to format all workspace

Using --files to format a single file doesn't work

dotnet format --files Ice\Collections.cs
  Could not find a MSBuild project file or solution file in 'D:\3.7\ice-master\csharp\src'. Specify which to use with the --workspace option.

dotnet-format --version
3.1.37601+256f37159dc60b29f76999749f57f4338324f102

dotnet-format throws unhandled exception: Microsoft.Build.Exceptions.InvalidProjectFileException

Version Used:
dotnet tool install -g dotnet-format --version 3.0.0-beta4-19105-10
Steps to Reproduce:

  1. Run dotnet format on this codebase https://github.com/wieslawsoltes/Core2D/tree/5f6fb6af5047edd0e359c3b1391dbd7e3058bc5f

  2. This is the msbuild project that is causing the exception
    https://github.com/AvaloniaUI/Avalonia/blob/1e91484c689562b257cc1d75828bc95fd79583f6/packages/Avalonia/AvaloniaBuildTasks.targets#L7-L9

Expected Behavior:
No exception is thrown.
Actual Behavior:
Exception is thrown:

PS C:\DOWNLOADS\GitHub\Core2D> dotnet format
  Formatowanie plików kodu w obszarze roboczym "C:\DOWNLOADS\GitHub\Core2D\Core2D.sln".
Unhandled exception: Microsoft.Build.Exceptions.InvalidProjectFileException: The result "" of evaluating the value "$(AvaloniaBuildTasksLocation)" of the "AssemblyFile" attribute in element <UsingTask> is not valid.  C:\Users\Wiesiek\.nuget\packages\avalonia\0.7.1-cibuild0001356-beta\build\AvaloniaBuildTasks.targets
   at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(String errorSubCategoryResourceName, IElementLocation elementLocation, String resourceName, Object[] args)
   at Microsoft.Build.Shared.ProjectErrorUtilities.VerifyThrowInvalidProject[T1,T2,T3,T4](Boolean condition, String errorSubCategoryResourceName, IElementLocation elementLocation, String resourceName, T1 arg0, T2 arg1, T3 arg2, T4 arg3)
   at Microsoft.Build.Execution.TaskRegistry.RegisterTasksFromUsingTaskElement[P,I](ILoggingService loggingService, BuildEventContext buildEventContext, String directoryOfImportingFile, ProjectUsingTaskElement projectUsingTaskXml, TaskRegistry taskRegistry, Expander`2 expander, ExpanderOptions expanderOptions, IFileSystem fileSystem)
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateUsingTaskElement(String directoryOfImportingFile, ProjectUsingTaskElement projectUsingTaskElement)
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate(ILoggingService loggingService, BuildEventContext buildEventContext)
   at Microsoft.Build.Evaluation.Project.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.CodeAnalysis.MSBuild.ProjectFile.GetProjectFileInfosAsync(CancellationToken cancellationToken) in /_/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFile.cs:line 66
   at Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Worker.DoOperationAndReportProgressAsync[TResult](ProjectLoadOperation operation, String projectPath, String targetFramework, Func`1 doFunc)
   at Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Worker.LoadProjectFileInfosAsync(String projectPath, DiagnosticReportingOptions reportingOptions, CancellationToken cancellationToken) in /_/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs:line 201
   at Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Worker.LoadProjectInfosFromPathAsync(String projectPath, DiagnosticReportingOptions reportingOptions, CancellationToken cancellationToken) in /_/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs:line 235
   at Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Worker.LoadAsync(CancellationToken cancellationToken) in /_/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs:line 155
   at Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadSolutionInfoAsync(String solutionFilePath, IProgress`1 progress, CancellationToken cancellationToken) in /_/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.cs:line 199
   at Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(String solutionFilePath, IProgress`1 progress, CancellationToken cancellationToken) in /_/src/Workspaces/Core/MSBuild/MSBuild/MSBuildWorkspace.cs:line 183
   at Microsoft.CodeAnalysis.Tools.CodeFormatter.CodeFormatter.FormatWorkspaceAsync(ILogger logger, String solutionOrProjectPath, Boolean isSolution, Boolean logAllWorkspaceWarnings, Boolean saveFormattedFiles, CancellationToken cancellationToken) in /_/src/Tools/dotnet-format/CodeFormatter.cs:line 53
   at Microsoft.CodeAnalysis.Tools.CodeFormatter.Program.Run(String workspace, String verbosity, Boolean dryRun, IConsole console) in /_/src/Tools/dotnet-format/Program.cs:line 68
   at System.CommandLine.Invocation.CommandHandler.GetResultCodeAsync(Object value, InvocationContext context)
   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass3_0.<<InvokeAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseErrorReporting>b__16_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass3_0.<<UseVersionOption>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseSuggestDirective>b__7_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseDebugDirective>b__4_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseHelp>b__14_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseDirective>b__6_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<RegisterWithDotnetSuggest>b__17_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseExceptionHandler>b__5_0>d.MoveNext()

Should major version be increased every time a new rule is added?

Recently released version 3.1 is a minor update as it adds new features.
However new features means handling new rules, for example it now handle the new line at end of file rule.
This mean that if you are relying on dotnet format on your build pipeline, and some of your files are not following this previously ignored rule, on update your build will fail, which is a bit nasty especially if you build install the latest version of the tool.
So from a consumer point of you, this actually behave like a breaking change, so maybe it deserve a major version update.
Thoughts?

Dotnet 3x

Using the command line

dotnet tool install -g dotnet-format --version 4.0.40103 --add-source https://dotnet.myget.org/F/format/api/v3/index.json

Under travis (Mac), we obtains this error:

Welcome to .NET Core 3.0!
---------------------
SDK Version: 3.0.100
----------------
Explore documentation: https://aka.ms/dotnet-docs
Report issues and find source on GitHub: https://github.com/dotnet/core
Find out what's new: https://aka.ms/dotnet-whats-new
Learn about the installed HTTPS developer cert: https://aka.ms/aspnet-core-https
Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli-docs
Write your first app: https://aka.ms/first-net-core-app
--------------------------------------------------------------------------------------
dyld: lazy symbol binding failed: Symbol not found: _utimensat
  Referenced from: /usr/local/share/dotnet/shared/Microsoft.NETCore.App/3.0.0/System.Native.dylib
  Expected in: /usr/lib/libSystem.B.dylib
dyld: Symbol not found: _utimensat
  Referenced from: /usr/local/share/dotnet/shared/Microsoft.NETCore.App/3.0.0/System.Native.dylib
  Expected in: /usr/lib/libSystem.B.dylib
The tool package could not be restored.
Tool 'dotnet-format' failed to install. This failure may have been caused by:
* You are attempting to install a preview release and did not use the --version option to specify the version.
* A package by this name was found, but it was not a .NET Core tool.
* The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
* You mistyped the name of the tool.

In linux it works perfect

--check along with --dry-run not working as expected

Hi,

My intention was to get a set of files and the errors associated with them with the --check command. But seems like --check returns just a non-zero response if there are any files that do not conform to the rules.

I tried the same, but the command 'dotnet format --check' doesn't seem to be different from running dotnet format without any options. They both format the file and save changes to disk.

Now, I tried to run the option --dry-run --check (as mentioned in another issue), so that it shows just the files that have error and returns a non-zero exit code. But, the command executed successfully.

Please find below the code against which the command was run:

       class Program
       {
          static void Main(string[] args)
         {
            test();
            Console.WriteLine("Inside Main");
         }
         public static void test()
         {
            var i = 0;
            if (i == 0){
                Console.WriteLine("i is 0");
            }
            else
            {
                Console.WriteLine("i is not 0");
            }
            Console.WriteLine("Inside Test method");
         }
       }

Rule:
csharp_new_line_before_else = true
csharp_new_line_before_open_brace = all

When I ran > dotnet format --check
The braces were formatted in the file Program.cs and the changes were saved.

Now, I tried running > dotnet format --dry-run --check
With the hope that it will exit with non-zero exit code. But it showed the below message:

Formatting code files in workspace 'C:\Project\MyHobbyProjects\EditoConfigCLISample\ConsoleApp1\ConsoleApp1.sln'.
Loading workspace.
Workspace loaded in 1785ms.
Formatting code files in project 'ConsoleApp1'.
Formatting code file 'Program.cs'.
Formatted code file 'Program.cs'.
Formatted 1 of 3 files in 1275ms.
Format complete.

Is it possible to display the files that doesn't abide by EditorConfig and the rules that it does not conform to?

Thanks!

Clarify which languages are supported

Please clarify at the top of Readme.md which languages are supported. Also change the error message Unhandled exception: System.InvalidOperationException: Cannot open project ... because the file extension '.fsproj' is not associated with a language. to something less ridiculous.

Error installing without version specified

When I tried
dotnet tool install -g dotnet-format

I received the following error:

The tool package could not be restored.
Tool 'dotnet-format' failed to install. This failure may have been caused by:

* You are attempting to install a preview release and did not use the --version option to specify the version.
* A package by this name was found, but it was not a .NET Core tool.
* The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
* You mistyped the name of the tool.

I have the following SDK's installed

2.1.403 [C:\Program Files\dotnet\sdk]
2.1.505 [C:\Program Files\dotnet\sdk]
2.1.602 [C:\Program Files\dotnet\sdk]
2.1.700-preview-009597 [C:\Program Files\dotnet\sdk]
2.1.700-preview-009601 [C:\Program Files\dotnet\sdk]
2.1.700-preview-009618 [C:\Program Files\dotnet\sdk]
2.2.101 [C:\Program Files\dotnet\sdk]
2.2.202 [C:\Program Files\dotnet\sdk]
3.0.100-preview4-011223 [C:\Program Files\dotnet\sdk]

When I tried to global.json myself to 2.2.2 I received the same error.

When I did the following, it worked fine:
dotnet tool install -g dotnet-format --version 3.0.4

Not sure if this is related to dotnet format itself or if this is a problem elsewhere since I have previews.

Why not fail in error condition ?

I am using the latest version of the tool. One thing I want to clarify why it does not show an error if it is mentioned in the editorconfig, e.g.: dotnet_style_object_initializer = true:error.

The second thing does the tool support all attributed defined at roslyn-editorconfig ?

Upgrade to .NET Core 2.2

This project throws an incompatible error while being added to a project with .Net Core 2.2. Is it possible to update the target framework to core 2.2 or to .net standard so that it supports all of them?

Ability to check formatting / code style without writing to disk

Hello!

Many existing code formatting tools ( Prettier, ClangFormat ) support checking code format without modifying source files.

Currently to only check formatting I can implement some wrapper which will clone source code, run `dotnet-format' on this clone and then compare formatted files with original source code. But this seems to be too complex approach for such scenario.

Do you plan to implement feature allowing to check format in dotnet-format (might be a console application option)?...

Prettier-style line breaking

It's my understanding the the project doesn't do line breaking the way Prettier does: Inserting and removing line breaks depending on the length of the resulting lines.

I can't find a rationale for this and I can't find a ticket mentioning this.

It's technically easy to implement (using Roslyn), but it's not entirely independent from other formatting jobs (eg. whether opening braces should always be on a new line).

So what's going on? Is there no love for Prettier's approach?

Run Roslyn Analyzers and CodeFixes

Configuration for diagnostic severity can now be expressed in .editorconfig files. dotnet format should be able to run diagnostics and apply fixes for those of a specified severity.

As a first step dotnet format could support the known set of CodeStyle diagnostics and fixes in Roslyn.
As a further enhancement it could run Analyzers installed via NuGet.

Exception occured when redirect output

Overview

Exception occured when attempting to redirect dotnet format command output.

Environment

dotnet-format version is 3.0.0-beta4-19105-10

my dotnet --info output is here.

.NET Core SDK (global.json を反映):
 Version:   3.0.100-preview-010184
 Commit:    c57bde4593

ランタイム環境:
 OS Name:     Windows
 OS Version:  6.3.9600
 OS Platform: Windows
 RID:         win81-x64
 Base Path:   C:\Program Files\dotnet\sdk\3.0.100-preview-010184\

Host (useful for support):
  Version: 3.0.0-preview-27324-5
  Commit:  63a01b08e5

.NET Core SDKs installed:
  1.0.0-preview2-003121 [C:\Program Files\dotnet\sdk]
  1.0.0-preview2-003131 [C:\Program Files\dotnet\sdk]
  1.0.0-preview2-003133 [C:\Program Files\dotnet\sdk]
  1.0.0-preview2-003156 [C:\Program Files\dotnet\sdk]
  1.0.0-preview2-1-003177 [C:\Program Files\dotnet\sdk]
  1.0.4 [C:\Program Files\dotnet\sdk]
  2.0.0 [C:\Program Files\dotnet\sdk]
  2.0.2 [C:\Program Files\dotnet\sdk]
  2.1.2 [C:\Program Files\dotnet\sdk]
  2.1.3 [C:\Program Files\dotnet\sdk]
  2.1.4 [C:\Program Files\dotnet\sdk]
  2.1.100 [C:\Program Files\dotnet\sdk]
  2.1.104 [C:\Program Files\dotnet\sdk]
  2.1.202 [C:\Program Files\dotnet\sdk]
  2.1.300 [C:\Program Files\dotnet\sdk]
  2.1.301 [C:\Program Files\dotnet\sdk]
  2.1.400 [C:\Program Files\dotnet\sdk]
  2.1.401 [C:\Program Files\dotnet\sdk]
  2.1.402 [C:\Program Files\dotnet\sdk]
  2.1.403 [C:\Program Files\dotnet\sdk]
  2.1.500 [C:\Program Files\dotnet\sdk]
  2.1.503 [C:\Program Files\dotnet\sdk]
  2.1.600-preview-009472 [C:\Program Files\dotnet\sdk]
  2.1.600-preview-009497 [C:\Program Files\dotnet\sdk]
  2.2.100 [C:\Program Files\dotnet\sdk]
  2.2.200-preview-009748 [C:\Program Files\dotnet\sdk]
  2.2.200-preview-009804 [C:\Program Files\dotnet\sdk]
  3.0.100-preview-010184 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.2 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.4 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.1.7 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.All 2.2.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.2 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.4 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.1.7 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 2.2.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.0.0-preview-19075-0444 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 1.0.0-rc2-3002702 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.0.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.0.3 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 1.1.2 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.3 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.4 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.0.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.2 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.3-servicing-26724-03 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.4 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.1.7 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.2.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 2.2.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.0.0-preview-27324-5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.WindowsDesktop.App 3.0.0-preview-27325-3 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

Step to Reproduce

  1. dotnet tool install -g dotnet-format --version 3.0.0-beta4-19105-10
  2. dotnet new console --name [project name]
  3. cd [project name]
  4. dotnet format > output.log

Expected Result

Program.cs is formatted and output.log is created as dotnet-format output

Actual Result

output following exception and exit with code 1.

Unhandled exception: System.AggregateException: An error occurred while writing to logger(s). (Object reference not set to an instance of an object.) ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.CodeAnalysis.Tools.Logging.SimpleConsoleLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) in /_/src/Tools/dotnet-format/Logging/SimpleConsoleLogger.cs:line 43
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   at Microsoft.Extensions.Logging.Logger`1.Microsoft.Extensions.Logging.ILogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args)
   at Microsoft.CodeAnalysis.Tools.CodeFormatter.CodeFormatter.FormatWorkspaceAsync(ILogger logger, String solutionOrProjectPath, Boolean isSolution, Boolean logAllWorkspaceWarnings, Boolean saveFormattedFiles, CancellationToken cancellationToken) in /_/src/Tools/dotnet-format/CodeFormatter.cs:line 30
   at Microsoft.CodeAnalysis.Tools.CodeFormatter.Program.Run(String workspace, String verbosity, Boolean dryRun, IConsole console) in /_/src/Tools/dotnet-format/Program.cs:line
68
   at System.CommandLine.Invocation.CommandHandler.GetResultCodeAsync(Object value, InvocationContext context)
   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass3_0.<<InvokeAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseErrorReporting>b__16_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass3_0.<<UseVersionOption>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseSuggestDirective>b__7_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseDebugDirective>b__4_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseHelp>b__14_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseDirective>b__6_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<RegisterWithDotnetSuggest>b__17_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseExceptionHandler>b__5_0>d.MoveNext()
---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.CodeAnalysis.Tools.Logging.SimpleConsoleLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) in /_/src/Tools/dotnet-format/Logging/SimpleConsoleLogger.cs:line 43
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)<---

I think the cause is System.Commandline.Rendering.Terminal.GetTerminal() returns null if redirecting.
This behavior caused SimpleLogger._terminal becomes null.

--folder option missing from installed version

I attempted to install and use dotnet-format, but was unable to use the --folder option. Help showed a list of all the options shown on the How To Use resource on the top page, with the exception of -f. I tried uninstalling and reinstalling with versions 3.1.37601 and 3.0.4 but neither showed -f as a viable option. Using dotnet-format with the other options (-w, --dry-run) worked as expected.

The project I'm working on has a number of plugins and for merging and verification purposes I would very much like to avoid reformatting across the entire project. Is --folder not an option available in the latest stable build, or have I made a mistake at some point in installation or usage?

Update "how to use" section to state it only works in a solution directory

For the dummies amongst us, it'd be useful if the How To Use section had something indicating that if you're not in a project folder dotnet-format doesn't get executed. I was trying all sorts of things to confirm it had installed correctly, but not in a project directory.

dotnet-format
dotnet tool list
dotnet tool format
dotnet tool run dotnet-format
dotnet tool run format
dotnet dotnet-format
dotnet format

cd \code\myproject
dotnet-format

Ahhhh! Definitely a PEBKAC issue, but still, maybe it'll help other the other PEBKACs out there if the doco is aimed at n00bs.

Ignore directories

First off, I love this; great work!! I have a few directories I need to exclude. In Visual Studio this is easy to achieve by making editorconfig files in those directories and setting them as root root = true and no other content. Visual Studio respects that editorconfig and formatting within that directory applies no changes because it doesn't respect VS default formatting preferences when an editorconfig is present.

When running dotnet-format, all projects are formatted, including the projects with these extra editorconfig files set as root and no other content. I presume this is by design because, this repo's readme states that "Preferences will be read from an .editorconfig file, if present, otherwise a default set of preferences will be used.".

I can always undo changes rendered in those problem directories or I can specifically run format for the specific project files and code files via a pre-built exe or powershell script but that seems unnecessary.
Thank you again for this tool, it's great.

Sometimes, --dry-run option print incorrect format

Version: 3.0.5-prerelease.19201.4+9a83fbd542735f7764c74f81ee6e3225a24fb8ae

Description:
I found sometimes dotnet-format print Formatting... without appending a newline. I can reproduce by this command:

$ for i in (seq 1 10); dotnet-format -v diagnostic -w ClockupStudio.YingGooDiEx.Player.csproj --dry-run;end

After run commands, sometimes it print:

 Formatting code files in project 'ClockupStudio.YingGooDiEx.Player'.
  Formatting code file 'PlayerSetting.cs'.
  Formatting code file 'Health.cs'.  Formatting code file 'PlayerDirection.cs'.
  Formatting code file 'PlayerSpriteSetting.cs'.

  Formatting code file 'MoveTracking.cs'.
  Formatting code file 'MovementBehaviour.cs'.
  Formatting code file 'Bullet.cs'.
  Formatting code file 'Walk.cs'.
  Formatting code file 'LifeContainer.cs'.
  Formatting code file 'PlayerHealthBehaviour.cs'.
  Formatting code file 'FireBulletBehaviour.cs'.
  Formatted code file 'Bullet.cs'.
  Skipping referenced project 'ClockupStudio.YingGooDiEx.Pool'.
  Skipping referenced project 'ClockupStudio.YingGooDiEx.Enemy'.
  Skipping referenced project 'ClockupStudio.YingGooDiEx.Controller'.
  Formatted 1 of 11 files in 799ms.
  Format complete.

And sometimes it print result as expected:

Formatting code files in project 'ClockupStudio.YingGooDiEx.Player'.
  Formatting code file 'PlayerSetting.cs'.
  Formatting code file 'PlayerDirection.cs'.
  Formatting code file 'Health.cs'.
  Formatting code file 'PlayerSpriteSetting.cs'.
  Formatting code file 'MovementBehaviour.cs'.
  Formatting code file 'MoveTracking.cs'.
  Formatting code file 'Bullet.cs'.
  Formatting code file 'Walk.cs'.
  Formatting code file 'LifeContainer.cs'.
  Formatting code file 'PlayerHealthBehaviour.cs'.
  Formatting code file 'FireBulletBehaviour.cs'.
  Formatted code file 'Bullet.cs'.
  Skipping referenced project 'ClockupStudio.YingGooDiEx.Pool'.
  Skipping referenced project 'ClockupStudio.YingGooDiEx.Enemy'.
  Skipping referenced project 'ClockupStudio.YingGooDiEx.Controller'.
  Formatted 1 of 11 files in 837ms.
  Format complete.

I attached file that come from command that I ran above here

Question: Diagnostic Verbosity

When I pass -v diag flag (with --dry-run), I can see that 1 file is formatted, but I don't see what formatting rules were violated and where. Is there a way to show this info?

--check option does not work

The new dotnet format --check does not seem to work. I would assume that it only shows if the .editorconfig rules have been applied or not but does not touch my files.

Steps to reproduce

1. Create a new project

dotnet new console -n Test
cd Test

2. Add .editorconfig

root = true

[*.cs]
csharp_new_line_before_open_brace = false

3. Run check option

dotnet format --check

Expected outcome

The dotnet format --check command fails with non-zero exit code, beacse Program.cs does not apply to the csharp_new_line_before_open_brace = false rule.

Actual outcome

The Program.cs file gets reformatted and the dotnet format --check` command completes successfully.

Possible to set this up within Jetbrains Rider using the folder watch to format on save?

Has anyone set this up with Rider? I have never set up a watcher from scratch as with GoLand you just tell it to format on save and it is built into the IDE, but I would imagine it should be possible to set this up to be able to format the particular file you are working on and autoformat it on file save?

I tried to see if I could get a single folder to format but I believe I might have done it incorrectly as nothing happened. When I omitted the --files and subsequent path it did indeed work, but of course it did the entire project which then forced a reimport of all of the files into Unity which would end up becoming quite time consuming on larger projects.

This is what I attempted:

dotnet-format -v diag --workspace /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Navigation_DOTS_20192.sln --files  /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Assets/_instance.id/_ECS/scripts/Waypoint/Systems

I made a few purposeful changes to force the need for formatting and tried again with increased verbosity:

~ » dotnet-format -v diag --workspace /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Navigation_DOTS_20192.sln --files  /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Assets/_instance.id/_ECS/scripts/Waypoint/Systems
  Formatting code files in workspace '/home/mosthated/_dev/_unity/Navigation_DOTS_20192/Navigation_DOTS_20192.sln'.
  Loading workspace.
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Sirenix.OdinInspector.CompatibilityLayer.Editor.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Sirenix.OdinInspector.CompatibilityLayer.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/BovineLabs.Entities.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Assembly-CSharp-firstpass.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Sirenix.OdinInspector.CompatibilityLayer.Editor.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Sirenix.OdinInspector.CompatibilityLayer.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/BovineLabs.Entities.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Assembly-CSharp-firstpass.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Sirenix.OdinInspector.CompatibilityLayer.Editor.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Sirenix.OdinInspector.CompatibilityLayer.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/BovineLabs.Entities.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Assembly-CSharp-firstpass.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Assembly-CSharp.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Assembly-CSharp-Editor-firstpass.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Sirenix.OdinInspector.CompatibilityLayer.Editor.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Sirenix.OdinInspector.CompatibilityLayer.csproj
  Found project reference without a matching metadata reference: /home/mosthated/_dev/_unity/Navigation_DOTS_20192/BovineLabs.Entities.csproj
  Complete in 2385ms.
  Determining formattable files.
  Complete in 188ms.
  Running formatters.
  Complete in 11ms.
  Formatted 0 of 395 files.
  Format complete in 2589ms.

This is what ended up working though and did all files.

dotnet-format -v diag --workspace /home/mosthated/_dev/_unity/Navigation_DOTS_20192/Navigation_DOTS_20192.sln

dotnet-format.exe 3.0.0 is looking for 3.0.0-beta4-19105-10 assemblies

Version Used:

dotnet-format.exe 3.0.0

Steps to Reproduce:

  1. Install dontet-format 3.0.0 - dotnet tool install --global dotnet-format --version 3.0.0
  2. run dotnet-format

Expected Behavior:

Runs!

Actual Behavior:

The application to execute does not exist: 'C:\Users\me\.dotnet\tools\.store\dotnet-format\3.0.0-beta4-19105-10\dotnet-format\3.0.0-beta4-19105-10\tools\netcoreapp2.1\any\dotnet-format.dll'.

Tool doesn't fix naming issues

I run the tool on my solution and it fixed the indentation problem (which I'm really happy about).
However, the namings were not fixed- Visual Studio still lists naming issues. Doesn't the tool fix naming violations?

Check option does not seem to work

I installed the latest version from myGet, but I can't seem to get the --check option to work. When I run it, it formats the files rather than terminating with a non-zero code.

Unhandled exception: System.AggregateException: An error occurred while writing to logger(s). (Object reference not set to an instance of an object.) ---> System.NullReferenceException: Object reference not set to an instance of an object.

dotnet-format crashes for me in CI.

Unhandled exception: System.AggregateException: An error occurred while writing to logger(s). (Object reference not set to an instance of an object.) ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.CodeAnalysis.Tools.Logging.SimpleConsoleLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) in /_/src/Logging/SimpleConsoleLogger.cs:line 43
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   at Microsoft.Extensions.Logging.Logger`1.Microsoft.Extensions.Logging.ILogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args)
   at Microsoft.CodeAnalysis.Tools.CodeFormatter.CodeFormatter.FormatWorkspaceAsync(ILogger logger, String solutionOrProjectPath, Boolean isSolution, Boolean logAllWorkspaceWarnings, Boolean saveFormattedFiles, CancellationToken cancellationToken) in /_/src/CodeFormatter.cs:line 30
   at Microsoft.CodeAnalysis.Tools.CodeFormatter.Program.Run(String workspace, String verbosity, Boolean dryRun, IConsole console) in /_/src/Program.cs:line 68
   at System.CommandLine.Invocation.CommandHandler.GetResultCodeAsync(Object value, InvocationContext context)
   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass3_0.<<InvokeAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseErrorReporting>b__16_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass3_0.<<UseVersionOption>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseSuggestDirective>b__7_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseDebugDirective>b__4_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseHelp>b__14_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseDirective>b__6_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<RegisterWithDotnetSuggest>b__17_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseExceptionHandler>b__5_0>d.MoveNext()
---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.CodeAnalysis.Tools.Logging.SimpleConsoleLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) in /_/src/Logging/SimpleConsoleLogger.cs:line 43
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)<---

https://travis-ci.org/felixfbecker/PSKubectl/builds/500837361#L695

Extensionpoint for custom rules

Hi,

I've played around with the .editorconfig and this tool and I find it really helpful (like meantioned on other thread).

Currently I'm thinking about if it will be valuable to have some extension points here to be apple to apply rules that are not supported by the .editorconfig.

Maybe something that it is possible to implement some custom "CSharpOnlyFormattingRule" like this here https://github.com/dotnet/codeformatter/blob/master/src/Microsoft.DotNet.CodeFormatting/Rules/UsingLocationRule.cs that will be loaded and also applied after the setting of the .editorconfig has been applied. I know that my refrence is possible with .editorconfig, it is more like how I found it useful.

This would over the option to apply custom rules to the code that is specific for a company.

Are there any plans?

Thanks
Daniel

Check file encoding

It would be very useful to be able to check if the files are in utf8 (with or without boom).

Is it possible to do it now?

dotnet-format: accept a list of files to format (instead of a full workspace)

Version Used: dotnet-format 3.0.0-beta4-19105-10 (70a2f514eb3932648f771b086834cb0a376fee20)

Steps to Reproduce:

  1. Change a number of files (so they appear in VCS output, such as git diff --name-only)
  2. Pass that file list as command line parameters into dotnet format (or try to pipe them into stdin)

Expected Behavior:
dotnet format only changes the passed files instead of the whole project (or solution)

Actual Behavior:
dotnet format errors out with either "Both a MSBuild project file and solution file found in $path. Specify which one to use with the --workspace option" or "Unrecognized command or argument 'path/to/file.cs'". Or somewhat...not sure if I should call it worse or just different: it runs successfully, formatting all files referenced by the project or solution (in case only a single project or solution file is found in the current working directory).

Intended Use-Case:
We run a few things as part of our CI (such as static analysis), and we'd also like to use dotnet format as a way to enforce code style before it even reaches the first review by a human. Right now this isn't too feasible as dotnet format takes quite a while on larger solutions with a lot of files; and running it only on the changed files would significantly improve the time to feedback (with the intention to simply error out in case it produces any changes in the CI working copy).

For smaller change sets, passing file names as command line parameter is likely a usable solution, but the larger the change set the more likely it would be to reach a length limit for arguments; so piping it into stdin would probably be the better approach there.

Or, alternatively (if it makes sense to do so), support this use case from within dotnet format itself (or a tool derived from it), along with the --dry-run switch: stop processing as soon as a change would have been made and return an error code that can be checked by a caller.

Thoughts and ideas are more than welcome, especially in case I missed some other tooling that already does this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.