optparse/0000755000176000001440000000000012317457560012151 5ustar ripleyusersoptparse/COPYING0000755000176000001440000004313312206447600013202 0ustar ripleyusers 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/inst/0000755000176000001440000000000012317447455013130 5ustar ripleyusersoptparse/inst/COPYRIGHTS0000644000176000001440000003121212317447336014543 0ustar ripleyusersFormat: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Files: * Copyright: 2010-2014 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 Copyright: 2012-2013 Trevor L Davis 2013 Kirill Müller File: inst/tests/test-optparse.R Copyright: 2008 Allen Day 2010-2013 Trevor L Davis 2013 Kirill Müller 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 2012-2013 Trevor L Davis 2011 Jim Nikelski 2010 Steve Lianoglou 2013 Kirill Müller 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. optparse/inst/doc/0000755000176000001440000000000012317447455013675 5ustar ripleyusersoptparse/inst/doc/optparse.Rrst0000644000176000001440000001213612317447455016411 0ustar ripleyusers.. %\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.R0000644000176000001440000000606412317447455015663 0ustar ripleyusers ## ----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.pdf0000644000176000001440000001652712317457560016236 0ustar ripleyusers%PDF-1.5 % 1 0 obj << /Type /ObjStm /Length 624 /Filter /FlateDecode /N 20 /First 140 >> stream xUO0_qohgBh;44(0xpyJ.v(;;6uc|/ẁ8( Y$eY% 4́2I@5bޏfQ3$яH3`Kb('D'D!ȫbd8HNL t!!X=D_u}\[˕ 5vָFI;oÉ] Ѫnw`FIM=ИĄ3q@>s;hkVUy;g1Mi6l < jm|wL/> stream xWko6 V0bg0Ki `RZ--zh~dKaY"yymi&4vOygÃv>ư3lq:]W -5L{cmhQ6{] 8nP #)|}6\Haqյg 1W0Vu Mw[FD}X9HO 3jeԆE T8a#X#, %p`-FDXxْAIT  7Z;tAd8!eQD┥GVauXр2vĜ(pw> D]TTl$'`MrX,wؕQB6tqB8‘^|%VF|j UD)`8d\] =`‍DRH(8d'!GGicZ>O5Ef.(SS"rI!DP{Ư7<^ξ/hn PUq;0{o1gͅ4i.*jޢ2R:jGLFVwЫٵ_Pcr7<lAN8찎=h5(AS ՈQR$(NTQZGF0Xn"\,Vwb)$e8A?^G%Z< ϵPZ43plJnz4x.arXpD :P옸ךD) ױaüU$[Yd|GH  }D(ՎNLGaMPIBegm}4/nnM_t:6~V?5LX:R׌"EV>M?\եy']=4f38Լp{5v:3Jh=1nSl$;LTgg :QzvɎXbGK)P(mi@!f3I}zVM/3̛ m8|ɹ L'|w|^UQ>iTITrPjL ?/s${P #gúxb:sf!ȆAk4biOyz/XLqB||5;IH##mIϨQ2>BےQːKgi(Li)u+p*_oNoK'E#x )-[yKw@YB,OvVP\!sdpae ,tj:4# Me%"ϱp +,> stream xVmOHTgyqDJhi/ux5싓81@6<3gփ6~=;KΦprׁۃgO[6~g> =`} 8<Ƞ嫿ЇNW Al0TGcV/Y$5( Âf8F 1~FtND{{7aL?MoY.cNQ z5!<>jI>D7H홾 RzXf,M8`"ME7f3VdrALj}&wU,°x1 sD*h@?bA_8C r%|!BZcQwx$rum,x G$!#ʹq_T&O X! *$>U0(cux TⱤXg \ZB4m#9!&tq )b4t: Y>WjTRc0Ŧ} B6T  aN :jXM0"HM/u}h}ѭAyS_իA7toOwΞ27}rѳ6*"]rlz 4WUt(WK^oc VĦYޛE (9)uwx.LJGFZIޡ9p=Rg)V_tkOtz]OuQd3؆f{Pϋ餖v+f6:`<ߦӛs8<^^דb_GP.;WeQ2'*vez |ݸ Tt]tt9'V,?JJfSAy ;ܱ(N>G2;Vs;2VΘHendstream endobj 24 0 obj << /Length 1366 /Filter /FlateDecode >> stream xWnF}7;@)-o I,DRӯRcQ<Z̝9sm ~}O2̀H#\O./>_^M_"e#ø‘M>H5H)o7`5[E_^0R+ˋOybH{4a(iBd!ڧUϡ,2_/JE] *ΧQɿ0y 7$P"-ӆƶآ3F[L1m)z2#-QJ24G{ۖPObnzn~!s(W.Ig_ób×xY2zQ/}}\.~gn`4\hTNkRy5y#X,THj4TMkǢ[8'bQX{'BnB""a}zìw/2n Xb.rs],i8"ʪn/K77f"N5MnjO]YzF0Y%P>7XCNdњjXuF5ZBU S7eME wÆT8:|o?}}"E~fX)AH?R,IeN1o>#@Eg!>ۨF ||.Ɋ-c=d% 3qFϭ4ZQKB4C%!F!8PJP1n)SO\ni}\vG.n/ab38 xcƱ8BC~t28MZK#Z3gO/t̀:cIL2wv* Wo>epHst  4% caԴ k/v\R7;"^VnD43-34(lv w4H*\#ˆae\V)کS7=LN~$\y8"ᎹB YG8=?K2XDhrDMl12@ڧRK#m"5f"HT\PqQ AO=(Ty[q.$#Q%XӋ2 kd:CA9!攐_\6k#h$,VWw;6|^Ɲv*|dz =gYI:sV'E*S!Ul&I9p!jUxEvJ\hH84ޕ"U0TդMF #G i=S' bC>}u¥5;}`j9O]^3mMwendstream endobj 25 0 obj << /Length 1491 /Filter /FlateDecode >> stream xVmoH^aS#&)8B ^vwס~km/ϼ=;;tkrpA ,tɗOB;oNvq˴zVcNrB/_qFd [ kvO@MQHyd'}•NH#XDi15 2& dH$X H2I,X(K4 m5-׶z4hq%c&I$'RG3 md)jVpq7((vFh@)d$ b1beB)h4ͤ Wy#f ):$#ęCu;.=";{NpXӞ G*^/ΜVƂ9ԉV5?s栢"o2btn}z\BCU?`8@o g/~'A [A8Ĉu>{0?ADv bfh fqG0JZC@W$ǪyYuBlPmE20~qoP#U,8&uG:8XvjEı]ۋn?(< ^M{%g!AF$q%t;V.nRd+U!^L  MǦAH k\ӶvEIT%;(pJ R`h҆oK Ġ=p.Tyux-\6E"hXqvWJ?endstream endobj 26 0 obj << /Length 424 /Filter /FlateDecode >> stream x͓N0GEJu 6lf2[$خ(NJ{ EgC؎g>3_BF~.s]|)0x e4fFts:`.uϧo?,fYtݵ %#b;C/ )wxxTh˓0mwƲMƥ7I|zIр_SahJ9rm0:*z=Os/2B%z=LU]эNot/1f4xxyȵ2VV[k^!1~) ۑTfuS5Wr_aVKutӕUuQZ9"^Wx?rȇqK@S )$TFh#'B/LsGSوVKԸߒ8[p?v(0 6|=.endstream endobj 27 0 obj << /Type /XRef /Length 49 /Filter /FlateDecode /DecodeParms << /Columns 4 /Predictor 12 >> /W [ 1 2 1 ] /Info 13 0 R /Root 12 0 R /Size 28 /ID [<0b923c5f8ba01855041636106e64da2e>] >> stream xcb&F~ c![&]@X BH0}` Dl endstream endobj startxref 7190 %%EOF optparse/exec/0000755000176000001440000000000012253432313013061 5ustar ripleyusersoptparse/exec/example.R0000644000176000001440000000473612206011115014640 0ustar ripleyusers#!/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")) # 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.R0000644000176000001440000000270412253432313015653 0ustar ripleyusers#!/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/tests/0000755000176000001440000000000012310676111013277 5ustar ripleyusersoptparse/tests/run-all.R0000644000176000001440000000005412255507237015005 0ustar ripleyuserslibrary("testthat") test_check("optparse") optparse/tests/testthat/0000755000176000001440000000000012310700103015124 5ustar ripleyusersoptparse/tests/testthat/test-optparse.R0000644000176000001440000003032512253464166020112 0ustar ripleyusers# Copyright 2010-2013 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]") ) 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_that(make_option("badflag"), throws_error()) }) 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(OptionParser(option_list = option_list), 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(OptionParser(option_list = option_list), 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(OptionParser(option_list = option_list), 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", "example.txt"), positional_arguments = TRUE)), sort_list(list(options = list(add_numbers = FALSE, help = FALSE), args = c("-add_numbers", "example.txt")))) expect_that(parse_args(parser, args = c("-add_numbers", "example.txt")), throws_error()) 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 = FALSE, help = FALSE), args = c("-add_numbers", "example.txt")))) 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")) } }) # 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) parse_args(parser, args = c("-m", "-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(OptionParser(option_list = option_list), 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_equal(sort_list(parse_args(OptionParser(option_list = option_list), args = c("-qcde", "10"), positional_arguments = TRUE)), sort_list(list(options = list(sd = 1, help = FALSE, verbose = TRUE, count = 5, mean = 0, generator = "rnorm"), args = c("-qcde", "10")))) expect_equal(sort_list(parse_args(OptionParser(option_list = option_list), 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")))) expect_equal(sort_list(parse_args(OptionParser(option_list = option_list), args = c("CMD", "-qc", "10", "--qcdefg", "--what-what", "bumblebee"), positional_arguments = TRUE)), sort_list(list(options = list(sd = 1, help = FALSE, verbose = FALSE, count = 10, mean = 0, generator = "rnorm"), args = c("CMD", "--qcdefg", "--what-what", "bumblebee")))) }) # 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(OptionParser(option_list = option_list), 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) # 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", epilog="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') }) optparse/NAMESPACE0000644000176000001440000000020112141060064013341 0ustar ripleyusersexport(OptionParser) export(add_option) export(make_option) export(parse_args) export(print_help) import(getopt) import(methods) optparse/NEWS0000644000176000001440000000361112317447263012650 0ustar ripleyusersoptparse 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. ``argparse`` will continue to ``quit(status=1)`` after printing a help message for non-interactive Rscripts unless ``print_help_and_exit == FALSE``. optparse 1.1.0 ============== * 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/R/0000755000176000001440000000000012317444552012347 5ustar ripleyusersoptparse/R/optparse.R0000644000176000001440000005540512253463413014334 0ustar ripleyusers# Copyright (c) 2010-2013 Trevor L. Davis # 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 #' @import methods setClass("OptionParser", representation(usage = "character", options = "list", description="character", epilogue="character")) setClass("OptionParserOption", representation(short_flag="character", long_flag="character", action="character", type="character", dest="character", default="ANY", help="character", metavar="character"),) #' 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 #' @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{http://docs.python.org/library/optparse.html} #' @import getopt #' @export OptionParser <- function(usage = "usage: %prog [options]", option_list=list(), add_help_option=TRUE, prog=NULL, description="", epilogue="") { 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)) } #'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}, 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. #' @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. Default is derived from the long flag #' in \code{opt_str}. #' @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}. #' @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{http://docs.python.org/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("-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="store", type=NULL, dest=NULL, default=NULL, help="", metavar=NULL) { # flags short_flag <- opt_str[grepl("^-[[:alpha:]]", opt_str)] if(length(short_flag)) {} else { short_flag <- as.character(NA) } long_flag <- opt_str[grepl("^--[[:alpha:]]", opt_str)] if(length(long_flag)) {} else {stop("We require a long flag option")} # type if(is.null(type)) { if( action %in% c("store_true", "store_false") ) { type <- "logical" } else { if( action %in% c("store") ) { if (is.null(default)) { type <- "character" } else { type <- typeof(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(action == "store") { metavar <- sub("^--", "", long_flag) } else { metavar <- character(0) } } return(new("OptionParserOption", short_flag=short_flag, long_flag=long_flag, action=action, type=type, dest=dest, default=default, help=help, metavar=metavar)) } #' @rdname add_make_option #' @export add_option <- function(object, opt_str, action="store", type=NULL, dest=NULL, default=NULL, help="", metavar=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) 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{http://docs.python.org/library/optparse.html} #' @export print_help <- 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@action == "store" ) { cat(" ", toupper(option@metavar), sep="") } cat(", ") } if(!is.null(option@long_flag)) { cat(option@long_flag) if( option@action == "store" ) { 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(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. #' #' @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. #' @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. #' @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{http://docs.python.org/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) #' #' @import getopt #' @export parse_args <- function(object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE, positional_arguments = FALSE) { n_options <- length( object@options ) # Convert our option specification into ``getopt`` format spec <- matrix(NA, nrow = n_options, ncol = 5) for (ii in seq(along = object@options)) { spec[ii, ] <- .convert_to_getopt( object@options[[ii]] ) } # 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") } arguments_positional <- character(0) if(max(positional_arguments) > 0) { os_and_n_arg <- .get_option_strings_and_n_arguments(object) 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) } } } } options_list <- list() if(length(args)) { opt <- getopt(spec=spec, opt=args) } else { opt <- 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 } } else { if( !is.null(option@default) & is.null(options_list[[option@dest]]) ) { options_list[[option@dest]] <- option@default } } } if(options_list[["help"]] & print_help_and_exit) { print_help(object) if(interactive()) stop("help requested") else quit(status=1) } 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) } } # Tells me whether a string is a valid option .is_option_string <- function(argument, object) { if(.is_long_flag(argument)) { if(grepl("=", argument)) { argument <- sub("(.*?)=.*", "\\1", argument) } return(argument %in% .get_long_options(object)) } else if(.is_short_flag(argument)) { return(all(.expand_short_option(argument) %in% .get_short_options(object))) } 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@action == "store") } } } 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@action == "store") } } } # 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)) } .get_long_options <- function(object) { long_options <- vector("character") for(ii in seq(along = object@options)) { long_options <- c(long_options, object@options[[ii]]@long_flag) } return(long_options) } .get_short_options <- function(object) { short_options <- vector("character") for(ii in seq(along = object@options)) { short_options <- c(short_options, object@options[[ii]]@short_flag) } return(short_options) } # .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") .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) } } # Returns a list with a field of option names and a field of number arguments option names take .get_option_strings_and_n_arguments <- function(object) { option_strings <- vector("character") n_arguments <- vector("numeric") for (ii in seq(along = object@options)) { option <- object@options[[ii]] option_strings <- c(option_strings, option@short_flag) option_strings <- c(option_strings, option@long_flag) if (option@action == "store") { n_arguments <- c(n_arguments, 1, 1) } else { n_arguments <- c(n_arguments, 0, 0) } } return(list(option_strings = option_strings, n_arguments = n_arguments)) } # 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) if( object@action %in% c("store_true", "store_false") ) { argument <- 0 } else { argument <- 1 } return( c( long_flag, short_flag, argument, object@type, object@help) ) } optparse/R/optparse-package.R0000644000176000001440000000410312141060064015701 0ustar ripleyusers#'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{http://docs.python.org/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/vignettes/0000755000176000001440000000000012317447455014163 5ustar ripleyusersoptparse/vignettes/optparse.Rrst0000644000176000001440000001213612253432313016661 0ustar ripleyusers.. %\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/MD50000644000176000001440000000210412317457560012456 0ustar ripleyuserseb723b61539feef013de476e68b5c50a *COPYING 7ab179cd119005b61e702de922d56447 *DESCRIPTION 8f47d5f3df9541f1a5b4b2df3285f9fc *NAMESPACE faca7bd3a454027e0dfba7473e90f0e6 *NEWS 52e3196bac3d6fa2c056308a33b6ed82 *R/optparse-package.R 53d62278895ed4d240e8e4de65114810 *R/optparse.R ee0aaf727f86463ca08cb60e94fd239e *build/vignette.rds 1208f601f23f90cd50aeaf3834b0e6d2 *exec/display_file.R abf8fc3b9540918b224443fd9dab9f2f *exec/example.R 86a63a46c438b91c99efe9ef34338d24 *inst/COPYRIGHTS 872b3bab42b658203ff991055a1abf4c *inst/doc/optparse.R 8a64473dff672d3f50622f46f76d56eb *inst/doc/optparse.Rrst 1ae73a629c23e6e316dfeb50c85ebd9f *inst/doc/optparse.pdf 29d58f0ccd82aff03269a1fba948e098 *man/OptionParser.Rd 4df6b1faed7a47a24b2cbced9f571b80 *man/add_make_option.Rd 2b3bf197603679568aa52c43f62d980e *man/optparse-package.Rd a28846163c305c301efff514a6c92985 *man/parse_args.Rd 39d2fd0747577655d29e22f099848fb0 *man/print_help.Rd 398b710c16889ab67e30dbb3bad87137 *tests/run-all.R 746f7461e81411b7b6d15fd7803d515f *tests/testthat/test-optparse.R 8a64473dff672d3f50622f46f76d56eb *vignettes/optparse.Rrst optparse/build/0000755000176000001440000000000012317447455013252 5ustar ripleyusersoptparse/build/vignette.rds0000644000176000001440000000033412317447455015611 0ustar ripleyusersmQ 0?YJB k_" .9cۘ'ώlvB6r,N߀[E>Z8W6❨k |`LpЬ( ,4fsIMCLVgHV{zk537pܔUt{bz8Y3ԟ+aw"hPMR E"optparse/DESCRIPTION0000644000176000001440000000202612317457560013657 0ustar ripleyusersEncoding: UTF-8 Package: optparse Type: Package Title: Command line option parser. Version: 1.2.0 Author: Trevor L Davis. Some documentation and examples ported from Allen Day's getopt package. Some documentation from the optparse Python module by the Python Software Foundation. Contributions from Steve Lianoglou, Jim Nikelski, and Kirill Müller. Maintainer: Trevor L Davis 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/optparse BugReports: https://github.com/trevorld/optparse/issues LazyLoad: yes Depends: R (>= 2.9.0) Imports: methods, getopt (>= 1.19) Suggests: knitr, stringr, testthat VignetteBuilder: knitr Collate: 'optparse-package.R' 'optparse.R' Packaged: 2014-04-04 06:20:29 UTC; trevorld NeedsCompilation: no Repository: CRAN Date/Publication: 2014-04-04 09:29:52 optparse/man/0000755000176000001440000000000012253432313012710 5ustar ripleyusersoptparse/man/add_make_option.Rd0000644000176000001440000000775712210023251016322 0ustar ripleyusers\name{make_option} \alias{add_option} \alias{make_option} \title{Functions to enable our OptionParser to recognize specific command line options.} \usage{ make_option(opt_str, action = "store", type = NULL, dest = NULL, default = NULL, help = "", metavar = NULL) add_option(object, opt_str, action = "store", type = NULL, dest = NULL, default = NULL, help = "", metavar = NULL) } \arguments{ \item{object}{An instance of the \code{OptionParser} class} \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}, 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{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. Default is derived from the long flag in \code{opt_str}.} \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}.} } \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("-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]") } \author{ Trevor Davis. } \references{ Python's \code{optparse} library, which inspires this package, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{\link{parse_args}} \code{\link{OptionParser}} } optparse/man/print_help.Rd0000644000176000001440000000132012141060064015333 0ustar ripleyusers\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. } \author{ Trevor Davis. } \references{ Python's \code{optparse} library, which inspired this package, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{{parse_args}} \code{{OptionParser}} } optparse/man/OptionParser.Rd0000644000176000001440000000367412141060064015632 0ustar ripleyusers\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 = "") } \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} } \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. } \author{ Trevor Davis. } \references{ Python's \code{optparse} library, which inspired this package, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{\link{parse_args}} \code{\link{make_option}} \code{\link{add_option}} } optparse/man/optparse-package.Rd0000644000176000001440000000412012141060064016416 0ustar ripleyusers\docType{package} \name{optparse-package} \alias{optparse} \alias{optparse-package} \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) } } \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. } \references{ Python's \code{optparse} library, which this package is based on, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{\link[getopt]{getopt}} } \keyword{package} optparse/man/parse_args.Rd0000644000176000001440000000712712253432313015334 0ustar ripleyusers\encoding{latin1} \name{parse_args} \alias{parse_args} \title{Parse command line options.} \usage{ parse_args(object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE, positional_arguments = FALSE) } \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.} } \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. } \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. } \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) } \author{ Trevor Davis. } \references{ Python's \code{optparse} library, which inspired this package, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{\link{OptionParser}} \code{\link{print_help}} }