Validating Options

I'm looking to have a filePath option that I can reuse.

The option would validate that filePath exists and is readable, writeable accessible etc..

ExpressibleByArgument doesn't support validate nor transform.
That would be useful.

struct FilePath: ExpressibleByArgument {
var pathString: String

init?(argument: String) {
    self.pathString = argument

func validate() throws {
    if (FileManager.default.fileExists(atPath: self.pathString)) {
        throw CliError.InvalidFilePath


Definitely seems like a valid request — could you open an issue on the GH repo describing your use case?

General per-type validation customization notwithstanding, I wouldn't recommend validating file existence separately from the place where you actually read it. It is very much possible that the file was added/removed between the validation and the actual reading.


The temporal distance between validating access to the filepath in the option verses reading it in the command impl is inconsequential in the majority of cases. If you don't provide a validate method there still is no reason you cannot choose to validate in the command impl itself. This way you have different design options to consider. I think that is a plus.

I mean, you do you. The precise requirement most likely differs from case to case.

IME, you still need to re-validate that the file exists when opening it though since that's how most IO frameworks operate. That's why I suggest to just do it during IO operations. You could, of course, assert that IO operations always succeed, but I personally feel that that's not using the framework to its fullest.

1 Like
Terms of Service

Privacy Policy

Cookie Policy