Skip to content

Commit

Permalink
Added files option (#52)
Browse files Browse the repository at this point in the history
* added files option resource

* added files option

* convert string from cli into an array of paths

* pass list of files into formatter

* added default value if files option isn't present

* need to check if files argument is null

* moved where file list is created

* added null file list to existing tests

* skip a document if the path is in the list

* added test for files option with a list of files

* fixed xlf files

* added files option to readme

* use unformatted project

* moved extra file into unformatted project

* deleted new project

* fixed tests since adding new file to unformatted project

* added a test for a file in the list that doesn't exist

* ignore case when comparing paths

* break after finding file

* convert loop to linq

* new resource missing from two xlf files

* removed directory from test file path

* use GetRelativePath to fix directory separators

* added test for directory separator insensitivity

* moved fixing path separators to when the list is split

* removed failing test since code moved

* make GetFileList internal for future test

* added new test for directory separator insensitivity
  • Loading branch information
Chris Allen authored and JoeRobich committed Mar 21, 2019
1 parent c6f928b commit 822c036
Show file tree
Hide file tree
Showing 21 changed files with 188 additions and 22 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Options:
diag[nostic]
--dry-run Format files, but do not save changes to disk.
--check Terminate with non-zero exit code if any files need to be formatted in the workspace.
--files The files to operate on. If none specified, all files in workspace will be operated on.
--version Display version information
```

Expand Down
23 changes: 17 additions & 6 deletions src/CodeFormatter.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
Expand All @@ -22,7 +23,7 @@ internal static class CodeFormatter
{
private const int MaxLoggedWorkspaceWarnings = 5;

public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(ILogger logger, string solutionOrProjectPath, bool isSolution, bool logAllWorkspaceWarnings, bool saveFormattedFiles, CancellationToken cancellationToken)
public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(ILogger logger, string solutionOrProjectPath, bool isSolution, bool logAllWorkspaceWarnings, bool saveFormattedFiles, string[] filesToFormat, CancellationToken cancellationToken)
{
logger.LogInformation(string.Format(Resources.Formatting_code_files_in_workspace_0, solutionOrProjectPath));

Expand Down Expand Up @@ -74,7 +75,7 @@ public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(ILogger log
logger.LogTrace(Resources.Workspace_loaded_in_0_ms, workspaceStopwatch.ElapsedMilliseconds);
workspaceStopwatch.Restart();

(formatResult.ExitCode, formatResult.FileCount, formatResult.FilesFormatted) = await FormatFilesInWorkspaceAsync(logger, workspace, projectPath, codingConventionsManager, saveFormattedFiles, cancellationToken).ConfigureAwait(false);
(formatResult.ExitCode, formatResult.FileCount, formatResult.FilesFormatted) = await FormatFilesInWorkspaceAsync(logger, workspace, projectPath, codingConventionsManager, saveFormattedFiles, filesToFormat, cancellationToken).ConfigureAwait(false);

logger.LogDebug(Resources.Formatted_0_of_1_files_in_2_ms, formatResult.FilesFormatted, formatResult.FileCount, workspaceStopwatch.ElapsedMilliseconds);
}
Expand Down Expand Up @@ -105,7 +106,7 @@ void LogWorkspaceWarnings(object sender, WorkspaceDiagnosticEventArgs args)
}
}

private static async Task<(int status, int fileCount, int filesFormatted)> FormatFilesInWorkspaceAsync(ILogger logger, Workspace workspace, string projectPath, ICodingConventionsManager codingConventionsManager, bool saveFormattedFiles, CancellationToken cancellationToken)
private static async Task<(int status, int fileCount, int filesFormatted)> FormatFilesInWorkspaceAsync(ILogger logger, Workspace workspace, string projectPath, ICodingConventionsManager codingConventionsManager, bool saveFormattedFiles, string[] filesToFormat, CancellationToken cancellationToken)
{
var projectIds = workspace.CurrentSolution.ProjectIds.ToImmutableArray();
var optionsApplier = new EditorConfigOptionsApplier();
Expand All @@ -129,7 +130,7 @@ void LogWorkspaceWarnings(object sender, WorkspaceDiagnosticEventArgs args)

logger.LogInformation(Resources.Formatting_code_files_in_project_0, project.Name);

var (formattedSolution, filesFormatted) = await FormatFilesInProjectAsync(logger, project, codingConventionsManager, optionsApplier, cancellationToken).ConfigureAwait(false);
var (formattedSolution, filesFormatted) = await FormatFilesInProjectAsync(logger, project, codingConventionsManager, optionsApplier, filesToFormat, cancellationToken).ConfigureAwait(false);
totalFileCount += project.DocumentIds.Count;
totalFilesFormatted += filesFormatted;
if (saveFormattedFiles && !workspace.TryApplyChanges(formattedSolution))
Expand All @@ -142,7 +143,7 @@ void LogWorkspaceWarnings(object sender, WorkspaceDiagnosticEventArgs args)
return (0, totalFileCount, totalFilesFormatted);
}

private static async Task<(Solution solution, int filesFormatted)> FormatFilesInProjectAsync(ILogger logger, Project project, ICodingConventionsManager codingConventionsManager, EditorConfigOptionsApplier optionsApplier, CancellationToken cancellationToken)
private static async Task<(Solution solution, int filesFormatted)> FormatFilesInProjectAsync(ILogger logger, Project project, ICodingConventionsManager codingConventionsManager, EditorConfigOptionsApplier optionsApplier, string[] filesToFormat, CancellationToken cancellationToken)
{
var isCommentTrivia = project.Language == LanguageNames.CSharp
? IsCSharpCommentTrivia
Expand All @@ -157,6 +158,16 @@ void LogWorkspaceWarnings(object sender, WorkspaceDiagnosticEventArgs args)
continue;
}

if (filesToFormat != null)
{
var fileInArgumentList = filesToFormat.Any(relativePath => document.FilePath.EndsWith(relativePath, StringComparison.OrdinalIgnoreCase));

if (!fileInArgumentList)
{
continue;
}
}

var formatTask = Task.Run(async () =>
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
Expand Down
11 changes: 10 additions & 1 deletion src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ private static async Task<int> Main(string[] args)
.AddOption(new Option(new[] { "-v", "--verbosity" }, Resources.Set_the_verbosity_level_Allowed_values_are_quiet_minimal_normal_detailed_and_diagnostic, new Argument<string>() { Arity = ArgumentArity.ExactlyOne }.FromAmong(_verbosityLevels)))
.AddOption(new Option(new[] { "--dry-run" }, Resources.Format_files_but_do_not_save_changes_to_disk, new Argument<bool>()))
.AddOption(new Option(new[] { "--check" }, Resources.Terminate_with_non_zero_exit_code_if_any_files_need_to_be_formatted_in_the_workspace, new Argument<bool>()))
.AddOption(new Option(new[] { "--files" }, Resources.The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on, new Argument<string>(() => null)))
.UseVersionOption()
.Build();

return await parser.InvokeAsync(args).ConfigureAwait(false);
}

public static async Task<int> Run(string workspace, string verbosity, bool dryRun, bool check, IConsole console = null)
public static async Task<int> Run(string workspace, string verbosity, bool dryRun, bool check, string files, IConsole console = null)
{
var serviceCollection = new ServiceCollection();
var logLevel = GetLogLevel(verbosity);
Expand Down Expand Up @@ -70,6 +71,8 @@ public static async Task<int> Run(string workspace, string verbosity, bool dryRu
var workspaceDirectory = Path.GetDirectoryName(workspacePath);
Environment.CurrentDirectory = workingDirectory;

var fileList = GetFileList(files);

// Since we are running as a dotnet tool we should be able to find an instance of
// MSBuild in a .NET Core SDK.
var msBuildInstance = Build.Locator.MSBuildLocator.QueryVisualStudioInstances().First();
Expand All @@ -88,6 +91,7 @@ public static async Task<int> Run(string workspace, string verbosity, bool dryRu
isSolution,
logAllWorkspaceWarnings: logLevel == LogLevel.Trace,
saveFormattedFiles: !dryRun,
filesToFormat: fileList,
cancellationTokenSource.Token).ConfigureAwait(false);

return GetExitCode(formatResult, check);
Expand Down Expand Up @@ -142,5 +146,10 @@ private static void ConfigureServices(ServiceCollection serviceCollection, ICons
serviceCollection.AddSingleton(new LoggerFactory().AddSimpleConsole(console, logLevel));
serviceCollection.AddLogging();
}

internal static string[] GetFileList(string files)
{
return files?.Split(',').Select(path => Path.GetRelativePath(Environment.CurrentDirectory, path)).ToArray();
}
}
}
10 changes: 10 additions & 0 deletions src/Resources.Designer.cs

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

3 changes: 3 additions & 0 deletions src/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,7 @@
<data name="Terminate_with_non_zero_exit_code_if_any_files_need_to_be_formatted_in_the_workspace" xml:space="preserve">
<value>Terminate with non-zero exit code if any files need to be formatted in the workspace.</value>
</data>
<data name="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on" xml:space="preserve">
<value>The files to operate on. If none specified, all files in workspace will be operated on.</value>
</data>
</root>
5 changes: 5 additions & 0 deletions src/xlf/Resources.cs.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Pracovní prostor se načetl za {0} ms.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.de.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Arbeitsbereich in {0} ms geladen.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.es.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Espacio de trabajo cargado en {0} ms.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.fr.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Espace de travail chargé en {0} ms.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.it.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Area di lavoro caricata in {0} ms.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.ja.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">ワークスペース {0} ミリ秒で読み込まれます。</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.ko.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">작업 영역이 {0}밀리초 안에 로드되었습니다.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.pl.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Obszar roboczy załadowano w {0} ms.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.pt-BR.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Espaço de trabalho carregado em {0}ms.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.ru.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Рабочая область загружена за {0} мс.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.tr.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">Çalışma alanı {0} ms yüklü.</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.zh-Hans.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">工作区已在 {0} 毫秒内加载完毕。</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
5 changes: 5 additions & 0 deletions src/xlf/Resources.zh-Hant.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@
<target state="translated">{0} 毫秒內載入的工作區。</target>
<note />
</trans-unit>
<trans-unit id="The_files_to_operate_on_If_none_specified_all_files_in_workspace_will_be_operated_on">
<source>The files to operate on. If none specified, all files in workspace will be operated on.</source>
<target state="new">The files to operate on. If none specified, all files in workspace will be operated on.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
Loading

0 comments on commit 822c036

Please sign in to comment.