trevorld / r-optparse

command-line optional argument parser
http://trevorldavis.com/R/optparse/dev/
GNU General Public License v2.0
146 stars 11 forks source link

Fix no help text showing when option's default is NA #2

Closed sseemayer closed 10 years ago

sseemayer commented 10 years ago

Hi Trevor,

Thank you for great port of optparse to R! I've realized today that when defining an option with a default value of NA, the help message printed by the -h switch will not show a help text for this option. Consider e.g. the following minimal example:

#!/usr/bin/env Rscript
library(optparse)

option_list <- list(
    make_option(c("-o", "--long-option"), dest="my_option", default=NA, help="An option [default: %default]")
)
opt <- parse_args(OptionParser(option_list = option_list))

print(opt)

Running this from the command line I get:

$ ./example.R -h
Usage: ./example.R [options]

Options:
    -o LONG-OPTION, --long-option=LONG-OPTION
        NA

    -h, --help
        Show this help message and exit

I've traced this to the sub call for replacing the %default variable in the help text. When the replacement is NA, the whole returned string will be NA (the constant, not the string!). The replacement is NA because as.character(NA) = NA, not "NA" as expected.

The pull request adds a check for NA in the default_str to check for this corner case and replace NA with "NA" so that the help text can be correctly formatted.

Best, Stefan

trevorld commented 10 years ago

First pull request I've received since moving to Github :-) I decided to move the logic of converting a default into a string into a helper function so I'm going to close the pull request without pulling in your exact patch but I've fixed the bug, added some unit tests, and thanked you in the documentation and NEWS file and have pushed those updates to the main branch.

Thanks,

Trevor

sseemayer commented 10 years ago

Your solution is a lot better than mine - thanks for the quick response!