optparse/0000755000176200001440000000000014130114742012104 5ustar liggesusersoptparse/NAMESPACE0000644000176200001440000000055514130110525013323 0ustar liggesusers# Generated by roxygen2: do not edit by hand export(IndentedHelpFormatter) export(OptionParser) export(OptionParserOption) export(TitledHelpFormatter) export(add_option) export(make_option) export(parse_args) export(parse_args2) export(print_help) exportClasses(OptionParser) exportClasses(OptionParserOption) import(getopt) import(methods) importFrom(utils,tail) optparse/exec/0000755000176200001440000000000013241456446013044 5ustar liggesusersoptparse/exec/example.R0000644000176200001440000000501413241456363014620 0ustar liggesusers#!/usr/bin/env Rscript # Copyright 2010-2013 Trevor L Davis # Copyright 2008 Allen Day # # This file is free software: you may copy, redistribute and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 2 of the License, or (at your # option) any later version. # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . suppressPackageStartupMessages(library("optparse")) suppressPackageStartupMessages(library("stats")) # specify our desired options in a list # by default OptionParser will add an help option equivalent to # make_option(c("-h", "--help"), action="store_true", default=FALSE, # help="Show this help message and exit") option_list <- list( make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]"), make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output"), make_option(c("-c", "--count"), type="integer", default=5, help="Number of random normals to generate [default %default]", metavar="number"), make_option("--generator", default="rnorm", help = "Function to generate random deviates [default \"%default\"]"), make_option("--mean", default=0, help="Mean if generator == \"rnorm\" [default %default]"), make_option("--sd", default=1, metavar="standard deviation", help="Standard deviation if generator == \"rnorm\" [default %default]") ) # get command line options, if help option encountered print help and exit, # otherwise if options not found on command line then set defaults, opt <- parse_args(OptionParser(option_list=option_list)) # print some progress messages to stderr if "quietly" wasn't requested if ( opt$verbose ) { write("writing some verbose output to standard error...\n", stderr()) } # do some operations based on user input if( opt$generator == "rnorm") { cat(paste(rnorm(opt$count, mean=opt$mean, sd=opt$sd), collapse="\n")) } else { cat(paste(do.call(opt$generator, list(opt$count)), collapse="\n")) } cat("\n") optparse/exec/display_file.R0000644000176200001440000000270113241456354015631 0ustar liggesusers#!/usr/bin/env Rscript # Copyright 2010-2013 Trevor L Davis # Copyright 2013 Kirill Müller # # This file is free software: you may copy, redistribute and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 2 of the License, or (at your # option) any later version. # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . suppressPackageStartupMessages(library("optparse")) option_list <- list( make_option(c("-n", "--add_numbers"), action="store_true", default=FALSE, help="Print line number at the beginning of each line [default]") ) parser <- OptionParser(usage = "%prog [options] file", option_list=option_list) arguments <- parse_args(parser, positional_arguments = 1) opt <- arguments$options file <- arguments$args if( file.access(file) == -1) { stop(sprintf("Specified file ( %s ) does not exist", file)) } else { file_text <- readLines(file) } if(opt$add_numbers) { cat(paste(1:length(file_text), file_text), sep = "\n") } else { cat(file_text, sep = "\n") } optparse/README.md0000644000176200001440000001126014130110525013356 0ustar liggesusers# optparse: Command line optional argument parser [![CRAN Status Badge](https://www.r-pkg.org/badges/version/optparse)](https://cran.r-project.org/package=optparse) [![R-CMD-check](https://github.com/trevorld/r-optparse/workflows/R-CMD-check/badge.svg)](https://github.com/trevorld/r-optparse/actions) [![Coverage Status](https://img.shields.io/codecov/c/github/trevorld/r-optparse/master.svg)](https://codecov.io/github/trevorld/r-optparse?branch=master) [![RStudio CRAN mirror downloads](https://cranlogs.r-pkg.org/badges/optparse)](https://cran.r-project.org/package=optparse) optparse hex sticker A pure R language command line parser inspired by Python's 'optparse' library to be used with Rscript to write "\#!" shebang scripts that accept short and long flag/options. To install the last version released on CRAN use the following command: install.packages("optparse") To install the development version use the following command: install.packages("remotes") remotes::install_github("trevorld/r-optparse") ## dependencies This package depends on the R package `getopt`. To run the unit tests you will need the suggested R package `testthat` and in order to build the vignette you will need the suggested R package `knitr` which in turn probably requires the system tool `pandoc`: sudo apt install pandoc ## examples A simple example: library("optparse") parser <- OptionParser() parser <- add_option(parser, c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]") parser <- add_option(parser, c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output") parser <- add_option(parser, c("-c", "--count"), type="integer", default=5, help="Number of random normals to generate [default %default]", metavar="number") parse_args(parser, args = c("--quietly", "--count=15")) ## $help ## [1] FALSE ## ## $verbose ## [1] FALSE ## ## $count ## [1] 15 Note that the `args` argument of `parse_args` default is `commandArgs(trailing=TRUE)` so it typically doesn't need to be explicitly set if writing an Rscript. One can also equivalently make options in a list: library("optparse") option_list <- list( make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]"), make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output"), make_option(c("-c", "--count"), type="integer", default=5, help="Number of random normals to generate [default %default]", metavar="number") ) parse_args(OptionParser(option_list=option_list), args = c("--verbose", "--count=11")) ## $verbose ## [1] TRUE ## ## $count ## [1] 11 ## ## $help ## [1] FALSE `optparse` automatically creates a help option: parse_args(parser, args = c("--help")) Usage: %prog [options] Options: -h, --help Show this help message and exit -v, --verbose Print extra output [default] -q, --quietly Print little output -c NUMBER, --count=NUMBER Number of random normals to generate [default 5] Error in parse_args(parser, args = c("--help")) : help requested Note by default when `optparse::parse_args` sees a `--help` flag it will first print out a usage message and then either throw an error in interactive use or call `quit` in non-interactive use (i.e. when used within an Rscript called by a shell). To disable the error/quit set the argument `print_help_and_exit` to `FALSE` in `parse_args` and to simply print out the usage string one can also use the function `print_usage`. `optparse` has limited positional argument support, other command-line parsers for R such as `argparse` have richer positional argument support: parse_args(parser, args = c("-vc", "25", "75", "22"), positional_arguments = TRUE) ## $options ## $options$help ## [1] FALSE ## ## $options$verbose ## [1] TRUE ## ## $options$count ## [1] 25 ## ## ## $args ## [1] "75" "22" The function `parse_args2` wraps `parse_args` while setting `positional_arguments=TRUE` and `convert_hyphens_to_underscores=TRUE`: parse_args2(parser, args = c("-vc", "25", "75", "22")) ## $options ## $options$help ## [1] FALSE ## ## $options$verbose ## [1] TRUE ## ## $options$count ## [1] 25 ## ## ## $args ## [1] "75" "22" optparse/man/0000755000176200001440000000000014127751506012672 5ustar liggesusersoptparse/man/OptionParser.Rd0000644000176200001440000000447514117701306015610 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \name{OptionParser} \alias{OptionParser} \title{A function to create an instance of a parser object} \usage{ OptionParser( usage = "usage: \%prog [options]", option_list = list(), add_help_option = TRUE, prog = NULL, description = "", epilogue = "", formatter = IndentedHelpFormatter ) } \arguments{ \item{usage}{The program usage message that will printed out if \code{parse_args} finds a help option, \code{\%prog} is substituted with the value of the \code{prog} argument.} \item{option_list}{A list of of \code{OptionParserOption} instances that will define how \code{parse_args} reacts to command line options. \code{OptionParserOption} instances are usually created by \code{make_option} and can also be added to an existing \code{OptionParser} instance via the \code{add_option} function.} \item{add_help_option}{Whether a standard help option should be automatically added to the \code{OptionParser} instance.} \item{prog}{Program name to be substituted for \code{\%prog} in the usage message (including description and epilogue if present), the default is to use the actual Rscript file name if called by an Rscript file and otherwise keep \code{\%prog}.} \item{description}{Additional text for \code{print_help} to print out between usage statement and options statement} \item{epilogue}{Additional text for \code{print_help} to print out after the options statement} \item{formatter}{A function that formats usage text. The function should take only one argument (an \code{OptionParser()} object). Default is \code{\link[=IndentedHelpFormatter]{IndentedHelpFormatter()}}. The other builtin formatter provided by this package is \code{\link[=TitledHelpFormatter]{TitledHelpFormatter()}}.} } \value{ An instance of the \code{OptionParser} class. } \description{ This function is used to create an instance of a parser object which when combined with the \code{parse_args}, \code{make_option}, and \code{add_option} methods is very useful for parsing options from the command line. } \references{ Python's \code{optparse} library, which inspired this package, is described here: \url{https://docs.python.org/3/library/optparse.html} } \seealso{ \code{\link{parse_args}} \code{\link{make_option}} \code{\link{add_option}} } \author{ Trevor Davis. } optparse/man/optparse-package.Rd0000644000176200001440000000417114117701306016402 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse-package.R \docType{package} \name{optparse-package} \alias{optparse-package} \alias{optparse} \title{Command line option parser} \description{ Goal is to create an R package of a command line parser inspired by Python's \dQuote{optparse} library. } \details{ \code{optparse} is primarily intended to be used with \dQuote{Rscript}. It facilitates writing \dQuote{#!} shebang scripts that accept short and long flags/options. It can also be used from directly, but is probably less useful in this context. See package vignette for a more detailed example. Notes on naming convention in package: 1. An option is one of the shell-split input strings. 2. A flag is a type of option. a flag can be defined as having no argument (defined below), a required argument, or an optional argument. 3. An argument is a type of option, and is the value associated with a flag. 4. A long flag is a type of flag, and begins with the string \dQuote{--}. If the long flag has an associated argument, it may be delimited from the long flag by either a trailing =, or may be the subsequent option. 5. A short flag is a type of flag, and begins with the string \dQuote{-}. If a short flag has an associated argument, it is the subsequent option. short flags may be bundled together, sharing a single leading \dQuote{"-"}, but only the final short flag is able to have a corresponding argument. \%\%\% } \examples{ example_file <- system.file("exec", "example.R", package = "optparse") example_file_2 <- system.file("exec", "display_file.R", package = "optparse") \dontrun{ readLines(example_file) readLines(example_file_2) } } \references{ Python's \code{optparse} library, which this package is based on, is described here: \url{https://docs.python.org/3/library/optparse.html} } \seealso{ \code{\link[getopt]{getopt}} } \author{ Trevor Davis. Some documentation and unit tests ported from Allen Day's getopt package. The documentation for Python's optparse library, which this package is based on, is Copyright 1990-2009, Python Software Foundation. } \keyword{package} optparse/man/OptionParserOption-class.Rd0000644000176200001440000000467613567307066020124 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \docType{class} \name{OptionParserOption-class} \alias{OptionParserOption-class} \alias{OptionParserOption} \title{Class to hold information about command-line options} \description{ Class to hold information about command-line options } \section{Slots}{ \describe{ \item{\code{short_flag}}{String of the desired short flag comprised of the \dQuote{-} followed by a letter.} \item{\code{long_flag}}{String of the desired long flag comprised of \dQuote{--} followed by a letter and then a sequence of alphanumeric characters.} \item{\code{action}}{A character string that describes the action \code{optparse} should take when it encounters an option, either \dQuote{store}, \dQuote{store_true}, or \dQuote{store_false}. The default is \dQuote{store} which signifies that \code{optparse} should store the specified following value if the option is found on the command string. \dQuote{store_true} stores \code{TRUE} if the option is found and \dQuote{store_false} stores \code{FALSE} if the option is found.} \item{\code{type}}{A character string that describes specifies which data type should be stored, either \dQuote{logical}, \dQuote{integer}, \dQuote{double}, \dQuote{complex}, or \dQuote{character}. Default is \dQuote{logical} if \code{action \%in\% c("store_true", store_false)}, \code{typeof(default)} if \code{action == "store"} and default is not \code{NULL} and \dQuote{character} if \code{action == "store"} and default is \code{NULL}. \dQuote{numeric} will be converted to \dQuote{double}.} \item{\code{dest}}{A character string that specifies what field in the list returned by \code{parse_args} should \code{optparse} store option values. Default is derived from the long flag in \code{opt_str}.} \item{\code{default}}{The default value \code{optparse} should use if it does not find the option on the command line.} \item{\code{help}}{A character string describing the option to be used by \code{print_help} in generating a usage message. \code{\%default} will be substituted by the value of \code{default}.} \item{\code{metavar}}{A character string that stands in for the option argument when printing help text. Default is the value of \code{dest}.} \item{\code{callback}}{A function that executes after the each option value is fully parsed} \item{\code{callback_args}}{Additional arguments that pass to the callback function.} }} \seealso{ \code{\link{make_option}} } optparse/man/figures/0000755000176200001440000000000014127751625014340 5ustar liggesusersoptparse/man/figures/logo.png0000644000176200001440000000201014130077664015775 0ustar liggesusersPNG  IHDR PLTEBRj~tRNSDP! pHYs  ~IDATx[ P/zГ/%tږ?jx]xO!ZCgL{\Yz d˟مV/,1uYiCVn}TV֛6Hde-WU#42+ŊO-W+2mveAh"x7M&ʊCY̍vbyY4 i m'=͌eL3uɌYV4M?!S.Xz4wo2ZօE"A\笯ZHV˚,,O ja»x*- Be՟2+Kj!e=)5yJ.OĔcur4`SPrӻnnC%`|8:[Ca>0a ~? ``F``÷N o_ـ-o/`&$L {Pj0A{Pj0A{Pja*nlP `ր A710#΍ [60nkUm ؠTq5`*nlP `oY|nH]`s$)8`ac\auF>i1ma0?w}vqob<`Tf㰸ϣe4>+4mUد~eW̛& HbIJUY!-Kr鱊),אRa9,X4+eIeYկ)LY4O"͛UtVm4q#K"F*RdEd,Ң)-jaZȴB]uA2IjedUK\ optparse/man/add_make_option.Rd0000644000176200001440000001133214117701306016266 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \name{make_option} \alias{make_option} \alias{add_option} \title{Functions to enable our OptionParser to recognize specific command line options.} \usage{ make_option( opt_str, action = NULL, type = NULL, dest = NULL, default = NULL, help = "", metavar = NULL, callback = NULL, callback_args = NULL ) add_option( object, opt_str, action = NULL, type = NULL, dest = NULL, default = NULL, help = "", metavar = NULL, callback = NULL, callback_args = NULL ) } \arguments{ \item{opt_str}{A character vector containing the string of the desired long flag comprised of \dQuote{--} followed by a letter and then a sequence of alphanumeric characters and optionally a string of the desired short flag comprised of the \dQuote{-} followed by a letter.} \item{action}{A character string that describes the action \code{optparse} should take when it encounters an option, either \dQuote{store}, \dQuote{store_true}, \dQuote{store_false}, or \dQuote{callback}. An action of \dQuote{store} signifies that \code{optparse} should store the specified following value if the option is found on the command string. \dQuote{store_true} stores \code{TRUE} if the option is found and \dQuote{store_false} stores \code{FALSE} if the option is found. \dQuote{callback} stores the return value produced by the function specified in the \code{callback} argument. If \code{callback} is not \code{NULL} then the default is \dQuote{callback} else \dQuote{store}.} \item{type}{A character string that describes specifies which data type should be stored, either \dQuote{logical}, \dQuote{integer}, \dQuote{double}, \dQuote{complex}, or \dQuote{character}. Default is \dQuote{logical} if \code{action \%in\% c("store_true", store_false)}, \code{typeof(default)} if \code{action == "store"} and default is not \code{NULL} and \dQuote{character} if \code{action == "store"} and default is \code{NULL}. \dQuote{numeric} will be converted to \dQuote{double}.} \item{dest}{A character string that specifies what field in the list returned by \code{parse_args} should \code{optparse} store option values. Default is derived from the long flag in \code{opt_str}.} \item{default}{The default value \code{optparse} should use if it does not find the option on the command line.} \item{help}{A character string describing the option to be used by \code{print_help} in generating a usage message. \code{\%default} will be substituted by the value of \code{default}.} \item{metavar}{A character string that stands in for the option argument when printing help text. Default is the value of \code{dest}.} \item{callback}{A function that executes after the each option value is fully parsed. It's value is assigned to the option and its arguments are the option S4 object, the long flag string, the value of the option, the parser S4 object, and \code{...}.} \item{callback_args}{A list of additional arguments passed to callback function (via \code{do.call}).} \item{object}{An instance of the \code{OptionParser} class} } \value{ Both \code{make_option} and \code{add_option} return instances of class \code{OptionParserOption}. } \description{ \code{add_option} adds a option to a prexisting \code{OptionParser} instance whereas \code{make_option} is used to create a list of \code{OptionParserOption} instances that will be used in the \code{option_list} argument of the \code{OptionParser} function to create a new \code{OptionParser} instance. } \examples{ make_option("--longflag") make_option(c("-l", "--longflag")) make_option("--integer", type = "integer", default = 5) make_option("--integer", default = as.integer(5)) # same as previous # examples from package vignette make_option(c("-v", "--verbose"), action = "store_true", default = TRUE, help = "Print extra output [default]") make_option(c("-q", "--quietly"), action = "store_false", dest = "verbose", help = "Print little output") make_option(c("-c", "--count"), type = "integer", default = 5, help = "Number of random normals to generate [default \%default]", metavar = "number") make_option("--generator", default = "rnorm", help = "Function to generate random deviates [default \"\%default\"]") make_option("--mean", default = 0, help = "Mean if generator == \"rnorm\" [default \%default]") make_option("--sd", default = 1, metavar = "standard deviation", help = "Standard deviation if generator == \"rnorm\" [default \%default]") } \references{ Python's \code{optparse} library, which inspires this package, is described here: \url{https://docs.python.org/3/library/optparse.html} } \seealso{ \code{\link{parse_args}} \code{\link{OptionParser}} } \author{ Trevor Davis. } optparse/man/print_help.Rd0000644000176200001440000000142314117701306015315 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \name{print_help} \alias{print_help} \title{Printing an usage message from an OptionParser object} \usage{ print_help(object) } \arguments{ \item{object}{A \code{OptionParser} instance.} } \value{ \code{print_help} uses the \code{cat} function to print out a usage message. It returns \code{invisible(NULL)}. } \description{ \code{print_help} print an usage message from an OptionParser object, usually called by \code{parse_args} when it encounters a help option. } \references{ Python's \code{optparse} library, which inspired this package, is described here: \url{https://docs.python.org/3/library/optparse.html} } \seealso{ \code{{parse_args}} \code{{OptionParser}} } \author{ Trevor Davis. } optparse/man/formatter.Rd0000644000176200001440000000201014117275402015150 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \name{IndentedHelpFormatter} \alias{IndentedHelpFormatter} \alias{TitledHelpFormatter} \title{Builtin help text formatters} \usage{ IndentedHelpFormatter(object) TitledHelpFormatter(object) } \arguments{ \item{object}{An \code{\link[=OptionParser]{OptionParser()}} object.} } \value{ \code{NULL} invisibly. As a side effect prints out help text. } \description{ \code{IndentedHelpFormatter()} is the default help text formatter. \code{TitledHelpFormatter()} is an alternative help text formatter. } \examples{ parser <- OptionParser(formatter = IndentedHelpFormatter) parser <- add_option(parser, "--generator", help = "Generator option") parser <- add_option(parser, "--count", help = "Count option") print_help(parser) parser <- OptionParser(formatter = TitledHelpFormatter) parser <- add_option(parser, "--generator", help = "Generator option") parser <- add_option(parser, "--count", help = "Count option") print_help(parser) } optparse/man/parse_args.Rd0000644000176200001440000001051614117675550015315 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \encoding{latin1} \name{parse_args} \alias{parse_args} \alias{parse_args2} \title{Parse command line options.} \usage{ parse_args( object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE, positional_arguments = FALSE, convert_hyphens_to_underscores = FALSE ) parse_args2( object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE ) } \arguments{ \item{object}{An \code{OptionParser} instance.} \item{args}{A character vector containing command line options to be parsed. Default is everything after the Rscript program in the command line. If \code{positional_arguments} is not \code{FALSE} then \code{parse_args} will look for positional arguments at the end of this vector.} \item{print_help_and_exit}{Whether \code{parse_args} should call \code{print_help} to print out a usage message and exit the program. Default is \code{TRUE}.} \item{positional_arguments}{Number of \emph{positional} arguments. A numeric denoting the exact number of supported arguments, or a numeric vector of length two denoting the minimum and maximum number of arguments (\code{Inf} for no limit). The value \code{TRUE} is equivalent to \code{c(0, Inf)}. The default \code{FALSE} is supported for backward compatibility only, as it alters the format of the return value.} \item{convert_hyphens_to_underscores}{If the names in the returned list of options contains hyphens then convert them to underscores. The default \code{FALSE} is supported for backward compatibility reasons as it alters the format of the return value} } \value{ Returns a list with field \code{options} containing our option values as well as another field \code{args} which contains a vector of positional arguments. For backward compatibility, if and only if \code{positional_arguments} is \code{FALSE}, returns a list containing option values. } \description{ \code{parse_args} parses command line options using an \code{OptionParser} instance for guidance. \code{parse_args2} is a wrapper to \code{parse_args} setting the options \code{positional_arguments} and \code{convert_hyphens_to_underscores} to \code{TRUE}. } \section{Acknowledgement}{ A big thanks to Steve Lianoglou for a bug report and patch; Juan Carlos \enc{Borrás}{Borras} for a bug report; Jim Nikelski for a bug report and patch; Ino de Brujin and Benjamin Tyner for a bug report; Jonas Zimmermann for bug report; Miroslav Posta for bug reports; Stefan Seemayer for bug report and patch; Kirill \enc{Müller}{Muller} for patches; Steve Humburg for patch. } \examples{ # example from vignette option_list <- list( make_option(c("-v", "--verbose"), action = "store_true", default = TRUE, help = "Print extra output [default]"), make_option(c("-q", "--quietly"), action = "store_false", dest = "verbose", help = "Print little output"), make_option(c("-c", "--count"), type = "integer", default = 5, help = "Number of random normals to generate [default \%default]", metavar = "number"), make_option("--generator", default = "rnorm", help = "Function to generate random deviates [default \"\%default\"]"), make_option("--mean", default = 0, help = "Mean if generator == \"rnorm\" [default \%default]"), make_option("--sd", default = 1, metavar = "standard deviation", help = "Standard deviation if generator == \"rnorm\" [default \%default]") ) parse_args(OptionParser(option_list = option_list), args = c("--sd=3", "--quietly")) # example from vignette using positional arguments option_list2 <- list( make_option(c("-n", "--add-numbers"), action = "store_true", default = FALSE, help = "Print line number at the beginning of each line [default]") ) parser <- OptionParser(usage = "\%prog [options] file", option_list = option_list2) parse_args(parser, args = c("--add-numbers", "example.txt"), positional_arguments = TRUE) parse_args(parser, args = c("--add-numbers", "example.txt"), positional_arguments = TRUE, convert_hyphens_to_underscores = TRUE) parse_args2(parser, args = c("--add-numbers", "example.txt")) } \references{ Python's \code{optparse} library, which inspired this package, is described here: \url{https://docs.python.org/3/library/optparse.html} } \seealso{ \code{\link{OptionParser}} \code{\link{print_help}} } \author{ Trevor Davis. } optparse/man/OptionParser-class.Rd0000644000176200001440000000250114117305375016705 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \docType{class} \name{OptionParser-class} \alias{OptionParser-class} \title{Option Parser} \description{ Option Parser } \section{Slots}{ \describe{ \item{\code{usage}}{The program usage message that will printed out if \code{parse_args} finds a help option, \code{\%prog} is substituted with the value of the \code{prog} argument.} \item{\code{options}}{A list of of \code{OptionParserOption} instances that will define how \code{parse_args} reacts to command line options. \code{OptionParserOption} instances are usually created by \code{make_option} and can also be added to an existing \code{OptionParser} instance via the \code{add_option} function.} \item{\code{description}}{Additional text for \code{print_help} to print out between usage statement and options statement} \item{\code{epilogue}}{Additional text for \code{print_help} to print out after the options statement} \item{\code{formatter}}{A function that \code{print_help} will use to print out after the options statement. Default is \code{\link[=IndentedHelpFormatter]{IndentedHelpFormatter()}}. This package also provides the builtin formatter \code{\link[=TitledHelpFormatter]{TitledHelpFormatter()}}.} }} \seealso{ \code{\link{OptionParserOption}} } \author{ Trevor Davis. } optparse/DESCRIPTION0000644000176200001440000000330114130114742013607 0ustar liggesusersEncoding: UTF-8 Package: optparse Type: Package Title: Command Line Option Parser Version: 1.7.1 Authors@R: c(person("Trevor L", "Davis", role = c("aut", "cre"), email="trevor.l.davis@gmail.com"), person("Allen", "Day", role="ctb", comment="Some documentation and examples ported from the getopt package."), person("Python Software Foundation", role="ctb", comment="Some documentation from the optparse Python module."), person("Steve", "Lianoglou", role="ctb"), person("Jim", "Nikelski", role="ctb"), person("Kirill", "Müller", role="ctb"), person("Peter", "Humburg", role="ctb"), person("Rich", "FitzJohn", role="ctb"), person("Gyu Jin", "Choi", role="ctb")) Description: A command line parser inspired by Python's 'optparse' library to be used with Rscript to write "#!" shebang scripts that accept short and long flag/options. License: GPL (>= 2) Copyright: See file (inst/)COPYRIGHTS. URL: https://github.com/trevorld/r-optparse BugReports: https://github.com/trevorld/r-optparse/issues LazyLoad: yes Depends: R (>= 2.9.0) Imports: methods, getopt (>= 1.20.2) Suggests: knitr (>= 1.15.19), stringr, testthat VignetteBuilder: knitr RoxygenNote: 7.1.1 NeedsCompilation: no Packaged: 2021-10-08 18:53:12 UTC; trevor Author: Trevor L Davis [aut, cre], Allen Day [ctb] (Some documentation and examples ported from the getopt package.), Python Software Foundation [ctb] (Some documentation from the optparse Python module.), Steve Lianoglou [ctb], Jim Nikelski [ctb], Kirill Müller [ctb], Peter Humburg [ctb], Rich FitzJohn [ctb], Gyu Jin Choi [ctb] Maintainer: Trevor L Davis Repository: CRAN Date/Publication: 2021-10-08 19:20:02 UTC optparse/build/0000755000176200001440000000000014130111630013174 5ustar liggesusersoptparse/build/vignette.rds0000644000176200001440000000033414130111630015533 0ustar liggesusersuQ 0~E׾DMA"]t;r@7'ώ*W8gg}r1r\H||8CY뚪Źj. HV(Ȇ FR .N uUZ`EDЊ5|ΒJe4#tx)/uq$R3|+f+^P^4(Q]optparse/tests/0000755000176200001440000000000014117214504013250 5ustar liggesusersoptparse/tests/test_help.Rout.save0000644000176200001440000000153613567307174017072 0ustar liggesusers R version 3.3.2 (2016-10-31) -- "Sincere Pumpkin Patch" Copyright (C) 2016 The R Foundation for Statistical Computing Platform: x86_64-pc-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > library("optparse") > > parser <- OptionParser() > parse_args(parser, "--help") Usage: %prog [options] Options: -h, --help Show this help message and exit optparse/tests/test_help.R0000644000176200001440000000011313567265621015373 0ustar liggesuserslibrary("optparse") parser <- OptionParser() parse_args(parser, "--help") optparse/tests/testthat/0000755000176200001440000000000014117461766015126 5ustar liggesusersoptparse/tests/testthat/test-optparse.R0000644000176200001440000004205614117310537020057 0ustar liggesusers# Copyright 2010-2019 Trevor L Davis # Copyright 2013 Kirill Müller # Copyright 2008 Allen Day # # This file is free software: you may copy, redistribute and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 2 of the License, or (at your # option) any later version. # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . option_list <- list( make_option(c("-v", "--verbose"), action = "store_true", default = TRUE, help = "Print extra output [default]"), make_option(c("-q", "--quietly"), action = "store_false", dest = "verbose", help = "Print little output"), make_option(c("-c", "--count"), type = "integer", default = 5, help = "Number of random normals to generate [default \\%default]", metavar = "number"), make_option("--generator", default = "rnorm", help = "Function to generate random deviates [default \"\\%default\"]"), make_option("--mean", default = 0, help = "Mean if generator == \"rnorm\" [default \\%default]"), make_option("--sd", default = 1, metavar = "standard deviation", help = "Standard deviation if generator == \"rnorm\" [default \\%default]") ) parser_ol <- OptionParser(option_list = option_list) context("Testing make_option") test_that("make_option works as expected", { expect_equal(make_option("--integer", type = "integer", default = 5), make_option("--integer", default = as.integer(5))) expect_equal(make_option("--logical", type = "logical", default = "TRUE"), make_option("--logical", default = TRUE)) expect_equal(make_option("--filename")@type, "character") expect_that(make_option("badflag"), throws_error()) expect_error(make_option("-cd"), "must only be") }) get_long_flags <- function(parser) { sort(sapply(parser@options, function(x) x@long_flag)) } context("Test add_option") test_that("add_option works as expected", { parser1 <- OptionParser(option_list = list(make_option("--generator"), make_option("--count"))) parser2 <- OptionParser() parser2 <- add_option(parser2, "--generator") parser2 <- add_option(parser2, "--count") expect_equal(get_long_flags(parser1), get_long_flags(parser2)) }) context("Testing parse_args") test_that("parse_args works as expected", { # option_list took outside test_that option_list2 <- list( make_option(c("-n", "--add-numbers"), action = "store_true", default = FALSE, help = "Print line number at the beginning of each line [default]") ) parser <- OptionParser(usage = "\\%prog [options] file", option_list = option_list2) expect_equal(sort_list(parse_args(parser_ol, args = c("--sd=3", "--quietly"))), sort_list(list(sd = 3, verbose = FALSE, help = FALSE, count = 5, mean = 0, generator = "rnorm"))) expect_equal(sort_list(parse_args(parser_ol, args = character(0), positional_arguments = TRUE)), sort_list(list(options = list(sd = 1, help = FALSE, verbose = TRUE, count = 5, mean = 0, generator = "rnorm"), args = character(0)))) expect_equal(sort_list(parse_args(parser_ol, args = c("-c", "10"))), sort_list(list(sd = 1, help = FALSE, verbose = TRUE, count = 10, mean = 0, generator = "rnorm"))) expect_equal(sort_list(parse_args(parser, args = c("--add-numbers", "example.txt"), positional_arguments = TRUE)), sort_list(list(options = list(`add-numbers` = TRUE, help = FALSE), args = c("example.txt")))) expect_equal(sort_list(parse_args(parser, args = c("--add-numbers"), positional_arguments = TRUE)), sort_list(list(options = list(`add-numbers` = TRUE, help = FALSE), args = character(0)))) expect_equal(sort_list(parse_args(parser, args = c("--add-numbers"), positional_arguments = TRUE, convert_hyphens_to_underscores = TRUE)), sort_list(list(options = list(add_numbers = TRUE, help = FALSE), args = character(0)))) expect_equal(sort_list(parse_args2(parser, args = c("--add-numbers"))), sort_list(list(options = list(add_numbers = TRUE, help = FALSE), args = character(0)))) expect_error(parse_args(parser, args = c("-add-numbers", "example.txt")), positional_arguments = FALSE) expect_error(parse_args(parser, args = c("-add-numbers", "example.txt"), positional_arguments = TRUE)) expect_equal(sort_list(parse_args(parser, args = c("--add-numbers", "example.txt"), positional_arguments = c(1, 3))), sort_list(list(options = list(`add-numbers` = TRUE, help = FALSE), args = c("example.txt")))) expect_equal(sort_list(parse_args(parser, args = c("example.txt"), positional_arguments = 1)), sort_list(list(options = list(`add-numbers` = FALSE, help = FALSE), args = c("example.txt")))) expect_that(parse_args(parser, args = c("-add-numbers", "example.txt"), positional_arguments = c(0, 1)), throws_error()) expect_that(parse_args(parser, args = c("example.txt"), positional_arguments = c(2, Inf)), throws_error()) expect_that(parse_args(parser, args = c("example.txt"), positional_arguments = 2), throws_error()) expect_that(parse_args(parser, args = c("example.txt"), positional_arguments = "any"), throws_error("must be logical or numeric")) expect_that(parse_args(parser, args = c("example.txt"), positional_arguments = 1:3), throws_error("must have length 1 or 2")) if (interactive()) { expect_that(capture.output(parse_args(parser, args = c("--help"))), throws_error("help requested")) expect_that(capture.output(parse_args(parser, args = c("--help"), positional_arguments = c(1, 2))), throws_error("help requested")) } }) # Patch from Gyu Jin Choi. test_that("callback works as expected", { power <- function(x, n = 2) x^n callback_fn <- function(option, flag, option_value, parser, n = 2) { power(option_value, n) } parser0 <- OptionParser() parser1 <- add_option(parser0, c("-s", "--squared_distance"), type = "integer", action = "callback", help = "Squared distance between two points", callback = callback_fn, callback_args = list(2)) opts <- parse_args(parser1, args = c("--squared_distance=16")) expect_equal(opts$squared_distance, 256) # Bug found by Ni Huang (#28) opts <- parse_args(parser1, positional_argument = TRUE, args = c("-s", "3")) expect_equal(opts$options$squared_distance, 9) # Bug found by Ni Huang (#29) expect_output(print_help(parser1), "SQUARED_DISTANCE") parser2 <- add_option(parser0, c("-v", "--value"), type = "integer", action = "callback", callback = callback_fn, callback_args = list(n = 3)) opts <- parse_args(parser2, args = c("--value=2")) expect_equal(opts$value, 8) parser3 <- add_option(parser0, c("-v", "--value"), type = "integer", action = "callback", callback = callback_fn) opts <- parse_args(parser3, args = c("--value=2")) expect_equal(opts$value, 4) expect_warning(add_option(parser0, "--warning", action = "store", callback = as.list), "callback argument is supplied for non-callback action") expect_warning(add_option(parser0, "--warning", callback_args = list(3, b = 4)), "callback_args argument is supplied for non-callback action") expect_warning(add_option(parser0, "--warning", action = "callback", type = "numeric", callback = "hello"), "callback argument is not a function") callback_fn <- function(option, flag, option_value, parser) { 42 } parser4 <- add_option(parser0, "--null_type", type = NULL, callback = callback_fn) opts <- parse_args(parser4, args = c("--null_type")) expect_equal(opts$null_type, 42) }) # Bug found by Miroslav Posta test_that("test using numeric instead of double", { option_list_neg <- list(make_option(c("-m", "--mean"), default = 0, type = "numeric")) parser <- OptionParser(usage = "\\%prog [options] file", option_list = option_list_neg) opts <- parse_args(parser, args = c("-m", "-5.0")) expect_equal(opts$mean, -5.0) }) # Bug found by Juan Carlos Borrás test_that("test bug of multiple '=' signs", { optlist <- list( make_option(c("-s", "--substitutions"), type = "character", dest = "substitutions", default = NULL, help = 'String of the form "KEY1=VALUE1 KEY2=VALUE2 ... KEY=VALUE" stating the SQL template substitutions', metavar = "substitution-list") ) optparser <- OptionParser(option_list = optlist) opt <- parse_args(optparser, c("-s", "FOO=bar")) opt_alt <- parse_args(optparser, c("--substitutions=FOO=bar")) expect_that(opt, equals(opt_alt)) # also check when positional_arguments is set to true, like later bug unit test opt <- parse_args(optparser, c("-s", "FOO=bar"), positional_arguments = TRUE) opt_alt <- parse_args(optparser, c("--substitutions=FOO=bar"), positional_arguments = TRUE) expect_that(opt, equals(opt_alt)) }) # Bug found by Jim Nikelski test_that("test bug when multiple short flag options '-abc' with positional_arguments = TRUE", { sort_list <- function(unsorted_list) { for (ii in seq_along(unsorted_list)) { if (is.list(unsorted_list[[ii]])) { unsorted_list[[ii]] <- sort_list(unsorted_list[[ii]]) } } unsorted_list[sort(names(unsorted_list))] } expect_equal(sort_list(parse_args(parser_ol, args = c("-qc", "10"), positional_arguments = TRUE)), sort_list(list(options = list(sd = 1, help = FALSE, verbose = FALSE, count = 10, mean = 0, generator = "rnorm"), args = character(0)))) expect_error(parse_args(parser_ol, args = c("-qcde", "10"), positional_arguments = TRUE)) expect_error(parse_args(parser_ol, args = c("a", "b", "c", "d", "e"), positional_arguments = c(1, 3))) expect_equal(sort_list(parse_args(parser_ol, args = c("CMD", "-qc", "10", "bumblebee"), positional_arguments = TRUE)), sort_list(list(options = list(sd = 1, help = FALSE, verbose = FALSE, count = 10, mean = 0, generator = "rnorm"), args = c("CMD", "bumblebee")))) args <- c("CMD", "-qc", "10", "bumblebee", "--qcdefg") expect_error(parse_args(parser_ol, args = args, positional_arguments = TRUE), "Don't know long flag argument --qcdefg") args <- c("-qxc", "10", "bumblebee") expect_error(parse_args(parser_ol, args = args, positional_arguments = TRUE), 'short flag "x" is invalid') }) # Bug found by Ino de Brujin and Benjamin Tyner test_that("test bug when long flag option with '=' with positional_arguments = TRUE", { expect_equal(sort_list(parse_args(parser_ol, args = c("--count=10"), positional_arguments = TRUE)), sort_list(list(options = list(sd = 1, help = FALSE, verbose = TRUE, count = 10, mean = 0, generator = "rnorm"), args = character(0)))) }) # Bug found by Miroslav Posta optlist <- list(make_option(c("--tmin"), type = "numeric", help = "Startup time [sec]. ")) parser <- OptionParser(option_list = optlist, usage = "", epilogue = "") test_that("test bug with a NA short flag option with positional_arguments = TRUE", { expect_equal(sort_list(parse_args(args = c("-h", "foo"), parser, positional_arguments = TRUE, print_help_and_exit = FALSE)), sort_list(list(options = list(help = TRUE), args = "foo"))) }) context("print_help") test_that("description and epilogue work as expected", { parser <- OptionParser() expect_output(print_help(parser), "Usage:") expect_output(print_help(parser), "Options:") parser2 <- OptionParser(usage = "program", description = "foo", epilogue = "bar") expect_output(print_help(parser2), "foo") expect_output(print_help(parser2), "bar$") expect_output(print_help(parser2), "^Usage: ") expect_equal(stringr::str_count( capture.output(print_help(OptionParser("usage: foo bar")))[1], "[Uu]sage"), 1) parser <- OptionParser(formatter = TitledHelpFormatter) parser <- add_option(parser, c("-f", "--foo"), help = "Foobar") expect_output(print_help(parser), "Usage\n=====") # bug found by Stefan Seemayer for NA default optlist <- list( make_option(c("--na"), type = "character", default = NA, help = "NA default is %default"), make_option(c("--null"), type = "character", default = NULL, help = "NULL default is %default"), make_option(c("--str"), type = "character", default = "str", help = "str default is %default"), make_option(c("--bool"), type = "logical", default = TRUE, help = "bool default is %default"), make_option(c("--int"), type = "integer", default = 42, help = "int default is %default"), make_option(c("--int"), type = "double", default = 11.11, help = "double default is %default") ) parser <- OptionParser(option_list = optlist) expect_output(print_help(parser), "NA default is NA") expect_output(print_help(parser), "NULL default is NULL") expect_output(print_help(parser), "str default is str") expect_output(print_help(parser), "bool default is TRUE") expect_output(print_help(parser), "int default is 42") expect_output(print_help(parser), "double default is 11.11") # bug / feature request by Miroslav Posta parser <- OptionParser(usage = "test %prog test %prog", epilogue = "epilog test %prog %prog", description = "description %prog test %prog", prog = "unit_test.r") expect_output(print_help(parser), "Usage:.*unit_test.r.*unit_test.r") expect_output(print_help(parser), "description unit_test.r test unit_test.r") expect_output(print_help(parser), "epilog test unit_test.r unit_test.r") }) # Bug found by Benjamin Tyner test_that("Can set zero length default options", { option_list_neg <- list(make_option(c("-m", "--mean"), default = numeric(0), type = "numeric", help = "Default %default")) parser <- OptionParser(usage = "\\%prog [options] file", option_list = option_list_neg) expect_equal(sort_list(parse_args(parser, args = c("-m", "-5.0"))), sort_list(list(mean = -5, help = FALSE))) expect_equal(sort_list(parse_args(parser)), sort_list(list(mean = numeric(0), help = FALSE))) expect_output(print_help(parser), "Default double") }) # Bug found by Matthew Flickinger test_that("Can parse empty string", { option_list <- list(make_option(c("", "--string"))) parser <- OptionParser(usage = "\\%prog [options] file", option_list = option_list) expect_equal(sort_list(parse_args(parser, args = c("--string="))), sort_list(list(string = "", help = FALSE))) }) # nolint start # # Bug found by Rich FitzJohn # oo <- options() # on.exit(options(oo)) # options(warnPartialMatchArgs = TRUE) # test_that("Avoid partial matching of arguments", { # expect_that(seq(along = 1:10), gives_warning("partial argument match")) # expect_that(seq_along(1:10), not(gives_warning())) # expect_that(parse_args(args = c("-h", "foo"), parser, positional_arguments = TRUE, print_help_and_exit = FALSE), # not(gives_warning())) # expect_that(print_help(OptionParser()), not(gives_warning())) # }) # nolint end # Use h flag for non-help (Reported by Jeff Bruce) context("Use h option for non-help") test_that("Use h option for non-help", { option_list_neg <- list(make_option(c("-h", "--mean"), default = 0.0)) parser <- OptionParser(usage = "\\%prog [options] file", option_list = option_list_neg) expect_error(parse_args(parser, args = c("-h", "-5.0")), "redundant short names") option_list_neg <- list(make_option(c("-h", "--mean"), default = 0.0)) parser <- OptionParser(usage = "\\%prog [options] file", option_list = option_list_neg, add_help_option = FALSE) args <- parse_args(parser, args = c("-h", "-5.0")) expect_equal(args, list(mean = -5.0)) }) optparse/tests/run-all.R0000644000176200001440000000005412536077777014772 0ustar liggesuserslibrary("testthat") test_check("optparse") optparse/vignettes/0000755000176200001440000000000014130111630014105 5ustar liggesusersoptparse/vignettes/optparse.Rrst0000644000176200001440000001213612253432313016631 0ustar liggesusers.. %\VignetteIndexEntry{optparse Command Line Option Parsing} %\VignetteEngine{knitr} optparse Command Line Option Parsing ==================================== optparse is a command line option parser inspired by Python's "optparse" library. Use this with Rscript to write "#!"-shebang scripts that accept short and long flags/options, generate a usage statement, and set default values for options that are not specified on the command line. .. {r echo=FALSE} .. library("knitr") .. Rscript_executable <- paste(file.path(R.home(), "bin", "Rscript"), "--vanilla") .. opts_knit$set(root.dir = system.file("exec", package="optparse")) # to access the "Rscript files" .. opts_chunk$set(comment=NA, echo=FALSE) .. # setwd(system.file("exec", package="optparse")) # to access the "Rscript files" .. list_file_command <- "ls" .. chmod_command <- "chmod ug+x display_file.R example.R" .. path_command <- "export PATH=$PATH:`pwd`" .. run_command <- function(string) { suppressWarnings(cat(system(string, intern=TRUE), sep="\n")) } .. .. In our working directory we have two example R scripts, named "example.R" and "display\_file.R" illustrating the use of the optparse package. **:r:`paste("bash$", list_file_command)`** .. {r} .. run_command(sprintf("%s", list_file_command)) .. command <- "display_file.R example.R" # to show file .. .. In order for a \*nix system to recognize a "#!"-shebang line you need to mark the file executable with the ``chmod`` command, it also helps to add the directory containing your Rscripts to your path: **:r:`paste("bash$", chmod_command)`** **:r:`paste("bash$", path_command)`** Here is what ``example.R`` contains: **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. .. {r} .. command <- "example.R --help" # same as system("Rscript example.R -h") .. .. By default *optparse* will generate a help message if it encounters ``--help`` or ``-h`` on the command line. Note how ``%default`` in the example program was replaced by the actual default values in the help statement that *optparse* generated. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R" # rely only on defaults .. .. If you specify default values when creating your ``OptionParser`` then *optparse* will use them as expected. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --mean=10 --sd=10 --count=3" .. .. Or you can specify your own values. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --quiet -c 4 --generator=\"runif\"" # same as above but "quiet" .. .. If you remember from the example program that ``--quiet`` had ``action="store_false"`` and ``dest="verbose"``. This means that ``--quiet`` is a switch that turns the ``verbose`` option from its default value of ``TRUE`` to ``FALSE``. Note how the ``verbose`` and ``quiet`` options store their value in the exact same variable. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --silent -m 5" # same as above but "quiet" .. .. If you specify an illegal flag then *optparse* will throw an error. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R -c 100 -c 2 -c 1000 -c 7" # same as above but "quiet" .. .. If you specify the same option multiple times then *optparse* will use the value of the last option specified. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. *optparse* can also recognize positional arguments if ``parse_args`` is given the option ``positional_arguments = c(min_pa, max_pa)`` where ``min_pa`` is the minimum and ``max_pa`` is the maximum number of supported positional arguments. (A single numeric corresponds to ``min_pa == max_pa``, ``TRUE`` is equivalent to ``c(0, Inf)``, and ``FALSE``, the default, is equivalent to ``0``.) Below we give an example program *display_file.R*, which is a program that prints out the contents of a single file (the required positional argument, not an optional argument) and which accepts the normal help option as well as an option to add line numbers to the output. Note that the positional arguments need to be placed *after* the optional arguments. .. {r} .. command <- "display_file.R --help" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R --add_numbers display_file.R" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R non_existent_file.txt" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. optparse/COPYING0000755000176200001440000004313312206447600013152 0ustar liggesusers GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. optparse/R/0000755000176200001440000000000014120212704012301 5ustar liggesusersoptparse/R/optparse.R0000644000176200001440000010013314117701276014274 0ustar liggesusers# Copyright (c) 2010-2019 Trevor L. Davis # Copyright (c) 2015 Rick FitzJohn https://github.com/richfitz # Copyright (c) 2013 Kirill Müller https://github.com/krlmlr # Copyright (c) 2011 Jim Nikelski # Copyright (c) 2010 Steve Lianoglou # # This file is free software: you may copy, redistribute and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 2 of the License, or (at your # option) any later version. # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # This file incorporates work from the optparse module in Python 2.6.2. # # Copyright (c) 1990-2009 Python Software Foundation; All Rights Reserved # # See (inst/)COPYRIGHTS or http://docs.python.org/2/license.html for the full # Python (GPL-compatible) license stack. # # As mentioned above, this file incorporates some patches by Steve Lianoglou (c) 2010 # He explicitly gave me a non-exclusive unlimited license to code in his patches #' Option Parser #' #' @slot usage The program usage message that will printed out if #' \code{parse_args} finds a help option, \code{\%prog} is substituted with the #' value of the \code{prog} argument. #' @slot options A list of of \code{OptionParserOption} instances that will #' define how \code{parse_args} reacts to command line options. #' \code{OptionParserOption} instances are usually created by \code{make_option} #' and can also be added to an existing \code{OptionParser} instance via the #' \code{add_option} function. #' @slot description Additional text for \code{print_help} to print out between #' usage statement and options statement #' @slot epilogue Additional text for \code{print_help} to print out after #' the options statement #' @slot formatter A function that \code{print_help} will use to print out after #' the options statement. Default is [IndentedHelpFormatter()]. This #' package also provides the builtin formatter [TitledHelpFormatter()]. #' @author Trevor Davis. #' @seealso \code{\link{OptionParserOption}} #' @import methods #' @exportClass OptionParser setClass("OptionParser", representation(usage = "character", options = "list", description = "character", epilogue = "character", formatter = "function")) #' Class to hold information about command-line options #' #' @slot short_flag String of the desired short flag #' comprised of the \dQuote{-} followed by a letter. #' @slot long_flag String of the desired long flag comprised of \dQuote{--} #' followed by a letter and then a sequence of alphanumeric characters. #' @slot action A character string that describes the action \code{optparse} #' should take when it encounters an option, either \dQuote{store}, #' \dQuote{store_true}, or \dQuote{store_false}. The default is \dQuote{store} #' which signifies that \code{optparse} should store the specified following #' value if the option is found on the command string. \dQuote{store_true} #' stores \code{TRUE} if the option is found and \dQuote{store_false} stores #' \code{FALSE} if the option is found. #' @slot type A character string that describes specifies which data type #' should be stored, either \dQuote{logical}, \dQuote{integer}, \dQuote{double}, #' \dQuote{complex}, or \dQuote{character}. Default is \dQuote{logical} if #' \code{action \%in\% c("store_true", store_false)}, \code{typeof(default)} if #' \code{action == "store"} and default is not \code{NULL} and #' \dQuote{character} if \code{action == "store"} and default is \code{NULL}. #' \dQuote{numeric} will be converted to \dQuote{double}. #' @slot dest A character string that specifies what field in the list returned #' by \code{parse_args} should \code{optparse} store option values. Default is #' derived from the long flag in \code{opt_str}. #' @slot default The default value \code{optparse} should use if it does not #' find the option on the command line. #' @slot help A character string describing the option to be used by #' \code{print_help} in generating a usage message. \code{\%default} will be #' substituted by the value of \code{default}. #' @slot metavar A character string that stands in for the option argument when #' printing help text. Default is the value of \code{dest}. #' @slot callback A function that executes after the each option value is fully parsed #' @slot callback_args Additional arguments that pass to the callback function. #' @seealso \code{\link{make_option}} #' @exportClass OptionParserOption #' @export OptionParserOption OptionParserOption <- setClass("OptionParserOption", representation(short_flag = "character", # nolint long_flag = "character", action = "character", type = "character", dest = "character", default = "ANY", help = "character", metavar = "character", callback = "ANY", callback_args = "ANY")) #' A function to create an instance of a parser object #' #' This function is used to create an instance of a parser object #' which when combined with the \code{parse_args}, \code{make_option}, and \code{add_option} #' methods is very useful for parsing options from the command line. #' #' @param usage The program usage message that will printed out if #' \code{parse_args} finds a help option, \code{\%prog} is substituted with the #' value of the \code{prog} argument. #' @param option_list A list of of \code{OptionParserOption} instances that will #' define how \code{parse_args} reacts to command line options. #' \code{OptionParserOption} instances are usually created by \code{make_option} #' and can also be added to an existing \code{OptionParser} instance via the #' \code{add_option} function. #' @param add_help_option Whether a standard help option should be automatically #' added to the \code{OptionParser} instance. #' @param prog Program name to be substituted for \code{\%prog} in the usage #' message (including description and epilogue if present), #' the default is to use the actual Rscript file name if called by an #' Rscript file and otherwise keep \code{\%prog}. #' @param description Additional text for \code{print_help} to print out between #' usage statement and options statement #' @param epilogue Additional text for \code{print_help} to print out after #' the options statement #' @param formatter A function that formats usage text. #' The function should take only one argument (an `OptionParser()` object). #' Default is [IndentedHelpFormatter()]. #' The other builtin formatter provided by this package is [TitledHelpFormatter()]. #' @return An instance of the \code{OptionParser} class. #' @author Trevor Davis. #' #' @seealso \code{\link{parse_args}} \code{\link{make_option}} #' \code{\link{add_option}} #' @references Python's \code{optparse} library, which inspired this package, #' is described here: \url{https://docs.python.org/3/library/optparse.html} #' @import getopt #' @export OptionParser <- function(usage = "usage: %prog [options]", option_list = list(), # nolint add_help_option = TRUE, prog = NULL, description = "", epilogue = "", formatter = IndentedHelpFormatter) { if (is.null(prog)) { prog <- get_Rscript_filename() } if (length(prog) && !is.na(prog)) { usage <- gsub("%prog", prog, usage) description <- gsub("%prog", prog, description) epilogue <- gsub("%prog", prog, epilogue) } # Match behavior of usage string in Python optparse package usage <- sub("^usage: ", "Usage: ", usage) usage <- ifelse(grepl("^Usage: ", usage), usage, sub("^", "Usage: ", usage)) if (add_help_option) { option_list[[length(option_list) + 1]] <- make_option(c("-h", "--help"), action = "store_true", dest = "help", default = FALSE, help = "Show this help message and exit") } return(new("OptionParser", usage = usage, options = option_list, description = description, epilogue = epilogue, formatter = formatter)) } #' Functions to enable our OptionParser to recognize specific command line #' options. #' #' \code{add_option} adds a option to a prexisting \code{OptionParser} instance #' whereas \code{make_option} is used to create a list of #' \code{OptionParserOption} instances that will be used in the #' \code{option_list} argument of the \code{OptionParser} function to create a #' new \code{OptionParser} instance. #' #' @rdname add_make_option #' @param object An instance of the \code{OptionParser} class #' @param opt_str A character vector containing the string of the desired long #' flag comprised of \dQuote{--} followed by a letter and then a sequence of #' alphanumeric characters and optionally a string of the desired short flag #' comprised of the \dQuote{-} followed by a letter. #' @param action A character string that describes the action \code{optparse} #' should take when it encounters an option, either \dQuote{store}, #' \dQuote{store_true}, \dQuote{store_false}, or \dQuote{callback}. #' An action of \dQuote{store} signifies that \code{optparse} #' should store the specified following value if the option is found on the command string. #' \dQuote{store_true} stores \code{TRUE} if the option is found #' and \dQuote{store_false} stores \code{FALSE} if the option is found. #' \dQuote{callback} stores the return value produced by the function #' specified in the \code{callback} argument. #' If \code{callback} is not \code{NULL} then the default is \dQuote{callback} else \dQuote{store}. #' @param type A character string that describes specifies which data type #' should be stored, either \dQuote{logical}, \dQuote{integer}, \dQuote{double}, #' \dQuote{complex}, or \dQuote{character}. Default is \dQuote{logical} if #' \code{action \%in\% c("store_true", store_false)}, \code{typeof(default)} if #' \code{action == "store"} and default is not \code{NULL} and #' \dQuote{character} if \code{action == "store"} and default is \code{NULL}. #' \dQuote{numeric} will be converted to \dQuote{double}. #' @param dest A character string that specifies what field in the list returned #' by \code{parse_args} should \code{optparse} store option values. Default is #' derived from the long flag in \code{opt_str}. #' @param default The default value \code{optparse} should use if it does not #' find the option on the command line. #' @param help A character string describing the option to be used by #' \code{print_help} in generating a usage message. \code{\%default} will be #' substituted by the value of \code{default}. #' @param metavar A character string that stands in for the option argument when #' printing help text. Default is the value of \code{dest}. #' @param callback A function that executes after the each option value is fully #' parsed. It's value is assigned to the option and its arguments are #' the option S4 object, the long flag string, the value of the option, #' the parser S4 object, and \code{...}. #' @param callback_args A list of additional arguments passed to callback function (via \code{do.call}). #' @return Both \code{make_option} and \code{add_option} return instances of #' class \code{OptionParserOption}. #' @author Trevor Davis. #' #' @seealso \code{\link{parse_args}} \code{\link{OptionParser}} #' @references Python's \code{optparse} library, which inspires this package, #' is described here: \url{https://docs.python.org/3/library/optparse.html} #' @examples #' #' make_option("--longflag") #' make_option(c("-l", "--longflag")) #' make_option("--integer", type = "integer", default = 5) #' make_option("--integer", default = as.integer(5)) # same as previous #' #' # examples from package vignette #' make_option(c("-v", "--verbose"), action = "store_true", default = TRUE, #' help = "Print extra output [default]") #' make_option(c("-q", "--quietly"), action = "store_false", #' dest = "verbose", help = "Print little output") #' make_option(c("-c", "--count"), type = "integer", default = 5, #' help = "Number of random normals to generate [default %default]", #' metavar = "number") #' make_option("--generator", default = "rnorm", #' help = "Function to generate random deviates [default \"%default\"]") #' make_option("--mean", default = 0, #' help = "Mean if generator == \"rnorm\" [default %default]") #' make_option("--sd", default = 1, metavar = "standard deviation", #' help = "Standard deviation if generator == \"rnorm\" [default %default]") #' #' @export make_option <- function(opt_str, action = NULL, type = NULL, dest = NULL, default = NULL, help = "", metavar = NULL, callback = NULL, callback_args = NULL) { action <- ifelse(is.null(action), ifelse(is.null(callback), "store", "callback"), action) # flags short_flag <- opt_str[grepl("^-[[:alpha:]]", opt_str)] if (length(short_flag) == 0) { short_flag <- NA_character_ } else { if (nchar(short_flag) > 2) { stop(paste("Short flag", short_flag, "must only be a '-' and a single letter")) } } long_flag <- opt_str[grepl("^--[[:alpha:]]", opt_str)] if (length(long_flag) == 0) stop("We require a long flag option") # type if (is.null(type)) { type <- infer_type(action, default) } if (type == "numeric") type <- "double" # default if ((type != typeof(default)) && !is.null(default)) { storage.mode(default) <- type } # dest if (is.null(dest)) dest <- sub("^--", "", long_flag) # metavar if (is.null(metavar)) { if (.option_needs_argument_helper(action, type)) { metavar <- sub("^--", "", long_flag) } else { metavar <- character(0) } } warn_callback(action, callback, callback_args) if (is.null(callback_args)) callback_args <- list() return(new("OptionParserOption", short_flag = short_flag, long_flag = long_flag, action = action, type = type, dest = dest, default = default, help = help, metavar = metavar, callback = callback, callback_args = callback_args)) } infer_type <- function(action, default) { switch(action, store = ifelse(is.null(default), "character", typeof(default)), store_false = "logical", store_true = "logical", callback = "NULL") } warn_callback <- function(action, callback, callback_args) { if (action == "callback") { if (!is.function(callback)) warning(sprintf("callback argument is not a function")) } else { if (!is.null(callback)) warning(sprintf("callback argument is supplied for non-callback action")) if (!is.null(callback_args)) warning(sprintf("callback_args argument is supplied for non-callback action")) } } #' @rdname add_make_option #' @export add_option <- function(object, opt_str, action = NULL, type = NULL, dest = NULL, default = NULL, help = "", metavar = NULL, callback = NULL, callback_args = NULL) { options_list <- object@options n_original_options <- length(options_list) options_list[[n_original_options + 1]] <- make_option(opt_str = opt_str, action = action, type = type, dest = dest, default = default, help = help, metavar = metavar, callback = callback, callback_args = callback_args) object@options <- options_list return(object) } #' Printing an usage message from an OptionParser object #' #' \code{print_help} print an usage message from an OptionParser object, usually #' called by \code{parse_args} when it encounters a help option. #' #' @param object A \code{OptionParser} instance. #' @return \code{print_help} uses the \code{cat} function to print out a usage #' message. It returns \code{invisible(NULL)}. #' @author Trevor Davis. #' #' @seealso \code{{parse_args}} \code{{OptionParser}} #' @references Python's \code{optparse} library, which inspired this package, #' is described here: \url{https://docs.python.org/3/library/optparse.html} #' @export print_help <- function(object) { object@formatter(object) } #' Builtin help text formatters #' #' `IndentedHelpFormatter()` is the default help text formatter. #' `TitledHelpFormatter()` is an alternative help text formatter. #' #' @param object An [OptionParser()] object. #' @examples #' parser <- OptionParser(formatter = IndentedHelpFormatter) #' parser <- add_option(parser, "--generator", help = "Generator option") #' parser <- add_option(parser, "--count", help = "Count option") #' print_help(parser) #' #' parser <- OptionParser(formatter = TitledHelpFormatter) #' parser <- add_option(parser, "--generator", help = "Generator option") #' parser <- add_option(parser, "--count", help = "Count option") #' print_help(parser) #' @return `NULL` invisibly. As a side effect prints out help text. #' @rdname formatter #' @export IndentedHelpFormatter <- function(object) { cat(object@usage, fill = TRUE) cat(object@description, fill = TRUE) cat("\n") cat("Options:", sep = "\n") options_list <- object@options for (ii in seq_along(options_list)) { option <- options_list[[ii]] cat("\t") if (!is.na(option@short_flag)) { cat(option@short_flag) if (.option_needs_argument(option)) { cat(" ", toupper(option@metavar), sep = "") } cat(", ") } if (!is.null(option@long_flag)) { cat(option@long_flag) if (.option_needs_argument(option)) { cat("=", toupper(option@metavar), sep = "") } } cat("\n\t\t") cat(sub("%default", .as_string(option@default), option@help)) cat("\n\n") } cat(object@epilogue, fill = TRUE) return(invisible(NULL)) } #' @rdname formatter #' @export TitledHelpFormatter <- function(object) { usage <- c("Usage\n=====\n", gsub("Usage: ", "", object@usage)) cat(usage, fill = TRUE) cat(object@description, fill = TRUE) cat("\n") cat("Options", "=======", sep = "\n") options_list <- object@options for (ii in seq_along(options_list)) { option <- options_list[[ii]] if (!is.null(option@long_flag)) { cat(option@long_flag) if (.option_needs_argument(option)) { cat("=", toupper(option@metavar), sep = "") } } if (!is.na(option@short_flag)) { cat(", ") cat(option@short_flag) if (.option_needs_argument(option)) { cat(" ", toupper(option@metavar), sep = "") } } cat("\n\t\t") cat(sub("%default", .as_string(option@default), option@help)) cat("\n\n") } cat(object@epilogue, fill = TRUE) return(invisible(NULL)) } # Turn default values into a string we can cat, handles NA's and NULL's .as_string <- function(default) { if (is.null(default)) { default_str <- "NULL" } else if (!length(default)) { default_str <- paste0(typeof(default), "(0)") } else if (is.na(default)) { default_str <- "NA" } else { default_str <- as.character(default) } } #' Parse command line options. #' #' \code{parse_args} parses command line options using an \code{OptionParser} #' instance for guidance. \code{parse_args2} is a wrapper to \code{parse_args} #' setting the options \code{positional_arguments} and \code{convert_hyphens_to_underscores} #' to \code{TRUE}. #' #' @param object An \code{OptionParser} instance. #' @param args A character vector containing command line options to be parsed. #' Default is everything after the Rscript program in the command line. If #' \code{positional_arguments} is not \code{FALSE} then \code{parse_args} will #' look for positional arguments at the end of this vector. #' @param print_help_and_exit Whether \code{parse_args} should call #' \code{print_help} to print out a usage message and exit the program. Default #' is \code{TRUE}. #' @param positional_arguments Number of \emph{positional} arguments. A numeric #' denoting the exact number of supported arguments, or a numeric vector of #' length two denoting the minimum and maximum number of arguments #' (\code{Inf} for no limit). The value \code{TRUE} is equivalent to #' \code{c(0, Inf)}. The default \code{FALSE} is #' supported for backward compatibility only, as it alters #' the format of the return value. #' @param convert_hyphens_to_underscores If the names in the returned list of options #' contains hyphens then convert them to underscores. The default \code{FALSE} is #' supported for backward compatibility reasons as it alters the format of the return value #' @return Returns a list with field \code{options} containing our option values #' as well as another field \code{args} which contains a vector of #' positional arguments. For backward compatibility, if and only if #' \code{positional_arguments} is \code{FALSE}, returns a list containing #' option values. #' @section Acknowledgement: #' A big thanks to Steve Lianoglou for a bug report and patch; #' Juan Carlos \enc{Borrás}{Borras} for a bug report; #' Jim Nikelski for a bug report and patch; #' Ino de Brujin and Benjamin Tyner for a bug report; #' Jonas Zimmermann for bug report; Miroslav Posta for bug reports; #' Stefan Seemayer for bug report and patch; #' Kirill \enc{Müller}{Muller} for patches; Steve Humburg for patch. #' @author Trevor Davis. #' #' @seealso \code{\link{OptionParser}} \code{\link{print_help}} #' @references Python's \code{optparse} library, which inspired this package, #' is described here: \url{https://docs.python.org/3/library/optparse.html} #' @encoding latin1 #' @examples #' # example from vignette #' option_list <- list( #' make_option(c("-v", "--verbose"), action = "store_true", default = TRUE, #' help = "Print extra output [default]"), #' make_option(c("-q", "--quietly"), action = "store_false", #' dest = "verbose", help = "Print little output"), #' make_option(c("-c", "--count"), type = "integer", default = 5, #' help = "Number of random normals to generate [default %default]", #' metavar = "number"), #' make_option("--generator", default = "rnorm", #' help = "Function to generate random deviates [default \"%default\"]"), #' make_option("--mean", default = 0, #' help = "Mean if generator == \"rnorm\" [default %default]"), #' make_option("--sd", default = 1, metavar = "standard deviation", #' help = "Standard deviation if generator == \"rnorm\" [default %default]") #' ) #'parse_args(OptionParser(option_list = option_list), args = c("--sd=3", "--quietly")) #' #'# example from vignette using positional arguments #'option_list2 <- list( #' make_option(c("-n", "--add-numbers"), action = "store_true", default = FALSE, #' help = "Print line number at the beginning of each line [default]") #' ) #'parser <- OptionParser(usage = "%prog [options] file", option_list = option_list2) #' #'parse_args(parser, args = c("--add-numbers", "example.txt"), positional_arguments = TRUE) #' #'parse_args(parser, args = c("--add-numbers", "example.txt"), positional_arguments = TRUE, #' convert_hyphens_to_underscores = TRUE) #' #'parse_args2(parser, args = c("--add-numbers", "example.txt")) #' #' @import getopt #' @importFrom utils tail #' @export parse_args <- function(object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE, positional_arguments = FALSE, convert_hyphens_to_underscores = FALSE) { pal <- should_include_any_args(positional_arguments) include_any_args <- pal$include_any_args positional_arguments <- pal$positional_arguments pal <- parse_positional_args(object, args, positional_arguments) arguments_positional <- pal$arguments_positional args <- pal$args options_list <- parse_options(object, args, convert_hyphens_to_underscores) if (any(grepl("^help$", names(options_list)))) { if (options_list[["help"]] && print_help_and_exit) { print_help(object) if (interactive()) stop("help requested") else quit(status = 0) } } if (length(arguments_positional) < min(positional_arguments)) { stop(sprintf("required at least %g positional arguments, got %g", min(positional_arguments), length(arguments_positional))) } if (length(arguments_positional) > max(positional_arguments)) { stop(sprintf("required at most %g positional arguments, got %g", max(positional_arguments), length(arguments_positional))) } if (include_any_args) { return(list(options = options_list, args = arguments_positional)) } else { return(options_list) } } getopt_options <- function(object, args) { # Convert our option specification into ``getopt`` format n_options <- length(object@options) spec <- matrix(NA, nrow = n_options, ncol = 5) for (ii in seq_along(object@options)) { spec[ii, ] <- .convert_to_getopt(object@options[[ii]]) } if (length(args)) { opt <- try(getopt(spec = spec, opt = args), silent = TRUE) if (class(opt) == "try-error") { if (grepl("redundant short names for flags", opt)) { opt <- paste(opt, "did you forget to set ``add_help_option=FALSE`` in ``OptionParser``") } stop(opt) } } else { opt <- list() } opt } should_include_any_args <- function(positional_arguments) { # pull out positional arguments if ``positional_arguments`` was set to TRUE # or not 0 or c(0, 0) if (!(length(positional_arguments) %in% 1L:2L)) stop("positional_arguments must have length 1 or 2") if (is.logical(positional_arguments)) { if (positional_arguments) { positional_arguments <- c(0, Inf) include_any_args <- TRUE } else { include_any_args <- FALSE } } else if (is.numeric(positional_arguments)) { include_any_args <- TRUE } else { stop("positional_arguments must be logical or numeric") } list(include_any_args = include_any_args, positional_arguments = positional_arguments) } parse_positional_args <- function(object, args, positional_arguments) { arguments_positional <- character(0) if (max(positional_arguments) > 0) { original_arguments <- args args <- NULL is_taken <- FALSE # set to true if optional argument needs to take next argument for (argument in original_arguments) { if (is_taken) { args <- c(args, argument) is_taken <- FALSE } else { if (.is_option_string(argument, object)) { args <- c(args, argument) if (.requires_argument(argument, object)) is_taken <- TRUE } else { arguments_positional <- c(arguments_positional, argument) } } } } list(arguments_positional = arguments_positional, args = args) } parse_options <- function(object, args, convert_hyphens_to_underscores) { opt <- getopt_options(object, args) options_list <- list() for (ii in seq_along(object@options)) { option <- object@options[[ii]] option_value <- opt[[sub("^--", "", option@long_flag)]] if (!is.null(option_value)) { if (option@action == "store_false") { options_list[[option@dest]] <- FALSE } else { options_list[[option@dest]] <- option_value } if (option@action == "callback") { callback_fn <- function(...) { option@callback(option, option@long_flag, option_value, object, ...) # nolint } options_list[[option@dest]] <- do.call(callback_fn, option@callback_args) } } else { if (!is.null(option@default) & is.null(options_list[[option@dest]])) { options_list[[option@dest]] <- option@default } } } if (convert_hyphens_to_underscores) { names(options_list) <- gsub("-", "_", names(options_list)) } options_list } #' @rdname parse_args #' @export parse_args2 <- function(object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE) { parse_args(object, args = args, print_help_and_exit = print_help_and_exit, positional_arguments = TRUE, convert_hyphens_to_underscores = TRUE) } # Tells me whether a string is a valid option .is_option_string <- function(argument, object) { if (.is_long_flag(argument)) { return(TRUE) } else if (.is_short_flag(argument)) { return(TRUE) } else { return(FALSE) } } # Tells me if an option string needs to take an argument .requires_argument <- function(argument, object) { if (.is_long_flag(argument)) { if (grepl("=", argument)) { return(FALSE) } else { for (ii in seq_along(object@options)) { option <- object@options[[ii]] if (option@long_flag == argument) return(.option_needs_argument(option)) } stop("Don't know long flag argument ", argument) } } else { # is a short flag last_flag <- tail(.expand_short_option(argument), 1) for (ii in seq_along(object@options)) { option <- object@options[[ii]] if (!is.na(option@short_flag) && option@short_flag == last_flag) return(.option_needs_argument(option)) } } } # convenience functions that tells if argument is a type of flag and returns all long flag options or short flag options .is_long_flag <- function(argument) return(grepl("^--", argument)) .is_short_flag <- function(argument) return(grepl("^-[^-]", argument)) # .expand_short_option based on function by Jim Nikelski (c) 2011 # He gave me a non-exclusive unlimited license to this code # .expand_short_option("-cde") = c("-c", "-d", "-e") # nolint .expand_short_option <- function(argument) { if (nchar(argument) == 2) { return(argument) } else { argument <- substr(argument, 2, nchar(argument)) # remove leading dash argument <- strsplit(argument, "")[[1]] # split into individual characters argument <- paste("-", argument, sep = "") # add leading dash to each short option return(argument) } } # Converts our representation of options to format getopt can understand .convert_to_getopt <- function(object) { short_flag <- sub("^-", "", object@short_flag) long_flag <- sub("^--", "", object@long_flag) argument <- ifelse(.option_needs_argument(object), 1, 0) type <- ifelse(object@type == "NULL", "logical", object@type) return(c(long_flag, short_flag, argument, type, object@help)) } .option_needs_argument <- function(option) { .option_needs_argument_helper(option@action, option@type) } .option_needs_argument_helper <- function(action, type) { switch(action, store = TRUE, callback = ifelse(type == "NULL", FALSE, TRUE), FALSE) } optparse/R/optparse-package.R0000644000176200001440000000410614117701160015660 0ustar liggesusers#'Command line option parser #' #'Goal is to create an R package of a command line parser inspired by Python's #'\dQuote{optparse} library. #' #'\code{optparse} is primarily intended to be used with #'\dQuote{Rscript}. It facilitates writing \dQuote{#!} shebang scripts that #'accept short and long flags/options. It can also be used from directly, but #'is probably less useful in this context. #' #'See package vignette for a more detailed example. #' #'Notes on naming convention in package: 1. An option is one of the shell-split #'input strings. 2. A flag is a type of option. a flag can be defined as having #'no argument (defined below), a required argument, or an optional argument. 3. #'An argument is a type of option, and is the value associated with a flag. 4. #'A long flag is a type of flag, and begins with the string \dQuote{--}. If the #'long flag has an associated argument, it may be delimited from the long flag #'by either a trailing =, or may be the subsequent option. 5. A short flag is a #'type of flag, and begins with the string \dQuote{-}. If a short flag has an #'associated argument, it is the subsequent option. short flags may be bundled #'together, sharing a single leading \dQuote{"-"}, but only the final short #'flag is able to have a corresponding argument. %%% #' #'@name optparse-package #'@aliases optparse-package optparse #'@docType package #'@author Trevor Davis. #' #'Some documentation and unit tests ported from Allen Day's getopt package. #' #'The documentation for Python's optparse library, which this package is based #'on, is Copyright 1990-2009, Python Software Foundation. #'@seealso \code{\link[getopt]{getopt}} #'@references Python's \code{optparse} library, which this package is based on, #'is described here: \url{https://docs.python.org/3/library/optparse.html} #'@keywords package #'@examples #' #' example_file <- system.file("exec", "example.R", package = "optparse") #' example_file_2 <- system.file("exec", "display_file.R", package = "optparse") #' \dontrun{ #' readLines(example_file) #' readLines(example_file_2) #' } #' NULL optparse/NEWS.md0000644000176200001440000001135514130070545013211 0ustar liggesusersoptparse 1.7.1 ============== * Add a ``formatter`` argument to ``OptionParser()`` for a function to format the usage message (#30). By default uses the new function ``IndentedHelpFormatter()``. `{optparse}` also provides the new function ``TitledHelpFormatter()``. Thanks Ni Huang for suggestion. optparse 1.6.6 ============== * Throws an error for unknown short flags and long flags when ``positional_arguments=TRUE``. Thanks Greg Minshall for bug report (#34). * If the ``callback`` parameter of ``add_option`` / ``make_option`` is not ``NULL`` then the default of ``action`` is now ``"callback"``. Thanks Greg Minshall for suggestion (#35). * Better documentation of ``action=="callback"`` in the man page for ``add_option`` and ``make_option``. Thanks Greg Minshall for bug report (#35). optparse 1.6.4 ============== * Fixes bug in printing help for ``action=="callback"`` when ``metavar==NULL`` (#29). Thanks Ni Huang for bug report. * Throws an error when passed short flags more than one letter long (#32). Thanks Gautier Richard for bug report. optparse 1.6.2 ============== * Fixs a parsing bug when ``action=="callback"`` and ``positional_argument==TRUE`` (#28). Thanks Ni Huang for bug report. optparse 1.6.1 ============== * Improves accuracy of README (#27). Thanks Alex Penson for bug report. optparse 1.6.0 ============== * Supports callback actions (#26). Thanks Gyu Jin Choi for patch. * If ``interactive() == FALSE`` and ``print_help_and_exit == TRUE`` then ``optparse`` will now call ``quit(status=0)`` instead of ``quit(status=1)`` after printing the help message (this matches behaviour of the python package). * Better error message when forgetting to set ``add_help_option=FALSE`` when defining an ``-h`` or ``--help`` flag. Thanks Jeff P. Bruce for bug report. * Increment ``getopt`` requirement so that empty strings are parsed correctly. Thanks Matthew Flickinger for bug report. optparse 1.4.4 ============== * Minor documentation fixes. Thanks J. J. Ramsey and Daeyoung Kim for bug reports. * Fix bug when ``add_help_option`` in ``OptionParser`` set to ``FALSE``. Thanks to Jeff Bruce for bug report. * ``parse_args`` now supports ``convert_hyphens_to_underscores`` argument which converts any hyphens to underscores when returning the list of options * Now includes the convenience function ``parse_args2`` which wraps ``parse_args`` with ``positional_arguments`` set to ``TRUE`` and ``convert_hyphens_to_underscores`` set to ``TRUE``. optparse 1.3.2 ============== * ``optparse`` should no longer give any warnings when ``options(warnPartialMatchArgs=TRUE)``. Thanks Rich FitzJohn for patch. * ``print_help`` no longer throws an error if we have a default argument of length zero. Thanks Benjamin Tyner for bug report. optparse 1.3.0 ============== * ``OptionParser`` and ``OptionParserOption`` S4 classes are now exported. Thanks Peter Humburg for patch. optparse 1.2.0 ============== * Parameter ``positional_arguments`` of function ``parse_args`` now accepts one or two numeric values that denote the minimum and maximum number of supported positional arguments. Thanks Kirill Müller for patch. * If ``interactive() == TRUE`` then ``parse_args`` will no longer ``quit(status=1)`` after printing a help message but will instead throw an error. ``optparse`` will continue to ``quit(status=1)`` after printing a help message for non-interactive Rscripts unless ``print_help_and_exit == FALSE``. * In ``make_option`` argument ``type="numeric"`` automatically cast to ``double``. Previously users might have received an error passing negative numbers if they accidentally specified "numeric" instead of "double". * Bug fixed in printing usage message for options with default value of NA and a help string including "%default". Thanks Stefan Seemayer for bug report and patch. optparse 1.0.2 ============== * Project website moved to https://github.com/trevorld/optparse * We now replace all occurrences of %prog in usage message (including description and epilogue). Previously we would only replace one occurrence and didn't make replacements in description and epilogue. * Fix bug in ``parse_args`` when we have options with no short flag and positional_arguments=TRUE. Thanks Miroslav Posta for bug report. optparse 1.0.0 ============== * Added `description` and `epilogue` arguments to `OptionParser` to allow users to add more information to generated help messages * Slightly alters the generated usage string to match more closely what the Python module does * No longer exports S4 classes that represent OptionParser and OptionParserOption * Now requires package getopt (>= 1.19) which has also been moved to Imports field from Depends field in DESCRIPTION * Now also Suggests stringr package in DESCRIPTION optparse/MD50000644000176200001440000000300314130114742012410 0ustar liggesuserseb723b61539feef013de476e68b5c50a *COPYING de2218f74e891695095a8b313ddd9380 *DESCRIPTION 14ab7fef4ce3043e680ac560d759350c *NAMESPACE b65a9b64f158bc8927f8afe09227cbc5 *NEWS.md 3f1593c0d6d9e967a2f4a9bf0c61729a *R/optparse-package.R 06f4857d9de72bfd8c672327a94fcddf *R/optparse.R 6a45d8a99ed07c7870ccaa76c1019220 *README.md 1b9ce4ffc8bce8c3774ff5f891be347d *build/vignette.rds 815abb80f29beecacb52f37ebe54fdb8 *exec/display_file.R 2a250ed6a5c87a6131cedf19b01ef698 *exec/example.R 9821839a14f1be05c82db873fe70b92c *inst/COPYRIGHTS 8321916b02038ef04c44972c7bc7a359 *inst/doc/optparse.R 8a64473dff672d3f50622f46f76d56eb *inst/doc/optparse.Rrst a8f270a3ec54a384a758e9ac8a370d60 *inst/doc/optparse.html bbdeed33d8414ff294f990fed4dcb960 *man/OptionParser-class.Rd c39b2746993f0a19e49217625ec45431 *man/OptionParser.Rd fc4136a63693bfa2451b072eced1ede3 *man/OptionParserOption-class.Rd b6687ffc092bd126b309a840052c5e5c *man/add_make_option.Rd dfffdcf9ac83bc3e9e85a337bc9d9a99 *man/figures/logo.png c3a3cbe86d2aa11364afe65eedcfd08d *man/figures/logo.svg 6965444760002d29bb25fdaec0992468 *man/formatter.Rd fdb3c5d45cc425300053073362e80688 *man/optparse-package.Rd 3da6a343b7e9a5ca197ce8e0e8f8473a *man/parse_args.Rd 5aca8433b45df4a07ef848b790038504 *man/print_help.Rd 398b710c16889ab67e30dbb3bad87137 *tests/run-all.R db4dd8c665d626beb66a70a7fd5ac1a6 *tests/test_help.R aa33491c5ca831201e373cb8ca1b3ddb *tests/test_help.Rout.save 7f7d22d2082f8e41de682aaa61f86621 *tests/testthat/test-optparse.R 8a64473dff672d3f50622f46f76d56eb *vignettes/optparse.Rrst optparse/inst/0000755000176200001440000000000014130111630013052 5ustar liggesusersoptparse/inst/doc/0000755000176200001440000000000014130111630013617 5ustar liggesusersoptparse/inst/doc/optparse.R0000644000176200001440000000611714130111630015604 0ustar liggesusers## ----echo=FALSE--------------------------------------------------------------- library("knitr") Rscript_executable <- paste(file.path(R.home(), "bin", "Rscript"), "--vanilla") opts_knit$set(root.dir = system.file("exec", package="optparse")) # to access the "Rscript files" opts_chunk$set(comment=NA, echo=FALSE) # setwd(system.file("exec", package="optparse")) # to access the "Rscript files" list_file_command <- "ls" chmod_command <- "chmod ug+x display_file.R example.R" path_command <- "export PATH=$PATH:`pwd`" run_command <- function(string) { suppressWarnings(cat(system(string, intern=TRUE), sep="\n")) } ## ----------------------------------------------------------------------------- run_command(sprintf("%s", list_file_command)) command <- "display_file.R example.R" # to show file ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) ## ----------------------------------------------------------------------------- command <- "example.R --help" # same as system("Rscript example.R -h") ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R" # rely only on defaults ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --mean=10 --sd=10 --count=3" ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --quiet -c 4 --generator=\"runif\"" # same as above but "quiet" ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --silent -m 5" # same as above but "quiet" ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R -c 100 -c 2 -c 1000 -c 7" # same as above but "quiet" ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) ## ----------------------------------------------------------------------------- command <- "display_file.R --help" ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R --add_numbers display_file.R" ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R non_existent_file.txt" ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R" ## ----------------------------------------------------------------------------- run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) optparse/inst/doc/optparse.Rrst0000644000176200001440000001213612253432313016343 0ustar liggesusers.. %\VignetteIndexEntry{optparse Command Line Option Parsing} %\VignetteEngine{knitr} optparse Command Line Option Parsing ==================================== optparse is a command line option parser inspired by Python's "optparse" library. Use this with Rscript to write "#!"-shebang scripts that accept short and long flags/options, generate a usage statement, and set default values for options that are not specified on the command line. .. {r echo=FALSE} .. library("knitr") .. Rscript_executable <- paste(file.path(R.home(), "bin", "Rscript"), "--vanilla") .. opts_knit$set(root.dir = system.file("exec", package="optparse")) # to access the "Rscript files" .. opts_chunk$set(comment=NA, echo=FALSE) .. # setwd(system.file("exec", package="optparse")) # to access the "Rscript files" .. list_file_command <- "ls" .. chmod_command <- "chmod ug+x display_file.R example.R" .. path_command <- "export PATH=$PATH:`pwd`" .. run_command <- function(string) { suppressWarnings(cat(system(string, intern=TRUE), sep="\n")) } .. .. In our working directory we have two example R scripts, named "example.R" and "display\_file.R" illustrating the use of the optparse package. **:r:`paste("bash$", list_file_command)`** .. {r} .. run_command(sprintf("%s", list_file_command)) .. command <- "display_file.R example.R" # to show file .. .. In order for a \*nix system to recognize a "#!"-shebang line you need to mark the file executable with the ``chmod`` command, it also helps to add the directory containing your Rscripts to your path: **:r:`paste("bash$", chmod_command)`** **:r:`paste("bash$", path_command)`** Here is what ``example.R`` contains: **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. .. {r} .. command <- "example.R --help" # same as system("Rscript example.R -h") .. .. By default *optparse* will generate a help message if it encounters ``--help`` or ``-h`` on the command line. Note how ``%default`` in the example program was replaced by the actual default values in the help statement that *optparse* generated. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R" # rely only on defaults .. .. If you specify default values when creating your ``OptionParser`` then *optparse* will use them as expected. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --mean=10 --sd=10 --count=3" .. .. Or you can specify your own values. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --quiet -c 4 --generator=\"runif\"" # same as above but "quiet" .. .. If you remember from the example program that ``--quiet`` had ``action="store_false"`` and ``dest="verbose"``. This means that ``--quiet`` is a switch that turns the ``verbose`` option from its default value of ``TRUE`` to ``FALSE``. Note how the ``verbose`` and ``quiet`` options store their value in the exact same variable. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --silent -m 5" # same as above but "quiet" .. .. If you specify an illegal flag then *optparse* will throw an error. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R -c 100 -c 2 -c 1000 -c 7" # same as above but "quiet" .. .. If you specify the same option multiple times then *optparse* will use the value of the last option specified. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. *optparse* can also recognize positional arguments if ``parse_args`` is given the option ``positional_arguments = c(min_pa, max_pa)`` where ``min_pa`` is the minimum and ``max_pa`` is the maximum number of supported positional arguments. (A single numeric corresponds to ``min_pa == max_pa``, ``TRUE`` is equivalent to ``c(0, Inf)``, and ``FALSE``, the default, is equivalent to ``0``.) Below we give an example program *display_file.R*, which is a program that prints out the contents of a single file (the required positional argument, not an optional argument) and which accepts the normal help option as well as an option to add line numbers to the output. Note that the positional arguments need to be placed *after* the optional arguments. .. {r} .. command <- "display_file.R --help" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R --add_numbers display_file.R" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R non_existent_file.txt" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. optparse/inst/doc/optparse.html0000644000176200001440000002361314130111630016347 0ustar liggesusers

optparse Command Line Option Parsing

optparse is a command line option parser inspired by Python's "optparse" library. Use this with Rscript to write "#!"-shebang scripts that accept short and long flags/options, generate a usage statement, and set default values for options that are not specified on the command line.

In our working directory we have two example R scripts, named "example.R" and "display_file.R" illustrating the use of the optparse package.

bash$ ls

display_file.R
example.R

In order for a *nix system to recognize a "#!"-shebang line you need to mark the file executable with the chmod command, it also helps to add the directory containing your Rscripts to your path:

bash$ chmod ug+x display_file.R example.R

bash$ export PATH=$PATH:`pwd`

Here is what example.R contains:

bash$ display_file.R example.R

#!/usr/bin/env Rscript
# Copyright 2010-2013 Trevor L Davis <trevor.l.davis@gmail.com>
# Copyright 2008 Allen Day
#  
#  This file is free software: you may copy, redistribute and/or modify it  
#  under the terms of the GNU General Public License as published by the  
#  Free Software Foundation, either version 2 of the License, or (at your  
#  option) any later version.  
#  
#  This file is distributed in the hope that it will be useful, but  
#  WITHOUT ANY WARRANTY; without even the implied warranty of  
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  
#  General Public License for more details.  
#  
#  You should have received a copy of the GNU General Public License  
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.  
suppressPackageStartupMessages(library("optparse"))
suppressPackageStartupMessages(library("stats"))

# specify our desired options in a list
# by default OptionParser will add an help option equivalent to 
# make_option(c("-h", "--help"), action="store_true", default=FALSE, 
#               help="Show this help message and exit")
option_list <- list( 
    make_option(c("-v", "--verbose"), action="store_true", default=TRUE,
        help="Print extra output [default]"),
    make_option(c("-q", "--quietly"), action="store_false", 
        dest="verbose", help="Print little output"),
    make_option(c("-c", "--count"), type="integer", default=5, 
        help="Number of random normals to generate [default %default]",
        metavar="number"),
    make_option("--generator", default="rnorm", 
        help = "Function to generate random deviates [default \"%default\"]"),
    make_option("--mean", default=0, 
        help="Mean if generator == \"rnorm\" [default %default]"),
    make_option("--sd", default=1, metavar="standard deviation",
        help="Standard deviation if generator == \"rnorm\" [default %default]")
    )

# get command line options, if help option encountered print help and exit,
# otherwise if options not found on command line then set defaults, 
opt <- parse_args(OptionParser(option_list=option_list))

# print some progress messages to stderr if "quietly" wasn't requested
if ( opt$verbose ) { 
    write("writing some verbose output to standard error...\n", stderr()) 
}

# do some operations based on user input
if( opt$generator == "rnorm") {
    cat(paste(rnorm(opt$count, mean=opt$mean, sd=opt$sd), collapse="\n"))
} else {
    cat(paste(do.call(opt$generator, list(opt$count)), collapse="\n"))
}
cat("\n")

By default optparse will generate a help message if it encounters --help or -h on the command line. Note how %default in the example program was replaced by the actual default values in the help statement that optparse generated.

bash$ example.R --help

Usage: example.R [options]


Options:
    -v, --verbose
        Print extra output [default]

    -q, --quietly
        Print little output

    -c NUMBER, --count=NUMBER
        Number of random normals to generate [default 5]

    --generator=GENERATOR
        Function to generate random deviates [default "rnorm"]

    --mean=MEAN
        Mean if generator == "rnorm" [default 0]

    --sd=STANDARD DEVIATION
        Standard deviation if generator == "rnorm" [default 1]

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

If you specify default values when creating your OptionParser then optparse will use them as expected.

bash$ example.R

writing some verbose output to standard error...

0.972205599600757
-0.358623322310077
0.0847026277675728
0.175739548893117
-1.81032479588441

Or you can specify your own values.

bash$ example.R --mean=10 --sd=10 --count=3

writing some verbose output to standard error...

2.49359293962927
5.77160634887535
6.38001313341107

If you remember from the example program that --quiet had action="store_false" and dest="verbose". This means that --quiet is a switch that turns the verbose option from its default value of TRUE to FALSE. Note how the verbose and quiet options store their value in the exact same variable.

bash$ example.R --quiet -c 4 --generator="runif"

0.62889474327676
0.630497339181602
0.715296199778095
0.471402876311913

If you specify an illegal flag then optparse will throw an error.

bash$ example.R --silent -m 5

Error in getopt_options(object, args) : 
  Error in getopt(spec = spec, opt = args) : long flag "silent" is invalid
Calls: parse_args -> parse_options -> getopt_options
Execution halted

If you specify the same option multiple times then optparse will use the value of the last option specified.

bash$ example.R -c 100 -c 2 -c 1000 -c 7

writing some verbose output to standard error...

-0.39223398826115
-0.598311567887497
0.0374801956874364
-0.293467284650871
-1.33908744572234
1.05352228913011
0.916112771473002

optparse can also recognize positional arguments if parse_args is given the option positional_arguments = c(min_pa, max_pa) where min_pa is the minimum and max_pa is the maximum number of supported positional arguments. (A single numeric corresponds to min_pa == max_pa, TRUE is equivalent to c(0, Inf), and FALSE, the default, is equivalent to 0.) Below we give an example program display_file.R, which is a program that prints out the contents of a single file (the required positional argument, not an optional argument) and which accepts the normal help option as well as an option to add line numbers to the output. Note that the positional arguments need to be placed after the optional arguments.

bash$ display_file.R --help

Usage: display_file.R [options] file


Options:
    -n, --add_numbers
        Print line number at the beginning of each line [default]

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

bash$ display_file.R --add_numbers display_file.R

1 #!/usr/bin/env Rscript
2 # Copyright 2010-2013 Trevor L Davis <trevor.l.davis@gmail.com>
3 # Copyright 2013 Kirill Müller 
4 #  
5 #  This file is free software: you may copy, redistribute and/or modify it  
6 #  under the terms of the GNU General Public License as published by the  
7 #  Free Software Foundation, either version 2 of the License, or (at your  
8 #  option) any later version.  
9 #  
10 #  This file is distributed in the hope that it will be useful, but  
11 #  WITHOUT ANY WARRANTY; without even the implied warranty of  
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  
13 #  General Public License for more details.  
14 #  
15 #  You should have received a copy of the GNU General Public License  
16 #  along with this program.  If not, see <http://www.gnu.org/licenses/>.  
17 suppressPackageStartupMessages(library("optparse"))
18 
19 option_list <- list( 
20     make_option(c("-n", "--add_numbers"), action="store_true", default=FALSE,
21         help="Print line number at the beginning of each line [default]")
22     )
23 parser <- OptionParser(usage = "%prog [options] file", option_list=option_list)
24 
25 arguments <- parse_args(parser, positional_arguments = 1)
26 opt <- arguments$options
27 file <- arguments$args
28 
29 if( file.access(file) == -1) {
30     stop(sprintf("Specified file ( %s ) does not exist", file))
31 } else {
32     file_text <- readLines(file)
33 }
34 
35 if(opt$add_numbers) {
36     cat(paste(1:length(file_text), file_text), sep = "\n")
37 } else {
38     cat(file_text, sep = "\n")
39 }

bash$ display_file.R non_existent_file.txt

Error: Specified file ( non_existent_file.txt ) does not exist
Execution halted

bash$ display_file.R

Error in parse_args(parser, positional_arguments = 1) : 
  required at least 1 positional arguments, got 0
Execution halted
optparse/inst/COPYRIGHTS0000644000176200001440000003144113450721121014501 0ustar liggesusersFormat: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Files: * Copyright: 2010-2019 Trevor L Davis License: GPL-2+ File: exec/example.R Copyright: 2008 Allen Day 2010-2013 Trevor L Davis License: GPL-2+ File: exec/display_file.R Copyright: 2010-2013 Trevor L Davis 2013 Kirill Müller License: GPL-2+ File: NEWS.md Copyright: 2012-2019 Trevor L Davis 2013 Kirill Müller File: inst/tests/test-optparse.R Copyright: 2008 Allen Day 2010-2019 Trevor L Davis 2013 Kirill Müller 2015 Rich FitzJohn 2018 Gyu Jin Choi License: GPL-2+ File: R/optparse-package.R Copyright: 2008 Allen Day 2010-2013 Trevor L Davis License: GPL-2+ File: R/optparse.R Copyright: 1990-2009 Python Software Foundation 2011-2019 Trevor L Davis 2010 Steve Lianoglou 2011 Jim Nikelski 2013 Kirill Müller 2014 Peter Humburg 2015 Rich FitzJohn 2018 Gyu Jin Choi License: GPL-2+ and Python-2.6.2 Comment: The FSF considers recent Python licenses (post Python version 2.1.1) to be GPL-compatible (http://www.gnu.org/licenses/license-list.html#Python). Note that the "Python License" the FSF has on their website (http://directory.fsf.org/wiki?title=License:Python2.0.1) is the full Python license stack which includes the historical modified CNRI and BEOPEN licenses and not merely the PSF License Agreement at the top. In 2001 ago the FSF negotiated with CNRI to change the wording of an earlier Python license (https://www.gnu.org/licenses/license-list.html#PythonOld, http://directory.fsf.org/wiki/License:Python1.6b1) because it had an overly strong "governed in Virginia" clause but later Python license stacks have a version of the CNRI license with a weakened enough clause to satisfy the FSF lawyers as being GPL-compatible. License: GPL-2+ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. . This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. . You should have received a copy of the GNU General Public License along with this package; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA . The full text of the GNU General Public License version 2 can be found in the file COPYING (source) or `R_HOME/share/licenses/GPL-2' (installed). License: Python-2.6.2 PSF LICENSE AGREEMENT FOR PYTHON 2.6.2 . 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 2.6.2 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 2.6.2 alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright © 2001-2009 Python Software Foundation; All Rights Reserved" are retained in Python 2.6.2 alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 2.6.2 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 2.6.2. 4. PSF is making Python 2.6.2 available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.6.2 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.6.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.6.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python 2.6.2, Licensee agrees to be bound by the terms and conditions of this License Agreement. . BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 . BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 . 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee") accessing and otherwise using this software in source or binary form and its associated documentation ("the Software"). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. . CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 . 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013." 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. . ACCEPT . CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 . Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. . Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. . STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.