Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Enhance --files option #533

Merged
merged 2 commits into from
Feb 12, 2020
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,6 @@ ASALocalRun/

# MFractors (Xamarin productivity tool) working folder
.mfractor/

# OS-specific files
**/.DS_Store
52 changes: 52 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": "dotnet-format -f . --dry-run",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/artifacts/bin/dotnet-format/Debug/netcoreapp2.1/dotnet-format.dll",
"args": [
"-f",
".",
"-v",
"diag",
"--dry-run"
],
"cwd": "${workspaceFolder}/src",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": "dotnet-format -w format.sln --dry-run",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/artifacts/bin/dotnet-format/Debug/netcoreapp2.1/dotnet-format.dll",
"args": [
"-w",
"format.sln",
"-v",
"diag",
"--dry-run"
],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
42 changes: 42 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/src/dotnet-format.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/src/dotnet-format.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/src/dotnet-format.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}
31 changes: 16 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

[![MyGet](https://img.shields.io/dotnet.myget/format/vpre/dotnet-format.svg?label=myget)](https://dotnet.myget.org/feed/format/package/nuget/dotnet-format)

|Branch| Windows (Debug)| Windows (Release)| Linux (Debug) | Linux (Release) | Localization (Debug) | Localization (Release) |
|Branch| Windows (Debug)| Windows (Release)| Linux (Debug) | Linux (Release) | Localization (Debug) | Localization (Release) |
|---|:--:|:--:|:--:|:--:|:--:|:--:|
[master](https://github.com/dotnet/format/tree/master)|[![Build Status](https://dev.azure.com/dnceng/public/_apis/build/status/dotnet/format/dotnet.format?branchName=master&jobName=Windows&configuration=debug&label=build)](https://dev.azure.com/dnceng/public/_build/latest?definitionId=347&branchName=master)|[![Build Status](https://dev.azure.com/dnceng/public/_apis/build/status/dotnet/format/dotnet.format?branchName=master&jobName=Windows&configuration=release&label=build)](https://dev.azure.com/dnceng/public/_build/latest?definitionId=347&branchName=master)|[![Build Status](https://dev.azure.com/dnceng/public/_apis/build/status/dotnet/format/dotnet.format?branchName=master&jobName=Linux&configuration=debug&label=build)](https://dev.azure.com/dnceng/public/_build/latest?definitionId=347&branchName=master)|[![Build Status](https://dev.azure.com/dnceng/public/_apis/build/status/dotnet/format/dotnet.format?branchName=master&jobName=Linux&configuration=release&label=build)](https://dev.azure.com/dnceng/public/_build/latest?definitionId=347&branchName=master)|[![Build Status](https://dev.azure.com/dnceng/public/_apis/build/status/dotnet/format/dotnet.format?branchName=master&jobName=Windows_Spanish&configuration=debug&label=build)](https://dev.azure.com/dnceng/public/_build/latest?definitionId=347&branchName=master)|[![Build Status](https://dev.azure.com/dnceng/public/_apis/build/status/dotnet/format/dotnet.format?branchName=master&jobName=Windows_Spanish&configuration=release&label=build)](https://dev.azure.com/dnceng/public/_build/latest?definitionId=347&branchName=master)|

Expand Down Expand Up @@ -41,30 +41,31 @@ 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
--folder, -f The folder to operate on. Cannot be used with the `--workspace` option.
--workspace, -w 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
--verbosity, -v Set the verbosity level. Allowed values are q[uiet], m[inimal], n[ormal], d[etailed], and
diag[nostic]
--dry-run Format files, but do not save changes to disk.
--check Terminates with a non-zero exit code if any files were formatted.
--files A comma separated list of relative file paths to format. All files are formatted if empty.
--include, --files A comma separated list of relative file or folder paths to include in formatting. All files are
formatted if empty.
--exclude A comma separated list of relative file or folder paths to exclude from formatting.
--version Display version information
--report Writes a json file to the given directory. Defaults to 'format-report.json' if no filename given.
```

Add `format` after `dotnet` and before the command arguments that you want to run:

| 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 |
| dotnet **format** --check --dry-run | Formats but does not save. Returns a non-zero exit code if any files would have been changed. |
| dotnet **format** --report <report-path> | Formats and saves a json report file to the given directory. |
| 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** --include Programs.cs,Utility\Logging.cs | Formats the files Program.cs and Utility\Logging.cs |
| dotnet **format** --check --dry-run | Formats but does not save. Returns a non-zero exit code if any files would have been changed. |
| dotnet **format** --report <report-path> | Formats and saves a json report file to the given directory. |

### How To Uninstall

Expand All @@ -82,7 +83,7 @@ You can build and package the tool using the following commands. The instruction
build -pack
# The final line from the build will read something like
# Successfully created package '..\artifacts\packages\Debug\Shipping\dotnet-format.3.0.0-dev.nupkg'.
# Use the value that is in the form `3.0.0-dev` as the version in the next command.
# Use the value that is in the form `3.2.0-dev` as the version in the next command.
dotnet tool install --add-source .\artifacts\packages\Debug\Shipping -g dotnet-format --version <version>
dotnet format
```
Expand Down
36 changes: 18 additions & 18 deletions src/CodeFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
ILogger logger,
CancellationToken cancellationToken)
{
var (workspaceFilePath, workspaceType, logLevel, saveFormattedFiles, _, filesToFormat, filesToIgnore, reportPath) = options;
var (workspaceFilePath, workspaceType, logLevel, saveFormattedFiles, _, pathsToInclude, pathsToExclude, reportPath) = options;
var logWorkspaceWarnings = logLevel == LogLevel.Trace;

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

using (var workspace = await OpenWorkspaceAsync(
workspaceFilePath, workspaceType, filesToFormat, logWorkspaceWarnings, logger, cancellationToken).ConfigureAwait(false))
workspaceFilePath, workspaceType, pathsToInclude, logWorkspaceWarnings, logger, cancellationToken).ConfigureAwait(false))
{
if (workspace is null)
{
Expand All @@ -60,7 +60,7 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
logger.LogTrace(Resources.Determining_formattable_files);

var (fileCount, formatableFiles) = await DetermineFormattableFiles(
solution, projectPath, filesToFormat, filesToIgnore, logger, cancellationToken).ConfigureAwait(false);
solution, projectPath, pathsToInclude, pathsToExclude, logger, cancellationToken).ConfigureAwait(false);

var determineFilesMS = workspaceStopwatch.ElapsedMilliseconds - loadWorkspaceMS;
logger.LogTrace(Resources.Complete_in_0_ms, determineFilesMS);
Expand Down Expand Up @@ -137,15 +137,15 @@ private static string GetReportFilePath(string reportPath)
private static async Task<Workspace> OpenWorkspaceAsync(
string workspacePath,
WorkspaceType workspaceType,
ImmutableHashSet<string> filesToFormat,
ImmutableHashSet<string> pathsToInclude,
bool logWorkspaceWarnings,
ILogger logger,
CancellationToken cancellationToken)
{
if (workspaceType == WorkspaceType.Folder)
{
var folderWorkspace = FolderWorkspace.Create();
await folderWorkspace.OpenFolder(workspacePath, filesToFormat, cancellationToken);
await folderWorkspace.OpenFolder(workspacePath, pathsToInclude, cancellationToken);
return folderWorkspace;
}

Expand Down Expand Up @@ -241,8 +241,8 @@ private static async Task<Solution> RunCodeFormattersAsync(
internal static async Task<(int, ImmutableArray<(DocumentId, OptionSet, ICodingConventionsSnapshot)>)> DetermineFormattableFiles(
Solution solution,
string projectPath,
ImmutableHashSet<string> filesToFormat,
ImmutableHashSet<string> filesToIgnore,
ImmutableHashSet<string> pathsToInclude,
ImmutableHashSet<string> pathsToExclude,
ILogger logger,
CancellationToken cancellationToken)
{
Expand Down Expand Up @@ -272,7 +272,7 @@ private static async Task<Solution> RunCodeFormattersAsync(

// Get project documents and options with .editorconfig settings applied.
var getProjectDocuments = project.DocumentIds.Select(documentId => GetDocumentAndOptions(
project, documentId, filesToFormat, filesToIgnore, codingConventionsManager, optionsApplier, cancellationToken));
project, documentId, pathsToInclude, pathsToExclude, codingConventionsManager, optionsApplier, cancellationToken));
getDocumentsAndOptions.AddRange(getProjectDocuments);
}

Expand Down Expand Up @@ -307,18 +307,18 @@ 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,
ImmutableHashSet<string> filesToIgnore,
ImmutableHashSet<string> pathsToInclude,
ImmutableHashSet<string> pathsToExclude,
ICodingConventionsManager codingConventionsManager,
EditorConfigOptionsApplier optionsApplier,
CancellationToken cancellationToken)
{
var document = project.Solution.GetDocument(documentId);

if (await ShouldIgnoreDocument(document, filesToFormat, filesToIgnore, cancellationToken))
if (await ShouldIgnoreDocument(document, pathsToInclude, pathsToExclude, cancellationToken))
{
return (null, null, null, false);
}
Expand All @@ -339,14 +339,14 @@ private static async Task<Solution> RunCodeFormattersAsync(
}

private static async Task<bool> ShouldIgnoreDocument(
Document document,
ImmutableHashSet<string> filesToFormat,
ImmutableHashSet<string> filesToIgnore,
Document document,
ImmutableHashSet<string> pathsToInclude,
ImmutableHashSet<string> pathsToExclude,
CancellationToken cancellationToken)
{
if (!filesToFormat.IsEmpty && !filesToFormat.Contains(document.FilePath))
if (!pathsToInclude.IsEmpty && !pathsToInclude.Any(path => document.FilePath.StartsWith(path, StringComparison.OrdinalIgnoreCase)))
{
// If a files list was passed in, then ignore files not present in the list.
// If a files list was passed in, then ignore files not present in the list.
return true;
}
else if (!document.SupportsSyntaxTree)
Expand All @@ -358,7 +358,7 @@ private static async Task<bool> ShouldIgnoreDocument(
// Ignore generated code files.
return true;
}
else if (!filesToIgnore.IsEmpty && filesToIgnore.Any(f => document.FilePath.StartsWith(f, StringComparison.OrdinalIgnoreCase)))
else if (!pathsToExclude.IsEmpty && pathsToExclude.Any(path => document.FilePath.StartsWith(path, StringComparison.OrdinalIgnoreCase)))
{
// Ignore file in, or under a folder in the list to exclude
return true;
Expand Down
20 changes: 10 additions & 10 deletions src/FormatOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ internal class FormatOptions
public LogLevel LogLevel { get; }
public bool SaveFormattedFiles { get; }
public bool ChangesAreErrors { get; }
public ImmutableHashSet<string> FilesToFormat { get; }
public ImmutableHashSet<string> FilesToIgnore { get; }
public ImmutableHashSet<string> PathsToInclude { get; }
public ImmutableHashSet<string> PathsToExclude { get; }
public string ReportPath { get; }

public FormatOptions(
Expand All @@ -22,17 +22,17 @@ public FormatOptions(
LogLevel logLevel,
bool saveFormattedFiles,
bool changesAreErrors,
ImmutableHashSet<string> filesToFormat,
ImmutableHashSet<string> filesToIgnore,
ImmutableHashSet<string> pathsToInclude,
ImmutableHashSet<string> pathsToExclude,
string reportPath)
{
WorkspaceFilePath = workspaceFilePath;
WorkspaceType = workspaceType;
LogLevel = logLevel;
SaveFormattedFiles = saveFormattedFiles;
ChangesAreErrors = changesAreErrors;
FilesToFormat = filesToFormat;
FilesToIgnore = filesToIgnore;
PathsToInclude = pathsToInclude;
PathsToExclude = pathsToExclude;
ReportPath = reportPath;
}

Expand All @@ -42,17 +42,17 @@ public void Deconstruct(
out LogLevel logLevel,
out bool saveFormattedFiles,
out bool changesAreErrors,
out ImmutableHashSet<string> filesToFormat,
out ImmutableHashSet<string> filesToIgnore,
out ImmutableHashSet<string> pathsToInclude,
out ImmutableHashSet<string> pathsToExclude,
out string reportPath)
{
workspaceFilePath = WorkspaceFilePath;
workspaceType = WorkspaceType;
logLevel = LogLevel;
saveFormattedFiles = SaveFormattedFiles;
changesAreErrors = ChangesAreErrors;
filesToFormat = FilesToFormat;
filesToIgnore = FilesToIgnore;
pathsToInclude = PathsToInclude;
pathsToExclude = PathsToExclude;
reportPath = ReportPath;
}
}
Expand Down
Loading