Skip to content

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

@remkop

Description

@remkop

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);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions