Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow custom type converter to map empty String to custom default value for empty options #325

Closed
remkop opened this issue Apr 6, 2018 · 0 comments

Comments

@remkop
Copy link
Owner

remkop commented Apr 6, 2018

Goal: provide the ability to specify a custom value to be used when a command line option is specified without any value.

@jesselong pointed out in #280 that with a small code change, users could specify a custom type converter that would assign the desired default value for options with no value.

Failing test to demonstrate the problem Jesse pointed out:

class ConversionForEmptyTest {
    static class EmptyValueConverter implements ITypeConverter<Short> {
        public Short convert(String value) throws Exception {
            return value == null
                    ? -1
                    : value.isEmpty() ? -2 : Short.valueOf(value);
        }
    }

    @Test
    public void testOptionEmptyValue() {
        class Standard {
            @Option(names = "-x", arity = "0..1", description = "may have empty value")
            Short x;
        }

        try {
            CommandLine.populateCommand(new Standard(), "-x");
            fail("Expect exception for Short.valueOf(\"\")");
        } catch (Exception expected) {
            assertTrue(expected.getMessage(), expected.getMessage().contains("input string: \"\""));
        }

        Standard withValue1 = CommandLine.populateCommand(new Standard(), "-x=987");
        assertEquals(Short.valueOf((short) 987), withValue1.x);

        //------------------
        class CustomConverter {
            @Option(names = "-x", arity = "0..1", description = "may have empty value",
                    converter = EmptyValueConverter.class)
            Short x;
        }

        CustomConverter withoutValue2 = CommandLine.populateCommand(new CustomConverter(), "-x");
        assertEquals(Short.valueOf((short) -2), withoutValue2.x);

        CustomConverter withValue2 = CommandLine.populateCommand(new CustomConverter(), "-x=987");
        assertEquals(Short.valueOf((short) 987), withValue2.x);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant