dotnet / dotnet/command-line-api
ArgumentExtensions.ExistingOnly, but allow "-" for reading standard input
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
In a command-line app, I'd like to define a mandatory argument whose value is either a file path to read that file, or "-" to read standard input. What is the best practice for defining such an argument so that it works properly with completion and validation?
[ArgumentExtensions.ExistingOnly](https://docs.microsoft.com/dotnet/api/system.commandline.argumentextensions.existingonly#system-commandline-argumentextensions-existingonly(system-commandline-argument((system-io-fileinfo)))) can be used to add validation that an Argument\ names an existing file, but this of course does not support "-". In 2.0.0-beta4.22272.1, neither ExistingOnly nor the FileInfo type affects completion, but I imagine they could do so in the future.
If I use Argument\, then the problem is how to recognize that the value is "-", rather than e.g. "./-". [FileInfo.Name](https://docs.microsoft.com/dotnet/api/system.io.fileinfo.name?view=netstandard-2.0) and [FileSystemInfo.FullName](https://docs.microsoft.com/dotnet/api/system.io.filesysteminfo.fullname?view=netstandard-2.0) are not suitable. [FileInfo.ToString()](https://docs.microsoft.com/dotnet/api/system.io.fileinfo.tostring?view=netstandard-2.0) could be suitable but the documentation advises against using it, and in Reference Source, there seems to be [some logic](https://github.com/microsoft/referencesource/blob/5697c29004a34d80acdaf5742d7e699022c64ecd/mscorlib/system/io/fileinfo.cs#L115) that might cause ToString() not to return the entire string that was passed to the constructor.
After my app has recognized "-", it can use either [Console.In](https://docs.microsoft.com/dotnet/api/system.console.in?view=netstandard-2.0) or [Console.OpenStandardInput()](https://docs.microsoft.com/dotnet/api/system.console.openstandardinput?view=netstandard-2.0), depending on whether it needs to read text or binary data. It can also check [IStandardIn.IsInputRedirected](https://docs.microsoft.com/dotnet/api/system.commandline.io.istandardin.isinputredirected) and refuse to read binary data from standard input unless redirected. does not seem useful to me because it does not cover binary input. I don't care about cancellation .
So then, is the best practice like this:
- Define the argument as Argument\, to avoid any shenanigans from FileInfo.ToString().
- Add validation similar to ArgumentExtensions.ExistingOnly, but using string rather than FileInfo, and allowing "-".
- Don't do anything about completion for now. Reconsider after has been implemented.
Contributor guide
Assessment
This issue has not been assessed yet.