Skip to content

Commit

Permalink
Support for passing a config file to csharpier
Browse files Browse the repository at this point in the history
closes #777
  • Loading branch information
belav committed Jan 14, 2023
1 parent ccff28f commit e767e6c
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 10 deletions.
8 changes: 8 additions & 0 deletions Docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Options:
--skip-write Skip writing changes. Generally used for testing to ensure csharpier doesn't throw any errors or cause syntax tree validation failures.
--write-stdout Write the results of formatting any files to stdout.
--pipe-multiple-files Keep csharpier running so that multiples files can be piped to it via stdin
--config-path Path to the CSharpier configuration file
--version Show version information
-?, -h, --help Show help and usage information

Expand Down Expand Up @@ -122,3 +123,10 @@ public class ClassName
public string Field;
}
```

### --config-path
If your configuration file lives in a location that CSharpier would not normally resolve it (such as in a config folder)
you can pass the path for the configuration file to CSharpier.
```bash
dotnet csharpier . --config-path "./config/.csharpierrc"
```
2 changes: 2 additions & 0 deletions Docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ CSharpier has support for a configuration file. You can use any of the following
- A ```.csharpierrc``` file in JSON or YAML.
- A ```.csharpierrc.json``` or ```.csharpierrc.yaml``` file.

The configuration file will be resolved starting from the location of the file being formatted, and searching up the file tree until a config file is (or isn’t) found.

### Configuration Options
JSON
```json
Expand Down
17 changes: 17 additions & 0 deletions Src/CSharpier.Cli.Tests/CliTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,23 @@ public async Task Should_Respect_Ignore_File_With_Subdirectory_When_DirectorOrFi
result.Should().Be(unformattedContent, $"The file at {filePath} should have been ignored");
}

[Test]
public async Task Should_Support_Config_Path()
{
const string fileContent = "var myVariable = someLongValue;";
var fileName = "TooWide.cs";
await this.WriteFileAsync(fileName, fileContent);
await this.WriteFileAsync("config/.csharpierrc", "printWidth: 10");

await new CsharpierProcess()
.WithArguments("--config-path config/.csharpierrc . ")
.ExecuteAsync();

var result = await this.ReadAllTextAsync(fileName);

result.Should().Be("var myVariable =\n someLongValue;\n");
}

[Test]
public async Task Should_Return_Error_When_No_DirectoryOrFile_And_Not_Piping_StdIn()
{
Expand Down
15 changes: 10 additions & 5 deletions Src/CSharpier.Cli/CommandLineFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ CancellationToken cancellationToken

var (ignoreFile, printerOptions) = await GetIgnoreFileAndPrinterOptions(
filePath,
commandLineOptions.ConfigPath,
fileSystem,
logger,
cancellationToken
Expand Down Expand Up @@ -131,6 +132,7 @@ CancellationToken cancellationToken

var (ignoreFile, printerOptions) = await GetIgnoreFileAndPrinterOptions(
directoryOrFile,
commandLineOptions.ConfigPath,
fileSystem,
logger,
cancellationToken
Expand Down Expand Up @@ -225,6 +227,7 @@ await FormatPhysicalFile(

private static async Task<(IgnoreFile, PrinterOptions)> GetIgnoreFileAndPrinterOptions(
string directoryOrFile,
string? configPath,
IFileSystem fileSystem,
ILogger logger,
CancellationToken cancellationToken
Expand All @@ -243,11 +246,13 @@ CancellationToken cancellationToken
cancellationToken
);

var printerOptions = ConfigurationFileOptions.CreatePrinterOptions(
baseDirectoryPath,
fileSystem,
logger
);
var printerOptions = configPath is null
? ConfigurationFileOptions.FindPrinterOptionsForDirectory(
baseDirectoryPath,
fileSystem,
logger
)
: ConfigurationFileOptions.CreatePrinterOptionsFromPath(configPath, fileSystem, logger);

return (ignoreFile, printerOptions);
}
Expand Down
6 changes: 6 additions & 0 deletions Src/CSharpier.Cli/CommandLineOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class CommandLineOptions
public bool PipeMultipleFiles { get; init; }
public bool NoCache { get; init; }
public string? StandardInFileContents { get; init; }
public string? ConfigPath { get; init; }
public string[] OriginalDirectoryOrFilePaths { get; init; } = Array.Empty<string>();

internal delegate Task<int> Handler(
Expand All @@ -22,6 +23,7 @@ internal delegate Task<int> Handler(
bool writeStdout,
bool pipeMultipleFiles,
bool noCache,
string? config,
CancellationToken cancellationToken
);

Expand Down Expand Up @@ -58,6 +60,10 @@ public static RootCommand Create()
new Option(
new[] { "--pipe-multiple-files" },
"Keep csharpier running so that multiples files can be piped to it via stdin"
),
new Option<string>(
new[] { "--config-path" },
"Path to the CSharpier configuration file"
)
};

Expand Down
25 changes: 24 additions & 1 deletion Src/CSharpier.Cli/ConfigurationFileOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class ConfigurationFileOptions

private static readonly string[] validExtensions = { ".csharpierrc", ".json", ".yml", ".yaml" };

internal static PrinterOptions CreatePrinterOptions(
internal static PrinterOptions FindPrinterOptionsForDirectory(
string baseDirectoryPath,
IFileSystem fileSystem,
ILogger logger
Expand All @@ -25,6 +25,29 @@ ILogger logger

var configurationFileOptions = Create(baseDirectoryPath, fileSystem, logger);

return ConvertToPrinterOptions(configurationFileOptions);
}

internal static PrinterOptions CreatePrinterOptionsFromPath(
string configPath,
IFileSystem fileSystem,
ILogger logger
)
{
// TODO this should load the file directly, instead of trying to find it in the directory
var configurationFileOptions = Create(
Path.GetDirectoryName(configPath),
fileSystem,
logger
);

return ConvertToPrinterOptions(configurationFileOptions);
}

private static PrinterOptions ConvertToPrinterOptions(
ConfigurationFileOptions configurationFileOptions
)
{
List<string[]> preprocessorSymbolSets;
if (configurationFileOptions.PreprocessorSymbolSets == null)
{
Expand Down
13 changes: 9 additions & 4 deletions Src/CSharpier.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,21 @@ public static async Task<int> Run(
bool writeStdout,
bool pipeMultipleFiles,
bool noCache,
string configPath,
CancellationToken cancellationToken
)
{
DebugLogger.Log("Starting");
DebugLogger.Log(configPath);
var console = new SystemConsole();
var logger = new ConsoleLogger(console);

if (pipeMultipleFiles)
{
return await PipeMultipleFiles(console, logger, cancellationToken);
return await PipeMultipleFiles(console, logger, configPath, cancellationToken);
}

var directoryOrFileNotProvided = (directoryOrFile is null or { Length: 0 });
var directoryOrFileNotProvided = directoryOrFile is null or { Length: 0 };
var originalDirectoryOrFile = directoryOrFile;

string? standardInFileContents = null;
Expand Down Expand Up @@ -75,7 +77,8 @@ CancellationToken cancellationToken
NoCache = noCache,
Fast = fast,
SkipWrite = skipWrite,
WriteStdout = writeStdout || standardInFileContents != null
WriteStdout = writeStdout || standardInFileContents != null,
ConfigPath = configPath
};

return await CommandLineFormatter.Format(
Expand All @@ -90,6 +93,7 @@ CancellationToken cancellationToken
private static async Task<int> PipeMultipleFiles(
SystemConsole console,
ILogger logger,
string? configPath,
CancellationToken cancellationToken
)
{
Expand Down Expand Up @@ -146,7 +150,8 @@ CancellationToken cancellationToken
},
StandardInFileContents = stringBuilder.ToString(),
Fast = true,
WriteStdout = true
WriteStdout = true,
ConfigPath = configPath
};

try
Expand Down

0 comments on commit e767e6c

Please sign in to comment.