rvesse / airline

Java annotation-based framework for parsing Git like command line structures with deep extensibility
https://rvesse.github.io/airline/
Apache License 2.0
128 stars 20 forks source link

Add support for Path conversion #111

Closed rkrisztian closed 3 years ago

rkrisztian commented 3 years ago

For conversion of parameters to Path, currently I have to add a custom converter class like this:

import java.nio.file.Path;
import java.nio.file.Paths;

import com.github.rvesse.airline.types.ConvertResult;
import com.github.rvesse.airline.types.DefaultTypeConverter;

public class MyTypeConverter extends DefaultTypeConverter {

    @Override
    public Object convert(String name, Class<?> type, String value) {
        checkArguments(name, type, value);

        ConvertResult result = tryConvertFromPath(type, value);
        if (result.wasSuccessfull()) {
            return result.getConvertedValue();
        }

        return super.convert(name, type, value);
    }

    private ConvertResult tryConvertFromPath(Class<?> type, String value) {
        if (type == Path.class) {
            try {
                return new ConvertResult(Paths.get(value));
            } catch (Throwable ex) {
                // Ignore
            }
        }
        return ConvertResult.FAILURE;
    }
}

It would be nice if this could be supported by default, as File is already supported.

Note: not urgent, for now I can just add this to my code:

CliBuilder<Runnable> builder = Cli.<Runnable>builder("my-cli")
        /* (...) */;
builder.withParser().withTypeConverter(new MyTypeConverter());
Cli<Runnable> parser = builder.build();

Note: I am probably not on the latest version yet, but if this inconveniently fluent-style-breaker withParser method has not been improved yet, please also consider making it more fluent too.

rkrisztian commented 3 years ago

BTW, wasSuccessful is the grammatically correct spelling, but I do not intend to annoy you. :)

rvesse commented 3 years ago

Thanks for the well described issue, just got back from vacation and catching up with everything.

To summarise the ask(s):

The first two are obvious to me but not so sure on the 3rd point. I guess you are referring to the point that once you have dropped into the parser builder you can't get back out to the parent builder. This is definitely possible in other parts of the Fluent API but not here so can certainly be improved in the future.

rvesse commented 3 years ago

This is fixed for the forthcoming 2.9.0 release, you can test out the fixes now by using 2.9.0-SNAPSHOT which is available from the Sonatype OSS repository per https://central.sonatype.org/publish/publish-guide/#accessing-repositories

Changes made to address this issue: