optparse/0000755000176200001440000000000013133505232012104 5ustar liggesusersoptparse/COPYING0000755000176200001440000004313312206447600013152 0ustar liggesusers GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. optparse/inst/0000755000176200001440000000000013133277714013074 5ustar liggesusersoptparse/inst/COPYRIGHTS0000644000176200001440000003134413117547524014520 0ustar liggesusersFormat: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Files: * Copyright: 2010-2017 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 2015 Rich FitzJohn License: GPL-2+ File: R/optparse-package.R Copyright: 2008 Allen Day 2010-2013 Trevor L Davis License: GPL-2+ File: R/optparse.R Copyright: 1990-2009 Python Software Foundation 2011-2017 Trevor L Davis 2010 Steve Lianoglou 2011 Jim Nikelski 2013 Kirill Müller 2014 Peter Humburg 2015 Rich FitzJohn 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/0000755000176200001440000000000013133277714013641 5ustar liggesusersoptparse/inst/doc/optparse.Rrst0000644000176200001440000001213613133277714016355 0ustar liggesusers.. %\VignetteIndexEntry{optparse Command Line Option Parsing} %\VignetteEngine{knitr} optparse Command Line Option Parsing ==================================== optparse is a command line option parser inspired by Python's "optparse" library. Use this with Rscript to write "#!"-shebang scripts that accept short and long flags/options, generate a usage statement, and set default values for options that are not specified on the command line. .. {r echo=FALSE} .. library("knitr") .. Rscript_executable <- paste(file.path(R.home(), "bin", "Rscript"), "--vanilla") .. opts_knit$set(root.dir = system.file("exec", package="optparse")) # to access the "Rscript files" .. opts_chunk$set(comment=NA, echo=FALSE) .. # setwd(system.file("exec", package="optparse")) # to access the "Rscript files" .. list_file_command <- "ls" .. chmod_command <- "chmod ug+x display_file.R example.R" .. path_command <- "export PATH=$PATH:`pwd`" .. run_command <- function(string) { suppressWarnings(cat(system(string, intern=TRUE), sep="\n")) } .. .. In our working directory we have two example R scripts, named "example.R" and "display\_file.R" illustrating the use of the optparse package. **:r:`paste("bash$", list_file_command)`** .. {r} .. run_command(sprintf("%s", list_file_command)) .. command <- "display_file.R example.R" # to show file .. .. In order for a \*nix system to recognize a "#!"-shebang line you need to mark the file executable with the ``chmod`` command, it also helps to add the directory containing your Rscripts to your path: **:r:`paste("bash$", chmod_command)`** **:r:`paste("bash$", path_command)`** Here is what ``example.R`` contains: **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. .. {r} .. command <- "example.R --help" # same as system("Rscript example.R -h") .. .. By default *optparse* will generate a help message if it encounters ``--help`` or ``-h`` on the command line. Note how ``%default`` in the example program was replaced by the actual default values in the help statement that *optparse* generated. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R" # rely only on defaults .. .. If you specify default values when creating your ``OptionParser`` then *optparse* will use them as expected. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --mean=10 --sd=10 --count=3" .. .. Or you can specify your own values. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --quiet -c 4 --generator=\"runif\"" # same as above but "quiet" .. .. If you remember from the example program that ``--quiet`` had ``action="store_false"`` and ``dest="verbose"``. This means that ``--quiet`` is a switch that turns the ``verbose`` option from its default value of ``TRUE`` to ``FALSE``. Note how the ``verbose`` and ``quiet`` options store their value in the exact same variable. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --silent -m 5" # same as above but "quiet" .. .. If you specify an illegal flag then *optparse* will throw an error. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R -c 100 -c 2 -c 1000 -c 7" # same as above but "quiet" .. .. If you specify the same option multiple times then *optparse* will use the value of the last option specified. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. *optparse* can also recognize positional arguments if ``parse_args`` is given the option ``positional_arguments = c(min_pa, max_pa)`` where ``min_pa`` is the minimum and ``max_pa`` is the maximum number of supported positional arguments. (A single numeric corresponds to ``min_pa == max_pa``, ``TRUE`` is equivalent to ``c(0, Inf)``, and ``FALSE``, the default, is equivalent to ``0``.) Below we give an example program *display_file.R*, which is a program that prints out the contents of a single file (the required positional argument, not an optional argument) and which accepts the normal help option as well as an option to add line numbers to the output. Note that the positional arguments need to be placed *after* the optional arguments. .. {r} .. command <- "display_file.R --help" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R --add_numbers display_file.R" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R non_existent_file.txt" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. optparse/inst/doc/optparse.R0000644000176200001440000000604413133277714015625 0ustar liggesusers## ----echo=FALSE---------------------------------------------------------- library("knitr") Rscript_executable <- paste(file.path(R.home(), "bin", "Rscript"), "--vanilla") opts_knit$set(root.dir = system.file("exec", package="optparse")) # to access the "Rscript files" opts_chunk$set(comment=NA, echo=FALSE) # setwd(system.file("exec", package="optparse")) # to access the "Rscript files" list_file_command <- "ls" chmod_command <- "chmod ug+x display_file.R example.R" path_command <- "export PATH=$PATH:`pwd`" run_command <- function(string) { suppressWarnings(cat(system(string, intern=TRUE), sep="\n")) } ## ------------------------------------------------------------------------ run_command(sprintf("%s", list_file_command)) command <- "display_file.R example.R" # to show file ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) ## ------------------------------------------------------------------------ command <- "example.R --help" # same as system("Rscript example.R -h") ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R" # rely only on defaults ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --mean=10 --sd=10 --count=3" ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --quiet -c 4 --generator=\"runif\"" # same as above but "quiet" ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R --silent -m 5" # same as above but "quiet" ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "example.R -c 100 -c 2 -c 1000 -c 7" # same as above but "quiet" ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) ## ------------------------------------------------------------------------ command <- "display_file.R --help" ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R --add_numbers display_file.R" ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R non_existent_file.txt" ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) command <- "display_file.R" ## ------------------------------------------------------------------------ run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) optparse/inst/doc/optparse.html0000644000176200001440000002363013133277714016370 0ustar liggesusers

optparse Command Line Option Parsing

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

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

bash$ ls

display_file.R
example.R

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

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

bash$ export PATH=$PATH:pwd

Here is what example.R contains:

bash$ display_file.R example.R

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

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

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

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

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

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

bash$ example.R --help

Usage: example.R [options]


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

    -q, --quietly
        Print little output

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

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

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

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

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

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

bash$ example.R

writing some verbose output to standard error...

1.49626496576745
-0.430133968033571
0.412183647327778
-0.0446135231106203
0.0332484143153748

Or you can specify your own values.

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

writing some verbose output to standard error...

11.6458476431069
5.72555072552593
11.2994544799871

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

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

0.0652185005601496
0.263430899009109
0.397433762671426
0.582770691253245

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

bash$ example.R --silent -m 5

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

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

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

writing some verbose output to standard error...

-0.0502636939925738
-1.20953394405362
1.46327954003337
1.43860488309639
1.26968788684086
1.51600057753648
-0.763034718503095

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

bash$ display_file.R --help

Usage: display_file.R [options] file


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

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

bash$ display_file.R --add_numbers display_file.R

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

bash$ display_file.R non_existent_file.txt

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

bash$ display_file.R

Error in parse_args(parser, positional_arguments = 1) : 
  required at least 1 positional arguments, got 0
Execution halted
optparse/exec/0000755000176200001440000000000012603573607013044 5ustar liggesusersoptparse/exec/example.R0000644000176200001440000000501712420264646014622 0ustar liggesusers#!/usr/bin/env Rscript # Copyright 2010-2013 Trevor L Davis # Copyright 2008 Allen Day # # This file is free software: you may copy, redistribute and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 2 of the License, or (at your # option) any later version. # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . suppressPackageStartupMessages(library("optparse")) suppressPackageStartupMessages(library("stats")) # specify our desired options in a list # by default OptionParser will add an help option equivalent to # make_option(c("-h", "--help"), action="store_true", default=FALSE, # help="Show this help message and exit") option_list <- list( make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]"), make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output"), make_option(c("-c", "--count"), type="integer", default=5, help="Number of random normals to generate [default %default]", metavar="number"), make_option("--generator", default="rnorm", help = "Function to generate random deviates [default \"%default\"]"), make_option("--mean", default=0, help="Mean if generator == \"rnorm\" [default %default]"), make_option("--sd", default=1, metavar="standard deviation", help="Standard deviation if generator == \"rnorm\" [default %default]") ) # get command line options, if help option encountered print help and exit, # otherwise if options not found on command line then set defaults, opt <- parse_args(OptionParser(option_list=option_list)) # print some progress messages to stderr if "quietly" wasn't requested if ( opt$verbose ) { write("writing some verbose output to standard error...\n", stderr()) } # do some operations based on user input if( opt$generator == "rnorm") { cat(paste(rnorm(opt$count, mean=opt$mean, sd=opt$sd), collapse="\n")) } else { cat(paste(do.call(opt$generator, list(opt$count)), collapse="\n")) } cat("\n") optparse/exec/display_file.R0000644000176200001440000000270412253432313015623 0ustar liggesusers#!/usr/bin/env Rscript # Copyright 2010-2013 Trevor L Davis # Copyright 2013 Kirill Müller # # This file is free software: you may copy, redistribute and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 2 of the License, or (at your # option) any later version. # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . suppressPackageStartupMessages(library("optparse")) option_list <- list( make_option(c("-n", "--add_numbers"), action="store_true", default=FALSE, help="Print line number at the beginning of each line [default]") ) parser <- OptionParser(usage = "%prog [options] file", option_list=option_list) arguments <- parse_args(parser, positional_arguments = 1) opt <- arguments$options file <- arguments$args if( file.access(file) == -1) { stop(sprintf("Specified file ( %s ) does not exist", file)) } else { file_text <- readLines(file) } if(opt$add_numbers) { cat(paste(1:length(file_text), file_text), sep = "\n") } else { cat(file_text, sep = "\n") } optparse/tests/0000755000176200001440000000000012536145337013262 5ustar liggesusersoptparse/tests/run-all.R0000644000176200001440000000005412536077777014772 0ustar liggesuserslibrary("testthat") test_check("optparse") optparse/tests/testthat/0000755000176200001440000000000013067512052015112 5ustar liggesusersoptparse/tests/testthat/test-optparse.R0000644000176200001440000003604013067511716020060 0ustar liggesusers# Copyright 2010-2015 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_equal(make_option("--filename")@type, "character") expect_that(make_option("badflag"), throws_error()) }) get_long_flags <- function(parser) { sort(sapply(parser@options, function(x) { x@long_flag })) } context("Test add_option") test_that("add_option works as expected", { parser1 <- OptionParser(option_list = list(make_option("--generator"), make_option("--count"))) parser2 <- OptionParser() parser2 <- add_option(parser2, "--generator") parser2 <- add_option(parser2, "--count") expect_equal(get_long_flags(parser1), get_long_flags(parser2)) }) context("Testing parse_args") test_that("parse_args works as expected", { # option_list took outside test_that option_list2 <- list( make_option(c("-n", "--add-numbers"), action="store_true", default=FALSE, help="Print line number at the beginning of each line [default]") ) parser <- OptionParser(usage = "\\%prog [options] file", option_list=option_list2) expect_equal(sort_list(parse_args(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"), positional_arguments = TRUE, convert_hyphens_to_underscores = TRUE)), sort_list(list(options = list(add_numbers = TRUE, help = FALSE), args = character(0)))) expect_equal(sort_list(parse_args2(parser, args = c("--add-numbers"))), sort_list(list(options = list(add_numbers = TRUE, help = FALSE), args = character(0)))) expect_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", epilogue="epilog test %prog %prog", description="description %prog test %prog", prog="unit_test.r") expect_output(print_help(parser), 'Usage:.*unit_test.r.*unit_test.r') expect_output(print_help(parser), 'description unit_test.r test unit_test.r') expect_output(print_help(parser), 'epilog test unit_test.r unit_test.r') }) # Bug found by Benjamin Tyner test_that("Can set zero length default options", { option_list_neg <- list( make_option(c("-m", "--mean"), default=numeric(0), type="numeric", help = "Default %default") ) parser <- OptionParser(usage = "\\%prog [options] file", option_list=option_list_neg) expect_equal(sort_list( parse_args(parser, args = c("-m", "-5.0"))) , sort_list(list(mean=-5, help=FALSE))) expect_equal(sort_list( parse_args(parser)) , sort_list(list(mean=numeric(0), help=FALSE))) expect_output(print_help(parser), "Default double") }) # # Bug found by Rich FitzJohn # oo <- options() # on.exit(options(oo)) # options(warnPartialMatchArgs=TRUE) # test_that("Avoid partial matching of arguments", { # expect_that(seq(along=1:10), gives_warning("partial argument match")) # expect_that(seq_along(1:10), not(gives_warning())) # expect_that(parse_args(args=c("-h", "foo"), parser, positional_arguments=TRUE, print_help_and_exit=FALSE), # not(gives_warning())) # expect_that(print_help(OptionParser()), not(gives_warning())) # }) # # Use h flag for non-help (Reported by Jeff Bruce) context("Use h option for non-help") test_that("Use h option for non-help", { option_list_neg <- list( make_option(c("-h", "--mean"), default=0.0) ) parser <- OptionParser(usage = "\\%prog [options] file", option_list=option_list_neg) expect_that(parse_args(parser, args = c("-h", "-5.0")), throws_error()) option_list_neg <- list( make_option(c("-h", "--mean"), default=0.0) ) parser <- OptionParser(usage = "\\%prog [options] file", option_list=option_list_neg, add_help_option=FALSE) args <- parse_args(parser, args = c("-h", "-5.0")) expect_equal(args, list(mean = -5.0)) }) optparse/NAMESPACE0000644000176200001440000000046313026074412013330 0ustar liggesusers# Generated by roxygen2: do not edit by hand export(OptionParser) export(OptionParserOption) export(add_option) export(make_option) export(parse_args) export(parse_args2) export(print_help) exportClasses(OptionParser) exportClasses(OptionParserOption) import(getopt) import(methods) importFrom(utils,tail) optparse/NEWS0000644000176200001440000000554513117550033012615 0ustar liggesusersoptparse 1.4.4 ============== * Minor documentation fixes. Thanks jjramsey and Daeyoung Kim for bug reports. optparse 1.4.1 ============== * Fix bug when ``add_help_option`` in ``OptionParser`` set to ``FALSE``. Thanks to Jeff Bruce for bug report. optparse 1.4.0 ============== * parse_args now supports convert_hyphens_to_underscores argument which converts any hyphens to underscores when returning the list of options * Now includes the convenience function parse_args2 which wraps parse_args with positional_arguments set to TRUE and convert_hyphens_to_underscores set to TRUE. optparse 1.3.1 ============== * optparse should no longer give any warnings when options(warnPartialMatchArgs=TRUE). Thanks Rich FitzJohn for patch. * print_help no longer throws an error if we have a default argument of length zero. Thanks Benjamin Tyner for bug report. optparse 1.3.0 ============== * OptionParser and OptionParserOption are now exported. Thanks Peter Humburg for patch. optparse 1.2.0 ============== * Parameter ``positional_arguments`` of function ``parse_args`` now accepts one or two numeric values that denote the minimum and maximum number of supported positional arguments. Thanks Kirill Müller for patch. * If ``interactive() == TRUE`` then ``parse_args`` will no longer ``quit(status=1)`` after printing a help message but will instead throw an error. ``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/0000755000176200001440000000000013125743363012317 5ustar liggesusersoptparse/R/optparse.R0000644000176200001440000006614513117547335014315 0ustar liggesusers# Copyright (c) 2010-2015 Trevor L. Davis # Copyright (c) 2015 Rick FitzJohn https://github.com/richfitz # Copyright (c) 2013 Kirill Müller https://github.com/krlmlr # Copyright (c) 2011 Jim Nikelski # Copyright (c) 2010 Steve Lianoglou # # This file is free software: you may copy, redistribute and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 2 of the License, or (at your # option) any later version. # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # This file incorporates work from the optparse module in Python 2.6.2. # # Copyright (c) 1990-2009 Python Software Foundation; All Rights Reserved # # See (inst/)COPYRIGHTS or http://docs.python.org/2/license.html for the full # Python (GPL-compatible) license stack. # # As mentioned above, this file incorporates some patches by Steve Lianoglou (c) 2010 # He explicitly gave me a non-exclusive unlimited license to code in his patches #' Option Parser #' #' @slot usage The program usage message that will printed out if #' \code{parse_args} finds a help option, \code{\%prog} is substituted with the #' value of the \code{prog} argument. #' @slot options A list of of \code{OptionParserOption} instances that will #' define how \code{parse_args} reacts to command line options. #' \code{OptionParserOption} instances are usually created by \code{make_option} #' and can also be added to an existing \code{OptionParser} instance via the #' \code{add_option} function. #' @slot description Additional text for \code{print_help} to print out between #' usage statement and options statement #' @slot epilogue Additional text for \code{print_help} to print out after #' the options statement #' @author Trevor Davis. #' @seealso \code{\link{OptionParserOption}} #' @import methods #' @exportClass OptionParser setClass("OptionParser", representation(usage = "character", options = "list", description="character", epilogue="character")) #' Class to hold information about command-line options #' #' @slot short_flag String of the desired short flag #' comprised of the \dQuote{-} followed by a letter. #' @slot long_flag String of the desired long flag comprised of \dQuote{--} #' followed by a letter and then a sequence of alphanumeric characters. #' @slot action A character string that describes the action \code{optparse} #' should take when it encounters an option, either \dQuote{store}, #' \dQuote{store_true}, or \dQuote{store_false}. The default is \dQuote{store} #' which signifies that \code{optparse} should store the specified following #' value if the option is found on the command string. \dQuote{store_true} #' stores \code{TRUE} if the option is found and \dQuote{store_false} stores #' \code{FALSE} if the option is found. #' @slot type A character string that describes specifies which data type #' should be stored, either \dQuote{logical}, \dQuote{integer}, \dQuote{double}, #' \dQuote{complex}, or \dQuote{character}. Default is \dQuote{logical} if #' \code{action \%in\% c("store_true", store_false)}, \code{typeof(default)} if #' \code{action == "store"} and default is not \code{NULL} and #' \dQuote{character} if \code{action == "store"} and default is \code{NULL}. #' \dQuote{numeric} will be converted to \dQuote{double}. #' @slot dest A character string that specifies what field in the list returned #' by \code{parse_args} should \code{optparse} store option values. Default is #' derived from the long flag in \code{opt_str}. #' @slot default The default value \code{optparse} should use if it does not #' find the option on the command line. #' @slot help A character string describing the option to be used by #' \code{print_help} in generating a usage message. \code{\%default} will be #' substituted by the value of \code{default}. #' @slot metavar A character string that stands in for the option argument when #' printing help text. Default is the value of \code{dest}. #' @seealso \code{\link{make_option}} #' @exportClass OptionParserOption #' @export OptionParserOption OptionParserOption <- 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. #' @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("-q", "--quietly"), action="store_false", #' dest="verbose", help="Print little output") #' make_option(c("-c", "--count"), type="integer", default=5, #' help="Number of random normals to generate [default %default]", #' metavar="number") #' make_option("--generator", default="rnorm", #' help = "Function to generate random deviates [default \"%default\"]") #' make_option("--mean", default=0, #' help="Mean if generator == \"rnorm\" [default %default]") #' make_option("--sd", default=1, metavar="standard deviation", #' help="Standard deviation if generator == \"rnorm\" [default %default]") #' #' @export make_option <- function(opt_str, action="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(!length(default)) { default_str <- paste0(typeof(default), "(0)") } else if(is.na(default)) { default_str <- "NA" } else { default_str <- as.character(default) } } #' Parse command line options. #' #' \code{parse_args} parses command line options using an \code{OptionParser} #' instance for guidance. \code{parse_args2} is a wrapper to \code{parse_args} #' setting the options \code{positional_arguments} and \code{convert_hyphens_to_underscores} #' to \code{TRUE}. #' #' @param object An \code{OptionParser} instance. #' @param args A character vector containing command line options to be parsed. #' Default is everything after the Rscript program in the command line. If #' \code{positional_arguments} is not \code{FALSE} then \code{parse_args} will #' look for positional arguments at the end of this vector. #' @param print_help_and_exit Whether \code{parse_args} should call #' \code{print_help} to print out a usage message and exit the program. Default #' is \code{TRUE}. #' @param positional_arguments Number of \emph{positional} arguments. A numeric #' denoting the exact number of supported arguments, or a numeric vector of #' length two denoting the minimum and maximum number of arguments #' (\code{Inf} for no limit). The value \code{TRUE} is equivalent to #' \code{c(0, Inf)}. The default \code{FALSE} is #' supported for backward compatibility only, as it alters #' the format of the return value. #' @param convert_hyphens_to_underscores If the names in the returned list of options #' contains hyphens then convert them to underscores. The default \code{FALSE} is #' supported for backward compatibility reasons as it alters the format of the return value #' @return Returns a list with field \code{options} containing our option values #' as well as another field \code{args} which contains a vector of #' positional arguments. For backward compatibility, if and only if #' \code{positional_arguments} is \code{FALSE}, returns a list containing #' option values. #' @section Acknowledgement: #' A big thanks to Steve Lianoglou for a bug report and patch; #' Juan Carlos \enc{Borrás}{Borras} for a bug report; #' Jim Nikelski for a bug report and patch; #' Ino de Brujin and Benjamin Tyner for a bug report; #' Jonas Zimmermann for bug report; Miroslav Posta for bug reports; #' Stefan Seemayer for bug report and patch; #' Kirill \enc{Müller}{Muller} for patches; Steve Humburg for patch. #' @author Trevor Davis. #' #' @seealso \code{\link{OptionParser}} \code{\link{print_help}} #' @references Python's \code{optparse} library, which inspired this package, #' is described here: \url{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, #' convert_hyphens_to_underscores = TRUE) #' #'parse_args2(parser, args = c("--add-numbers", "example.txt")) #' #' @import getopt #' @importFrom utils tail #' @export parse_args <- function(object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE, positional_arguments = FALSE, convert_hyphens_to_underscores = FALSE) { 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 (convert_hyphens_to_underscores) { names(options_list) <- gsub("-", "_", names(options_list)) } if (any(grepl("^help$", names(options_list)))) { if(options_list[["help"]] & print_help_and_exit) { print_help(object) if(interactive()) stop("help requested") else quit(status=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) } } #' @rdname parse_args #' @export parse_args2 <- function(object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE) { parse_args(object, args = args, print_help_and_exit = print_help_and_exit, positional_arguments = TRUE, convert_hyphens_to_underscores = TRUE) } # Tells me whether a string is a valid option .is_option_string <- function(argument, object) { if(.is_long_flag(argument)) { 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.R0000644000176200001440000000410312141060064015651 0ustar liggesusers#'Command line option parser #' #'Goal is to create an R package of a command line parser inspired by Python's #'\dQuote{optparse} library. #' #'\code{optparse} is primarily intended to be used with #'\dQuote{Rscript}. It facilitates writing \dQuote{#!} shebang scripts that #'accept short and long flags/options. It can also be used from directly, but #'is probably less useful in this context. #' #'See package vignette for a more detailed example. #' #'Notes on naming convention in package: 1. An option is one of the shell-split #'input strings. 2. A flag is a type of option. a flag can be defined as having #'no argument (defined below), a required argument, or an optional argument. 3. #'An argument is a type of option, and is the value associated with a flag. 4. #'A long flag is a type of flag, and begins with the string \dQuote{--}. If the #'long flag has an associated argument, it may be delimited from the long flag #'by either a trailing =, or may be the subsequent option. 5. A short flag is a #'type of flag, and begins with the string \dQuote{-}. If a short flag has an #'associated argument, it is the subsequent option. short flags may be bundled #'together, sharing a single leading \dQuote{"-"}, but only the final short #'flag is able to have a corresponding argument. %%% #' #'@name optparse-package #'@aliases optparse-package optparse #'@docType package #'@author Trevor Davis. #' #'Some documentation and unit tests ported from Allen Day's getopt package. #' #'The documentation for Python's optparse library, which this package is based #'on, is Copyright 1990-2009, Python Software Foundation. #'@seealso \code{\link[getopt]{getopt}} #'@references Python's \code{optparse} library, which this package is based on, #'is described here: \url{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/0000755000176200001440000000000013133277714014127 5ustar liggesusersoptparse/vignettes/optparse.Rrst0000644000176200001440000001213612253432313016631 0ustar liggesusers.. %\VignetteIndexEntry{optparse Command Line Option Parsing} %\VignetteEngine{knitr} optparse Command Line Option Parsing ==================================== optparse is a command line option parser inspired by Python's "optparse" library. Use this with Rscript to write "#!"-shebang scripts that accept short and long flags/options, generate a usage statement, and set default values for options that are not specified on the command line. .. {r echo=FALSE} .. library("knitr") .. Rscript_executable <- paste(file.path(R.home(), "bin", "Rscript"), "--vanilla") .. opts_knit$set(root.dir = system.file("exec", package="optparse")) # to access the "Rscript files" .. opts_chunk$set(comment=NA, echo=FALSE) .. # setwd(system.file("exec", package="optparse")) # to access the "Rscript files" .. list_file_command <- "ls" .. chmod_command <- "chmod ug+x display_file.R example.R" .. path_command <- "export PATH=$PATH:`pwd`" .. run_command <- function(string) { suppressWarnings(cat(system(string, intern=TRUE), sep="\n")) } .. .. In our working directory we have two example R scripts, named "example.R" and "display\_file.R" illustrating the use of the optparse package. **:r:`paste("bash$", list_file_command)`** .. {r} .. run_command(sprintf("%s", list_file_command)) .. command <- "display_file.R example.R" # to show file .. .. In order for a \*nix system to recognize a "#!"-shebang line you need to mark the file executable with the ``chmod`` command, it also helps to add the directory containing your Rscripts to your path: **:r:`paste("bash$", chmod_command)`** **:r:`paste("bash$", path_command)`** Here is what ``example.R`` contains: **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. .. {r} .. command <- "example.R --help" # same as system("Rscript example.R -h") .. .. By default *optparse* will generate a help message if it encounters ``--help`` or ``-h`` on the command line. Note how ``%default`` in the example program was replaced by the actual default values in the help statement that *optparse* generated. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R" # rely only on defaults .. .. If you specify default values when creating your ``OptionParser`` then *optparse* will use them as expected. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --mean=10 --sd=10 --count=3" .. .. Or you can specify your own values. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --quiet -c 4 --generator=\"runif\"" # same as above but "quiet" .. .. If you remember from the example program that ``--quiet`` had ``action="store_false"`` and ``dest="verbose"``. This means that ``--quiet`` is a switch that turns the ``verbose`` option from its default value of ``TRUE`` to ``FALSE``. Note how the ``verbose`` and ``quiet`` options store their value in the exact same variable. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R --silent -m 5" # same as above but "quiet" .. .. If you specify an illegal flag then *optparse* will throw an error. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "example.R -c 100 -c 2 -c 1000 -c 7" # same as above but "quiet" .. .. If you specify the same option multiple times then *optparse* will use the value of the last option specified. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. *optparse* can also recognize positional arguments if ``parse_args`` is given the option ``positional_arguments = c(min_pa, max_pa)`` where ``min_pa`` is the minimum and ``max_pa`` is the maximum number of supported positional arguments. (A single numeric corresponds to ``min_pa == max_pa``, ``TRUE`` is equivalent to ``c(0, Inf)``, and ``FALSE``, the default, is equivalent to ``0``.) Below we give an example program *display_file.R*, which is a program that prints out the contents of a single file (the required positional argument, not an optional argument) and which accepts the normal help option as well as an option to add line numbers to the output. Note that the positional arguments need to be placed *after* the optional arguments. .. {r} .. command <- "display_file.R --help" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R --add_numbers display_file.R" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R non_existent_file.txt" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. command <- "display_file.R" .. .. **:r:`paste("bash$", command)`** .. {r} .. run_command(sprintf("%s %s 2>&1", Rscript_executable, command)) .. .. optparse/MD50000644000176200001440000000230313133505232012412 0ustar liggesuserseb723b61539feef013de476e68b5c50a *COPYING ce81a796dfbf2278cf99842398085caf *DESCRIPTION 749f23b64eeb7c0b390b46bf4b9fd05c *NAMESPACE 1a5486daff51215c8c7fe8586e395d6d *NEWS 52e3196bac3d6fa2c056308a33b6ed82 *R/optparse-package.R 148887ec729b4414562dc7fa052f185b *R/optparse.R 435b78f0d560935a5a096d8db11bad73 *build/vignette.rds 1208f601f23f90cd50aeaf3834b0e6d2 *exec/display_file.R df7a5045be8d8227affc83c88cb21e79 *exec/example.R e3b4ab464d3b774a7ba93b60c34cc716 *inst/COPYRIGHTS e8d2f193753efe3a0260ddb16cf68493 *inst/doc/optparse.R 8a64473dff672d3f50622f46f76d56eb *inst/doc/optparse.Rrst 9d965bbc828a03c8697e3be9c9133a20 *inst/doc/optparse.html 12daa156845d29d0eaee6879cd1f25e2 *man/OptionParser-class.Rd 07a5161e2ca95285aff95a61565d19c4 *man/OptionParser.Rd 0dcee7403c9dc84876743d69a5bb099c *man/OptionParserOption-class.Rd 4807fdaa669b288f36bceec38615c9fd *man/add_make_option.Rd 1e125ca48f272987c81387481c2e845b *man/optparse-package.Rd 8885bdb1abe98033e3f1245eb1006989 *man/parse_args.Rd d31f07626001175444d44f070a5d2c12 *man/print_help.Rd 398b710c16889ab67e30dbb3bad87137 *tests/run-all.R 08a5305946fa1a1c403c779a7a64e9be *tests/testthat/test-optparse.R 8a64473dff672d3f50622f46f76d56eb *vignettes/optparse.Rrst optparse/build/0000755000176200001440000000000013133277714013216 5ustar liggesusersoptparse/build/vignette.rds0000644000176200001440000000033413133277714015555 0ustar liggesusersuQ 0~k_" .jl'ώ*W8gg}r.r180_;C>htCI!㕨kx8f9 <뺲 Fȓ '5U|҆;%hF2VQw4Rg?ߗMaW"^4(&Qoptparse/DESCRIPTION0000644000176200001440000000205313133505232013612 0ustar liggesusersEncoding: UTF-8 Package: optparse Type: Package Title: Command Line Option Parser Version: 1.4.4 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, Kirill Müller, Peter Humburg, and Rich FitzJohn. 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.0) Suggests: knitr (>= 1.15.19), stringr, testthat VignetteBuilder: knitr RoxygenNote: 6.0.1 NeedsCompilation: no Packaged: 2017-07-18 03:26:04 UTC; trevorld Repository: CRAN Date/Publication: 2017-07-18 22:24:26 UTC optparse/man/0000755000176200001440000000000012442146513012664 5ustar liggesusersoptparse/man/add_make_option.Rd0000644000176200001440000001002513117554123016266 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \name{make_option} \alias{make_option} \alias{add_option} \title{Functions to enable our OptionParser to recognize specific command line options.} \usage{ make_option(opt_str, action = "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{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.} \item{help}{A character string describing the option to be used by \code{print_help} in generating a usage message. \code{\%default} will be substituted by the value of \code{default}.} \item{metavar}{A character string that stands in for the option argument when printing help text. Default is the value of \code{dest}.} \item{object}{An instance of the \code{OptionParser} class} } \value{ Both \code{make_option} and \code{add_option} return instances of class \code{OptionParserOption}. } \description{ \code{add_option} adds a option to a prexisting \code{OptionParser} instance whereas \code{make_option} is used to create a list of \code{OptionParserOption} instances that will be used in the \code{option_list} argument of the \code{OptionParser} function to create a new \code{OptionParser} instance. } \examples{ make_option("--longflag") make_option(c("-l", "--longflag")) make_option("--integer", type="integer", default=5) make_option("--integer", default=as.integer(5)) # same as previous # examples from package vignette make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]") make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output") make_option(c("-c", "--count"), type="integer", default=5, help="Number of random normals to generate [default \%default]", metavar="number") make_option("--generator", default="rnorm", help = "Function to generate random deviates [default \\"\%default\\"]") make_option("--mean", default=0, help="Mean if generator == \\"rnorm\\" [default \%default]") make_option("--sd", default=1, metavar="standard deviation", help="Standard deviation if generator == \\"rnorm\\" [default \%default]") } \references{ Python's \code{optparse} library, which inspires this package, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{\link{parse_args}} \code{\link{OptionParser}} } \author{ Trevor Davis. } optparse/man/print_help.Rd0000644000176200001440000000142413070312564015317 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \name{print_help} \alias{print_help} \title{Printing an usage message from an OptionParser object} \usage{ print_help(object) } \arguments{ \item{object}{A \code{OptionParser} instance.} } \value{ \code{print_help} uses the \code{cat} function to print out a usage message. It returns \code{invisible(NULL)}. } \description{ \code{print_help} print an usage message from an OptionParser object, usually called by \code{parse_args} when it encounters a help option. } \references{ Python's \code{optparse} library, which inspired this package, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{{parse_args}} \code{{OptionParser}} } \author{ Trevor Davis. } optparse/man/OptionParser.Rd0000644000176200001440000000371613070312564015606 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \name{OptionParser} \alias{OptionParser} \title{A function to create an instance of a parser object} \usage{ OptionParser(usage = "usage: \%prog [options]", option_list = list(), add_help_option = TRUE, prog = NULL, description = "", epilogue = "") } \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. } \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}} } \author{ Trevor Davis. } optparse/man/OptionParserOption-class.Rd0000644000176200001440000000441213117554123020075 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \docType{class} \name{OptionParserOption-class} \alias{OptionParserOption-class} \alias{OptionParserOption} \title{Class to hold information about command-line options} \description{ Class to hold information about command-line options } \section{Slots}{ \describe{ \item{\code{short_flag}}{String of the desired short flag comprised of the \dQuote{-} followed by a letter.} \item{\code{long_flag}}{String of the desired long flag comprised of \dQuote{--} followed by a letter and then a sequence of alphanumeric characters.} \item{\code{action}}{A character string that describes the action \code{optparse} should take when it encounters an option, either \dQuote{store}, \dQuote{store_true}, or \dQuote{store_false}. The default is \dQuote{store} which signifies that \code{optparse} should store the specified following value if the option is found on the command string. \dQuote{store_true} stores \code{TRUE} if the option is found and \dQuote{store_false} stores \code{FALSE} if the option is found.} \item{\code{type}}{A character string that describes specifies which data type should be stored, either \dQuote{logical}, \dQuote{integer}, \dQuote{double}, \dQuote{complex}, or \dQuote{character}. Default is \dQuote{logical} if \code{action \%in\% c("store_true", store_false)}, \code{typeof(default)} if \code{action == "store"} and default is not \code{NULL} and \dQuote{character} if \code{action == "store"} and default is \code{NULL}. \dQuote{numeric} will be converted to \dQuote{double}.} \item{\code{dest}}{A character string that specifies what field in the list returned by \code{parse_args} should \code{optparse} store option values. Default is derived from the long flag in \code{opt_str}.} \item{\code{default}}{The default value \code{optparse} should use if it does not find the option on the command line.} \item{\code{help}}{A character string describing the option to be used by \code{print_help} in generating a usage message. \code{\%default} will be substituted by the value of \code{default}.} \item{\code{metavar}}{A character string that stands in for the option argument when printing help text. Default is the value of \code{dest}.} }} \seealso{ \code{\link{make_option}} } optparse/man/OptionParser-class.Rd0000644000176200001440000000203213070312564016677 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \docType{class} \name{OptionParser-class} \alias{OptionParser-class} \title{Option Parser} \description{ Option Parser } \section{Slots}{ \describe{ \item{\code{usage}}{The program usage message that will printed out if \code{parse_args} finds a help option, \code{\%prog} is substituted with the value of the \code{prog} argument.} \item{\code{options}}{A list of of \code{OptionParserOption} instances that will define how \code{parse_args} reacts to command line options. \code{OptionParserOption} instances are usually created by \code{make_option} and can also be added to an existing \code{OptionParser} instance via the \code{add_option} function.} \item{\code{description}}{Additional text for \code{print_help} to print out between usage statement and options statement} \item{\code{epilogue}}{Additional text for \code{print_help} to print out after the options statement} }} \seealso{ \code{\link{OptionParserOption}} } \author{ Trevor Davis. } optparse/man/optparse-package.Rd0000644000176200001440000000416313070312564016404 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse-package.R \docType{package} \name{optparse-package} \alias{optparse-package} \alias{optparse} \title{Command line option parser} \description{ Goal is to create an R package of a command line parser inspired by Python's \dQuote{optparse} library. } \details{ \code{optparse} is primarily intended to be used with \dQuote{Rscript}. It facilitates writing \dQuote{#!} shebang scripts that accept short and long flags/options. It can also be used from directly, but is probably less useful in this context. See package vignette for a more detailed example. Notes on naming convention in package: 1. An option is one of the shell-split input strings. 2. A flag is a type of option. a flag can be defined as having no argument (defined below), a required argument, or an optional argument. 3. An argument is a type of option, and is the value associated with a flag. 4. A long flag is a type of flag, and begins with the string \dQuote{--}. If the long flag has an associated argument, it may be delimited from the long flag by either a trailing =, or may be the subsequent option. 5. A short flag is a type of flag, and begins with the string \dQuote{-}. If a short flag has an associated argument, it is the subsequent option. short flags may be bundled together, sharing a single leading \dQuote{"-"}, but only the final short flag is able to have a corresponding argument. %%% } \examples{ example_file <- system.file("exec", "example.R", package = "optparse") example_file_2 <- system.file("exec", "display_file.R", package = "optparse") \dontrun{ readLines(example_file) readLines(example_file_2) } } \references{ Python's \code{optparse} library, which this package is based on, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{\link[getopt]{getopt}} } \author{ Trevor Davis. Some documentation and unit tests ported from Allen Day's getopt package. The documentation for Python's optparse library, which this package is based on, is Copyright 1990-2009, Python Software Foundation. } \keyword{package} optparse/man/parse_args.Rd0000644000176200001440000001052713070312564015305 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/optparse.R \encoding{latin1} \name{parse_args} \alias{parse_args} \alias{parse_args2} \title{Parse command line options.} \usage{ parse_args(object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE, positional_arguments = FALSE, convert_hyphens_to_underscores = FALSE) parse_args2(object, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE) } \arguments{ \item{object}{An \code{OptionParser} instance.} \item{args}{A character vector containing command line options to be parsed. Default is everything after the Rscript program in the command line. If \code{positional_arguments} is not \code{FALSE} then \code{parse_args} will look for positional arguments at the end of this vector.} \item{print_help_and_exit}{Whether \code{parse_args} should call \code{print_help} to print out a usage message and exit the program. Default is \code{TRUE}.} \item{positional_arguments}{Number of \emph{positional} arguments. A numeric denoting the exact number of supported arguments, or a numeric vector of length two denoting the minimum and maximum number of arguments (\code{Inf} for no limit). The value \code{TRUE} is equivalent to \code{c(0, Inf)}. The default \code{FALSE} is supported for backward compatibility only, as it alters the format of the return value.} \item{convert_hyphens_to_underscores}{If the names in the returned list of options contains hyphens then convert them to underscores. The default \code{FALSE} is supported for backward compatibility reasons as it alters the format of the return value} } \value{ Returns a list with field \code{options} containing our option values as well as another field \code{args} which contains a vector of positional arguments. For backward compatibility, if and only if \code{positional_arguments} is \code{FALSE}, returns a list containing option values. } \description{ \code{parse_args} parses command line options using an \code{OptionParser} instance for guidance. \code{parse_args2} is a wrapper to \code{parse_args} setting the options \code{positional_arguments} and \code{convert_hyphens_to_underscores} to \code{TRUE}. } \section{Acknowledgement}{ A big thanks to Steve Lianoglou for a bug report and patch; Juan Carlos \enc{Borrás}{Borras} for a bug report; Jim Nikelski for a bug report and patch; Ino de Brujin and Benjamin Tyner for a bug report; Jonas Zimmermann for bug report; Miroslav Posta for bug reports; Stefan Seemayer for bug report and patch; Kirill \enc{Müller}{Muller} for patches; Steve Humburg for patch. } \examples{ # example from vignette option_list <- list( make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Print extra output [default]"), make_option(c("-q", "--quietly"), action="store_false", dest="verbose", help="Print little output"), make_option(c("-c", "--count"), type="integer", default=5, help="Number of random normals to generate [default \%default]", metavar="number"), make_option("--generator", default="rnorm", help = "Function to generate random deviates [default \\"\%default\\"]"), make_option("--mean", default=0, help="Mean if generator == \\"rnorm\\" [default \%default]"), make_option("--sd", default=1, metavar="standard deviation", help="Standard deviation if generator == \\"rnorm\\" [default \%default]") ) parse_args(OptionParser(option_list = option_list), args = c("--sd=3", "--quietly")) # example from vignette using positional arguments option_list2 <- list( make_option(c("-n", "--add-numbers"), action="store_true", default=FALSE, help="Print line number at the beginning of each line [default]") ) parser <- OptionParser(usage = "\%prog [options] file", option_list=option_list2) parse_args(parser, args = c("--add-numbers", "example.txt"), positional_arguments = TRUE) parse_args(parser, args = c("--add-numbers", "example.txt"), positional_arguments = TRUE, convert_hyphens_to_underscores = TRUE) parse_args2(parser, args = c("--add-numbers", "example.txt")) } \references{ Python's \code{optparse} library, which inspired this package, is described here: \url{http://docs.python.org/library/optparse.html} } \seealso{ \code{\link{OptionParser}} \code{\link{print_help}} } \author{ Trevor Davis. }