././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/COPYING 0000644 0000000 0000000 00000104514 14644537545 010526 0 ustar 00 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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
state 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 3 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, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU 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 Lesser General
Public License instead of this License. But first, please read
.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/COPYING.LESSER 0000644 0000000 0000000 00000016744 14644537545 011531 0 ustar 00 GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/README.rst 0000644 0000000 0000000 00000012106 14644537545 011155 0 ustar 00 Argh: The Effortless CLI
========================
.. image:: https://github.com/neithere/argh/actions/workflows/lint-and-test.yml/badge.svg
:target: https://github.com/neithere/argh/actions/workflows/lint-and-test.yml
.. image:: https://img.shields.io/pypi/format/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://img.shields.io/pypi/status/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://img.shields.io/pypi/v/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://img.shields.io/pypi/pyversions/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://img.shields.io/pypi/dd/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://readthedocs.org/projects/argh/badge/?version=stable
:target: http://argh.readthedocs.org/en/stable/
.. image:: https://readthedocs.org/projects/argh/badge/?version=latest
:target: http://argh.readthedocs.org/en/latest/
**The power of Argparse with plain Python functions!**
Building a command-line interface? Found yourself uttering "argh!" while
struggling with the API of `argparse`? Don't like the complexity but need
the power?
`Argh` builds on the power of `argparse` (which comes with Python) and makes it
really easy to use. It eliminates the complex API and lets you "dispatch"
ordinary Python functions as CLI commands.
Installation
------------
::
$ pip install argh
Example
-------
.. code-block:: python
import argh
def verify_paths(paths: list[str], *, verbose: bool = False):
"""
Verify that all given paths exist.
"""
for path in paths:
if verbose:
print(f"Checking {path}...")
assert os.path.exists(path)
argh.dispatch_command(verify_paths)
Now you can run the script like this:
.. code-block:: bash
$ python app.py foo.txt bar/quux.txt
$ python app.py foo.txt bar/quux.txt --verbose
Checking foo.txt...
Checking bar/quux.txt...
$ python app.py -h
usage: app.py [-h] [-v] [paths ...]
Verify that all given paths exist.
positional arguments:
paths -
options:
-h, --help show this help message and exit
-v, --verbose False
Please check the documentation for examples of multiple commands, modularity,
help generation, advanced type annotations inspection, decorators and more:
* `Quick Start `_
* `Tutorial `_
Why Argh?
---------
`Argh`-powered applications are *simple* but *flexible*:
:Pythonic, KISS:
Commands are plain Python functions. Almost no CLI-specific API to learn.
:Reusable:
Endpoint functions can be used directly outside of CLI context.
:Static typing friendly:
100% of the code including endpoint functions can be type-checked.
Argh is driven primarily by type annotations.
:DRY:
Don't Repeat Yourself. The amount of boilerplate code is minimal.
Among other things, `Argh` will:
* infer command name from function name;
* infer arguments from function signature;
* infer argument types, actions and much more from annotations.
:Modular:
Declaration of commands can be decoupled from assembling and dispatching.
:Layered:
The complexity of code raises with requirements.
:Transparent:
You can directly access `argparse.ArgumentParser` if needed.
:Subcommands:
Easily nested commands. Argh isolates the complexity of subparsers.
:NIH free:
`Argh` supports *completion*, *progress bars* and everything else by being
friendly to excellent 3rd-party libraries. No need to reinvent the wheel.
:Compact:
No dependencies apart from Python's standard library.
Links
-----
See also the `project page on GitHub`_, `documentation`_ and `PyPI page`_.
.. _project page on GitHub: http://github.com/neithere/argh/
.. _documentation: http://argh.readthedocs.org
.. _PyPI page: http://pypi.python.org/pypi/argh
Author
------
Developed by Andrey Mikhaylenko since 2010.
See `contributors `_
for a list of contributors to this library.
Contribute
----------
The fastest way to improve this project is to submit tested and documented
patches or detailed bug reports.
Donate
------
You can `donate via Liberapay`_. This may speed up development or simply
make the original author happy :)
.. _donate via Liberapay: https://liberapay.com/neithere/donate
Licensing
---------
Argh is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Argh 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Argh. If not, see .
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/pyproject.toml 0000644 0000000 0000000 00000004274 14644537545 012411 0 ustar 00 [build-system]
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"
[project]
name = "argh"
version = "0.31.3"
description = "Plain Python functions as CLI commands without boilerplate"
readme = "README.rst"
requires-python = ">=3.8"
license = { file = "COPYING.LESSER" }
authors = [
{ name = "Andy Mikhaylenko", email = "neithere@gmail.com" },
]
maintainers = [
{ name = "Andy Mikhaylenko", email = "neithere@gmail.com" },
]
keywords = [
"cli",
"command line",
"argparse",
"optparse",
"argument",
"option",
]
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: User Interfaces",
"Topic :: Software Development :: Libraries :: Python Modules",
]
[project.urls]
Homepage = "https://github.com/neithere/argh"
"Issue Tracker" = "https://github.com/neithere/argh/issues"
Discussions = "https://github.com/neithere/argh/discussions"
"Releases" = "https://github.com/neithere/argh/releases"
Documentation = "https://argh.readthedocs.io/en/latest"
[project.optional-dependencies]
completion = [
"argcomplete >= 2.0",
]
test = [
"tox >= 4.11.3",
"pytest >= 7.4",
"pytest-cov >= 4.1",
]
docs = [
"sphinx >= 7.2",
"sphinx-pyproject == 0.3",
"sphinx_rtd_theme >= 2.0",
"readthedocs-sphinx-search == 0.3.2",
]
linters = [
"pre-commit >= 3.4.0",
]
[tool.distutils.bdist_wheel]
universal = 1
[tool.bandit]
exclude_dirs = ["tests"]
[tool.flit.sdist]
include = [
"AUTHORS.rst",
"CHANGES.rst",
"COPYING",
"COPYING.LESSER",
"tests/",
"tox.ini",
]
[tool.doc8]
max-line-length = 95
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/__init__.py 0000644 0000000 0000000 00000002267 14644537545 013316 0 ustar 00 """
Argh
~~~~
"""
#
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
from .assembling import add_commands, add_subcommands, set_default_command
from .decorators import aliases, arg, named, wrap_errors
from .dispatching import (
PARSER_FORMATTER,
ArghNamespace,
EntryPoint,
dispatch,
dispatch_command,
dispatch_commands,
parse_and_resolve,
run_endpoint_function,
)
from .exceptions import AssemblingError, CommandError, DispatchingError
from .helpers import ArghParser
from .interaction import confirm
__all__ = (
"add_commands",
"add_subcommands",
"set_default_command",
"aliases",
"arg",
"named",
"wrap_errors",
"PARSER_FORMATTER",
"ArghNamespace",
"EntryPoint",
"dispatch",
"dispatch_command",
"dispatch_commands",
"AssemblingError",
"CommandError",
"DispatchingError",
"ArghParser",
"confirm",
"parse_and_resolve",
"run_endpoint_function",
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/assembling.py 0000644 0000000 0000000 00000071725 14644537545 013710 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Assembling
~~~~~~~~~~
Functions and classes to properly assemble your commands in a parser.
"""
import inspect
import textwrap
import warnings
from argparse import OPTIONAL, ZERO_OR_MORE, ArgumentParser
from collections import OrderedDict
from enum import Enum
from typing import (
Any,
Callable,
Dict,
Iterator,
List,
Literal,
Optional,
Tuple,
Union,
get_args,
get_origin,
)
# types.UnionType was introduced in Python < 3.10
try: # pragma: no cover
from types import UnionType
UNION_TYPES = [Union, UnionType]
except ImportError: # pragma: no cover
UNION_TYPES = [Union]
from argh.completion import COMPLETION_ENABLED
from argh.constants import (
ATTR_ALIASES,
ATTR_ARGS,
ATTR_NAME,
DEFAULT_ARGUMENT_TEMPLATE,
DEST_FUNCTION,
PARSER_FORMATTER,
)
from argh.dto import NotDefined, ParserAddArgumentSpec
from argh.exceptions import AssemblingError
from argh.utils import get_subparsers
__all__ = [
"set_default_command",
"add_commands",
"add_subcommands",
"NameMappingPolicy",
]
class NameMappingPolicy(Enum):
"""
Represents possible approaches to treat default values when inferring argument
specification from function signature.
* `BY_NAME_IF_KWONLY` is the default and recommended approach introduced
in v0.30. It enables fine control over two aspects:
* positional vs named;
* required vs optional.
"Normal" arguments are identified by position, "kwonly" are identified by
name, regardless of the presence of default values. A positional with a
default value becomes optional but still positional (``nargs=OPTIONAL``).
A kwonly argument without a default value becomes a required named
argument.
Example::
def func(alpha, beta=1, *, gamma, delta=2): ...
is equivalent to::
prog alpha [beta] --gamma [--delta DELTA]
That is, ``alpha`` and ``--gamma`` are mandatory while ``beta`` and
``--delta`` are optional (they have default values).
* `BY_NAME_IF_HAS_DEFAULT` is very close to the the legacy approach
(pre-v0.30). If a function argument has a default value, it becomes an
"option" (called by name, like ``--foo``); otherwise it's treated as a
positional argument.
Example::
def func(alpha, beta=1, *, gamma, delta=2): ...
is equivalent to::
prog [--beta BETA] [--delta DELTA] alpha gamma
That is, ``alpha`` and ``gamma`` are mandatory and positional, while
``--beta`` and ``--delta`` are optional (they have default values). Note
that it's impossible to have an optional positional or a mandatory named
argument.
The difference between this policy and the behaviour of Argh before
v0.30 is in the treatment of kwonly arguments without default values:
they used to become ``--foo FOO`` (required) but for the sake of
simplicity they are treated as positionals. If you are already using
kwonly args, please consider the better suited policy `BY_NAME_IF_KWONLY`
instead.
It is recommended to migrate any older code to `BY_NAME_IF_KWONLY`.
.. versionadded:: 0.30
"""
BY_NAME_IF_HAS_DEFAULT = "specify CLI argument by name if it has a default value"
BY_NAME_IF_KWONLY = "specify CLI argument by name if it comes from kwonly"
def infer_argspecs_from_function(
function: Callable,
name_mapping_policy: Optional[NameMappingPolicy] = None,
can_use_hints: bool = False,
) -> Iterator[ParserAddArgumentSpec]:
if name_mapping_policy and name_mapping_policy not in NameMappingPolicy:
raise NotImplementedError(f"Unknown name mapping policy {name_mapping_policy}")
func_signature = inspect.signature(function)
has_kwonly = any(
p.kind == p.KEYWORD_ONLY for p in func_signature.parameters.values()
)
# define the list of conflicting option strings
# (short forms, i.e. single-character ones)
named_args = [
p.name
for p in func_signature.parameters.values()
if p.default is not p.empty or p.kind == p.KEYWORD_ONLY
]
named_arg_chars = [a[0] for a in named_args]
named_arg_char_counts = dict(
(char, named_arg_chars.count(char)) for char in set(named_arg_chars)
)
conflicting_opts = tuple(
char for char in named_arg_char_counts if 1 < named_arg_char_counts[char]
)
def _make_cli_arg_names_options(arg_name) -> Tuple[List[str], List[str]]:
cliified_arg_name = arg_name.replace("_", "-")
positionals = [cliified_arg_name]
can_have_short_opt = arg_name[0] not in conflicting_opts
if can_have_short_opt:
options = [f"-{cliified_arg_name[0]}", f"--{cliified_arg_name}"]
else:
options = [f"--{cliified_arg_name}"]
return positionals, options
default_value: Any
for parameter in func_signature.parameters.values():
(cli_arg_names_positional, cli_arg_names_options) = _make_cli_arg_names_options(
parameter.name
)
if parameter.default is not parameter.empty:
default_value = parameter.default
else:
default_value = NotDefined
extra_spec_kwargs = {}
if can_use_hints:
hints = function.__annotations__
if parameter.name in hints:
extra_spec_kwargs = (
TypingHintArgSpecGuesser.typing_hint_to_arg_spec_params(
hints[parameter.name]
)
)
if parameter.kind in (
parameter.POSITIONAL_ONLY,
parameter.POSITIONAL_OR_KEYWORD,
):
if default_value != NotDefined and not name_mapping_policy:
message = textwrap.dedent(
f"""
Argument "{parameter.name}" in function "{function.__name__}"
is not keyword-only but has a default value.
Please note that since Argh v.0.30 the default name mapping
policy has changed.
More information:
https://argh.readthedocs.io/en/latest/changes.html#version-0-30-0-2023-10-21
You need to upgrade your functions so that the arguments
that have default values become keyword-only:
f(x=1) -> f(*, x=1)
If you actually want an optional positional argument,
please set the name mapping policy explicitly to `BY_NAME_IF_KWONLY`.
If you choose to postpone the migration, you have two options:
a) set the policy explicitly to `BY_NAME_IF_HAS_DEFAULT`;
b) pin Argh version to 0.29 until you are ready to migrate.
Thank you for understanding!
"""
).strip()
# Assume legacy policy and show a warning if the signature is
# simple (without kwonly args) so that the script continues working
# but the author is urged to upgrade it.
# When it cannot be auto-resolved (kwonly args mixed with old-style
# ones but no policy specified), throw an error.
#
# TODO: remove in v.0.33 if it happens, otherwise in v1.0.
if has_kwonly:
raise ArgumentNameMappingError(message)
warnings.warn(DeprecationWarning(message))
name_mapping_policy = NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT
arg_spec = ParserAddArgumentSpec(
func_arg_name=parameter.name,
cli_arg_names=cli_arg_names_positional,
default_value=default_value,
other_add_parser_kwargs=extra_spec_kwargs,
)
if default_value != NotDefined:
if name_mapping_policy == NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT:
arg_spec.cli_arg_names = cli_arg_names_options
else:
arg_spec.nargs = OPTIONAL
# annotations are interpreted without regard to the broader
# context, e.g. default values; in some cases argparse requires
# pretty specific combinations of props, so we need to adjust them
if can_use_hints:
# "required" is invalid for positional CLI argument;
# it may have been set from Optional[...] hint above.
# Reinterpret it as "optional positional" instead.
if "required" in arg_spec.other_add_parser_kwargs:
value = arg_spec.other_add_parser_kwargs.pop("required")
if value is False:
arg_spec.nargs = OPTIONAL
if name_mapping_policy == NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT:
# The guesser yields `type=bool` from `foo: bool = False`
# but `type` is incompatible with `action="store_true"` which
# is added by guess_extra_parser_add_argument_spec_kwargs().
if (
isinstance(arg_spec.default_value, bool)
and arg_spec.other_add_parser_kwargs.get("type") == bool
):
del arg_spec.other_add_parser_kwargs["type"]
yield arg_spec
elif parameter.kind == parameter.KEYWORD_ONLY:
arg_spec = ParserAddArgumentSpec(
func_arg_name=parameter.name,
cli_arg_names=cli_arg_names_positional,
default_value=default_value,
other_add_parser_kwargs=extra_spec_kwargs,
)
if name_mapping_policy == NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT:
if default_value != NotDefined:
arg_spec.cli_arg_names = cli_arg_names_options
else:
arg_spec.cli_arg_names = cli_arg_names_options
if default_value == NotDefined:
arg_spec.is_required = True
# annotations are interpreted without regard to the broader
# context, e.g. default values; in some cases argparse requires
# pretty specific combinations of props, so we need to adjust them
if can_use_hints:
# The guesser yields `type=bool` from `foo: bool = False`
# but `type` is incompatible with `action="store_true"` which
# is added by guess_extra_parser_add_argument_spec_kwargs().
if (
isinstance(arg_spec.default_value, bool)
and arg_spec.other_add_parser_kwargs.get("type") == bool
):
del arg_spec.other_add_parser_kwargs["type"]
yield arg_spec
elif parameter.kind == parameter.VAR_POSITIONAL:
yield ParserAddArgumentSpec(
func_arg_name=parameter.name,
cli_arg_names=[parameter.name.replace("_", "-")],
nargs=ZERO_OR_MORE,
other_add_parser_kwargs=extra_spec_kwargs,
)
def guess_extra_parser_add_argument_spec_kwargs(
parser_add_argument_spec: ParserAddArgumentSpec,
) -> Dict[str, Any]:
"""
Given an argument specification, returns types, actions, etc. that could be
guessed from it:
* ``default=3`` → ``type=int``
TODO: deprecate in favour of ``foo: int = 3`` in func signature.
* ``choices=[3]`` → ``type=int``
TODO: deprecate in favour of ``foo: int`` in func signature.
* ``type=bool`` → ``action="store_false"`` or ``action="store_true"``
(if action was not explicitly defined).
"""
# TODO: use typing to extract
other_add_parser_kwargs = parser_add_argument_spec.other_add_parser_kwargs
guessed: Dict[str, Any] = {}
is_positional = not parser_add_argument_spec.cli_arg_names[0].startswith("-")
# Parser actions that accept argument 'type'
TYPE_AWARE_ACTIONS = "store", "append"
# guess type/action from default value
default_value = parser_add_argument_spec.default_value
if default_value not in (None, NotDefined):
if isinstance(default_value, bool):
if not is_positional and other_add_parser_kwargs.get("action") is None:
# infer action from default value
# (not applicable to positionals: _StoreAction doesn't accept `nargs`)
guessed["action"] = "store_false" if default_value else "store_true"
elif other_add_parser_kwargs.get("type") is None:
if isinstance(default_value, (list, tuple)):
if "nargs" not in other_add_parser_kwargs:
# the argument has a default value, so it doesn't have to
# be passed; "zero or more" is a reasonable guess
guessed["nargs"] = ZERO_OR_MORE
else:
# infer type from default value
# (make sure that action handler supports this keyword)
if other_add_parser_kwargs.get("action", "store") in TYPE_AWARE_ACTIONS:
guessed["type"] = type(default_value)
# guess type from choices (first item)
if other_add_parser_kwargs.get("choices") and "type" not in list(guessed) + list(
other_add_parser_kwargs
):
guessed["type"] = type(other_add_parser_kwargs["choices"][0])
return guessed
def set_default_command(
parser,
function: Callable,
name_mapping_policy: Optional[NameMappingPolicy] = None,
) -> None:
"""
Sets default command (i.e. a function) for given parser.
If `parser.description` is empty and the function has a docstring,
it is used as the description.
:param function:
The function to use as the command.
:name_mapping_policy:
The policy to use when mapping function arguments onto CLI arguments.
See :class:`.NameMappingPolicy`. If not defined explicitly,
`BY_NAME_IF_KWONLY` is used.
.. versionadded:: 0.30
.. versionchanged:: 0.30.2
Raises `ArgumentNameMappingError` if the policy was not explicitly
defined and a non-kwonly argument has a default value. The reason
is that it's very likely to be a case of non-migrated code where
the argument was intended to be mapped onto a CLI option. It's
better to fail explicitly than to silently change the CLI API.
.. note::
If there are both explicitly declared arguments (e.g. via
:func:`~argh.decorators.arg`) and ones inferred from the function
signature, declared ones will be merged into inferred ones.
If an argument does not conform to the function signature,
`ArgumentNameMappingError` is raised.
.. note::
If the parser was created with ``add_help=True`` (which is by default),
option name ``-h`` is silently removed from any argument.
"""
func_signature = inspect.signature(function)
# the **kwargs thing
has_varkw = any(p.kind == p.VAR_KEYWORD for p in func_signature.parameters.values())
declared_args: List[ParserAddArgumentSpec] = getattr(function, ATTR_ARGS, [])
# transitional period: hints are used for types etc. only if @arg is not used
can_use_hints = not declared_args
inferred_args: List[ParserAddArgumentSpec] = list(
infer_argspecs_from_function(
function,
name_mapping_policy=name_mapping_policy,
can_use_hints=can_use_hints,
)
)
if declared_args and not inferred_args and not has_varkw:
raise ArgumentNameMappingError(
f"{function.__name__}: cannot extend argument declarations "
"for an endpoint function that takes no arguments."
)
if not declared_args:
parser_add_argument_specs = inferred_args
else:
# We've got a mixture of declared and inferred arguments
try:
parser_add_argument_specs = _merge_inferred_and_declared_args(
inferred_args=inferred_args,
declared_args=declared_args,
has_varkw=has_varkw,
)
except ArgumentNameMappingError as exc:
raise ArgumentNameMappingError(f"{function.__name__}: {exc}") from exc
# add the fully formed argument specs to the parser
for spec in parser_add_argument_specs:
_extend_parser_add_argument_spec(
spec=spec, parser_adds_help_arg=parser.add_help
)
try:
action = parser.add_argument(
*spec.cli_arg_names,
**spec.get_all_kwargs(),
)
except Exception as exc:
err_cli_args = "/".join(spec.cli_arg_names)
raise AssemblingError(
f"{function.__name__}: cannot add '{spec.func_arg_name}' as {err_cli_args}: {exc}"
) from exc
if COMPLETION_ENABLED and spec.completer:
action.completer = spec.completer
# display endpoint function docstring in command help
docstring = inspect.getdoc(function)
if docstring and not parser.description:
parser.description = docstring
# add the endpoint function to the parsing result (namespace)
parser.set_defaults(
**{
DEST_FUNCTION: function,
}
)
def _extend_parser_add_argument_spec(
spec: ParserAddArgumentSpec, parser_adds_help_arg: bool
) -> None:
# add types, actions, etc. (e.g. default=3 implies type=int)
spec.other_add_parser_kwargs.update(
guess_extra_parser_add_argument_spec_kwargs(spec)
)
# display default value for this argument in command help
if "help" not in spec.other_add_parser_kwargs:
spec.other_add_parser_kwargs.update(help=DEFAULT_ARGUMENT_TEMPLATE)
# If the parser was created with `add_help=True`, it automatically adds
# the -h/--help argument (on argparse side). If we have added -h for
# another argument (e.g. --host) earlier (inferred or declared), we
# need to remove that short form now.
if parser_adds_help_arg and "-h" in spec.cli_arg_names:
spec.cli_arg_names = [name for name in spec.cli_arg_names if name != "-h"]
def _merge_inferred_and_declared_args(
inferred_args: List[ParserAddArgumentSpec],
declared_args: List[ParserAddArgumentSpec],
has_varkw: bool,
) -> List[ParserAddArgumentSpec]:
# a mapping of "dest" strings to argument declarations.
#
# * a "dest" string is a normalized form of argument name, i.e.:
#
# "-f", "--foo" → "foo"
# "foo-bar" → "foo_bar"
#
# * argument declaration is a dictionary representing an argument;
# it is obtained either from infer_argspecs_from_function()
# or from an @arg decorator (as is).
#
specs_by_func_arg_name = OrderedDict()
# arguments inferred from function signature
for parser_add_argument_spec in inferred_args:
specs_by_func_arg_name[parser_add_argument_spec.func_arg_name] = (
parser_add_argument_spec
)
# arguments declared via @arg decorator
for declared_spec in declared_args:
parser_add_argument_spec = declared_spec
func_arg_name = parser_add_argument_spec.func_arg_name
if func_arg_name in specs_by_func_arg_name:
# the argument is already known from function signature
#
# now make sure that this declared arg conforms to the function
# signature and therefore only refines an inferred arg:
#
# @arg("my-foo") maps to func(my_foo)
# @arg("--my-bar") maps to func(my_bar=...)
# either both arguments are positional or both are optional
decl_positional = _is_positional(declared_spec.cli_arg_names)
infr_positional = _is_positional(
specs_by_func_arg_name[func_arg_name].cli_arg_names
)
if decl_positional != infr_positional:
kinds = {True: "positional", False: "optional"}
kind_inferred = kinds[infr_positional]
kind_declared = kinds[decl_positional]
raise ArgumentNameMappingError(
f'argument "{func_arg_name}" declared as {kind_inferred} '
f"(in function signature) and {kind_declared} (via decorator). "
"If you've just migrated from Argh v.0.29, please check "
"the new default NameMappingPolicy. Perhaps you need "
"to replace `func(x=1)` with `func(*, x=1)`?"
)
# merge explicit argument declaration into the inferred one
# (e.g. `help=...`)
specs_by_func_arg_name[func_arg_name].update(parser_add_argument_spec)
else:
# the argument is not in function signature
if has_varkw:
# function accepts **kwargs; the argument goes into it
specs_by_func_arg_name[func_arg_name] = parser_add_argument_spec
else:
# there's no way we can map the argument declaration
# to function signature
dest_option_strings = (
specs_by_func_arg_name[x].cli_arg_names
for x in specs_by_func_arg_name
)
msg_flags = ", ".join(declared_spec.cli_arg_names)
msg_signature = ", ".join("/".join(x) for x in dest_option_strings)
raise ArgumentNameMappingError(
f"argument {msg_flags} does not fit "
f"function signature: {msg_signature}"
)
# pack the modified data back into a list
return list(specs_by_func_arg_name.values())
def _is_positional(args: List[str], prefix_chars: str = "-") -> bool:
if not args or not args[0]:
raise ValueError("Expected at least one argument")
if args[0][0].startswith(tuple(prefix_chars)):
return False
return True
def add_commands(
parser: ArgumentParser,
functions: List[Callable],
name_mapping_policy: Optional[NameMappingPolicy] = None,
group_name: Optional[str] = None,
group_kwargs: Optional[Dict[str, Any]] = None,
func_kwargs: Optional[Dict[str, Any]] = None,
) -> None:
"""
Adds given functions as commands to given parser.
:param parser:
an :class:`argparse.ArgumentParser` instance.
:param functions:
a list of functions. A subparser is created for each of them.
If the function is decorated with :func:`~argh.decorators.arg`, the
arguments are passed to :meth:`argparse.ArgumentParser.add_argument`.
See also :func:`~argh.dispatching.dispatch` for requirements
concerning function signatures. The command name is inferred from the
function name. Note that the underscores in the name are replaced with
hyphens, i.e. function name "foo_bar" becomes command name "foo-bar".
:param name_mapping_policy:
See :class:`argh.assembling.NameMappingPolicy`.
.. versionadded:: 0.30
:param group_name:
an optional string representing the group of commands. For example, if
a command named "hello" is added without the group name, it will be
available as "prog.py hello"; if the group name if specified as "greet",
then the command will be accessible as "prog.py greet hello". The
group itself is not callable, so "prog.py greet" will fail and only
display a help message.
:param func_kwargs:
a `dict` of keyword arguments to be passed to each nested ArgumentParser
instance created per command (i.e. per function). Members of this
dictionary have the highest priority, so a function's docstring is
overridden by a `help` in `func_kwargs` (if present).
:param group_kwargs:
a `dict` of keyword arguments to be passed to the nested ArgumentParser
instance under given `group_name`.
.. note::
This function modifies the parser object. Generally side effects are
bad practice but we don't seem to have any choice as ArgumentParser is
pretty opaque.
You may prefer :meth:`~argh.helpers.ArghParser.add_commands` for a bit
more predictable API.
.. note::
An attempt to add commands to a parser which already has a default
function (e.g. added with :func:`~argh.assembling.set_default_command`)
results in `AssemblingError`.
"""
group_kwargs = group_kwargs or {}
subparsers_action = get_subparsers(parser, create=True)
if group_name:
# Make a nested parser and init a deeper _SubParsersAction under it.
# Create a named group of commands. It will be listed along with
# root-level commands in ``app.py --help``; in that context its `title`
# can be used as a short description on the right side of its name.
# Normally `title` is shown above the list of commands
# in ``app.py my-group --help``.
subsubparser = subparsers_action.add_parser(
group_name, help=group_kwargs.get("title")
)
subparsers_action = subsubparser.add_subparsers(**group_kwargs)
else:
if group_kwargs:
raise ValueError("`group_kwargs` only makes sense with `group_name`.")
for func in functions:
cmd_name, func_parser_kwargs = _extract_command_meta_from_func(func)
# override any computed kwargs by manually supplied ones
if func_kwargs:
func_parser_kwargs.update(func_kwargs)
# create and set up the parser for this command
command_parser = subparsers_action.add_parser(cmd_name, **func_parser_kwargs)
set_default_command(
command_parser, func, name_mapping_policy=name_mapping_policy
)
def _extract_command_meta_from_func(func: Callable) -> Tuple[str, dict]:
# use explicitly defined name; if none, use function name (a_b → a-b)
cmd_name = getattr(func, ATTR_NAME, func.__name__.replace("_", "-"))
func_parser_kwargs: Dict[str, Any] = {
# add command help from function's docstring
"help": func.__doc__,
# set default formatter
"formatter_class": PARSER_FORMATTER,
}
# add aliases for command name
func_parser_kwargs["aliases"] = getattr(func, ATTR_ALIASES, [])
return cmd_name, func_parser_kwargs
def add_subcommands(
parser: ArgumentParser, group_name: str, functions: List[Callable], **group_kwargs
) -> None:
"""
A wrapper for :func:`add_commands`.
These examples are equivalent::
add_commands(
parser,
[get, put],
group_name="db",
group_kwargs={
"title": "database commands",
"help": "CRUD for our silly database"
}
)
add_subcommands(
parser,
"db",
[get, put],
title="database commands",
help="CRUD for our database"
)
"""
add_commands(parser, functions, group_name=group_name, group_kwargs=group_kwargs)
class ArgumentNameMappingError(AssemblingError): ...
class TypingHintArgSpecGuesser:
BASIC_TYPES = (str, int, float, bool)
@classmethod
def typing_hint_to_arg_spec_params(
cls, type_def: type, is_positional: bool = False
) -> Dict[str, Any]:
origin = get_origin(type_def)
args = get_args(type_def)
# `str`
if type_def in cls.BASIC_TYPES:
return {
"type": type_def
# "type": _parse_basic_type(type_def)
}
# `list`
if type_def in (list, List):
return {"nargs": ZERO_OR_MORE}
# `Literal["a", "b"]`
if origin == Literal:
return {"choices": args, "type": type(args[0])}
# `str | int`
if any(origin is t for t in UNION_TYPES):
retval = {}
first_subtype = args[0]
if first_subtype in cls.BASIC_TYPES:
retval["type"] = first_subtype
if first_subtype in (list, List):
retval["nargs"] = ZERO_OR_MORE
if first_subtype != List and get_origin(first_subtype) == list:
retval["nargs"] = ZERO_OR_MORE
item_type = cls._extract_item_type_from_list_type(first_subtype)
if item_type:
retval["type"] = item_type
if type(None) in args:
retval["required"] = False
return retval
# `list[str]`
if origin == list:
retval = {}
retval["nargs"] = ZERO_OR_MORE
if args[0] in cls.BASIC_TYPES:
retval["type"] = args[0]
return retval
return {}
@classmethod
def _extract_item_type_from_list_type(cls, type_def) -> Optional[type]:
args = get_args(type_def)
if args[0] in cls.BASIC_TYPES:
return args[0]
return None
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/completion.py 0000644 0000000 0000000 00000006002 14644537545 013717 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Shell completion
~~~~~~~~~~~~~~~~
Command and argument completion is a great way to reduce the number of
keystrokes and improve user experience.
To display suggestions when you press :kbd:`tab`, a shell must obtain choices
from your program. It calls the program in a specific environment and expects
it to return a list of relevant choices.
`Argparse` does not support completion out of the box. However, there are
3rd-party apps that do the job, such as argcomplete_ and
python-selfcompletion_.
`Argh` supports only argcomplete_ which doesn't require subclassing
the parser and monkey-patches it instead. Combining `Argh`
with python-selfcompletion_ isn't much harder though: simply use
`SelfCompletingArgumentParser` instead of vanilla `ArgumentParser`.
See installation details and gotchas in the documentation of the 3rd-party app
you've chosen for the completion backend.
`Argh` automatically enables completion if argcomplete_ is available
(see :attr:`COMPLETION_ENABLED`). If completion is undesirable in given app by
design, it can be turned off by setting ``completion=False``
in :func:`argh.dispatching.dispatch`.
Note that you don't *have* to add completion via `Argh`; it doesn't matter
whether you let it do it for you or use the underlying API.
.. _argcomplete: https://github.com/kislyuk/argcomplete
.. _python-selfcompletion: https://github.com/dbarnett/python-selfcompletion
Argument-level completion
-------------------------
Argcomplete_ supports custom "completers". The documentation suggests adding
the completer as an attribute of the argument parser action::
parser.add_argument("--env-var1").completer = EnvironCompleter
However, this doesn't fit the normal `Argh`-assisted workflow.
It is recommended to use the :func:`~argh.decorators.arg` decorator::
@arg("--env-var1", completer=EnvironCompleter)
def func(...):
...
"""
import logging
import os
from argparse import ArgumentParser
COMPLETION_ENABLED = False
"""
Dynamically set to `True` on load if argcomplete_ was successfully imported.
"""
try:
import argcomplete
except ImportError: # pragma: no cover
argcomplete = None
else:
COMPLETION_ENABLED = True # pragma: no cover
__all__ = ["autocomplete", "COMPLETION_ENABLED"]
logger = logging.getLogger(__package__)
def autocomplete(parser: ArgumentParser) -> None:
"""
Adds support for shell completion via argcomplete_ by patching given
`argparse.ArgumentParser` (sub)class.
If completion is not enabled, logs a debug-level message.
"""
if COMPLETION_ENABLED:
argcomplete.autocomplete(parser)
elif "bash" in os.getenv("SHELL", ""):
logger.debug("Bash completion is not available. Please install argcomplete.")
else:
pass
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/constants.py 0000644 0000000 0000000 00000006631 14644537545 013572 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Constants
~~~~~~~~~
"""
import argparse
__all__ = (
"ATTR_NAME",
"ATTR_ALIASES",
"ATTR_ARGS",
"ATTR_WRAPPED_EXCEPTIONS",
"ATTR_WRAPPED_EXCEPTIONS_PROCESSOR",
"PARSER_FORMATTER",
"DEFAULT_ARGUMENT_TEMPLATE",
"DEST_FUNCTION",
"CustomFormatter",
)
#
# Names of function attributes where Argh stores command behaviour
#
#: explicit command name (differing from function name)
ATTR_NAME = "argh_name"
#: alternative command names
ATTR_ALIASES = "argh_aliases"
#: declared arguments
ATTR_ARGS = "argh_args"
#: list of exception classes that should be wrapped and printed as results
ATTR_WRAPPED_EXCEPTIONS = "argh_wrap_errors"
#: a function to preprocess the exception object when it is wrapped
ATTR_WRAPPED_EXCEPTIONS_PROCESSOR = "argh_wrap_errors_processor"
#
# Dest names in parser defaults
#
#: dest name for a function mapped to given endpoint (goes to Namespace obj)
DEST_FUNCTION = "function"
#
# Other library-wide stuff
#
class CustomFormatter(
argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter
):
"""
A slightly customised :class:`argparse.ArgumentDefaultsHelpFormatter`
+ :class:`argparse.RawDescriptionHelpFormatter`.
"""
def _expand_help(self, action):
"""
This method is copied verbatim from ArgumentDefaultsHelpFormatter with
a couple of lines added just before the end. Reason: we need to
`repr()` default values instead of simply inserting them as is.
This helps notice, for example, an empty string as the default value;
moreover, it prevents breaking argparse due to logical quirks inside
of its formatters.
Ideally this could be achieved by simply defining
:attr:`DEFAULT_ARGUMENT_TEMPLATE` as ``{default!r}`` but unfortunately
argparse only supports the old printf syntax.
"""
params = dict(vars(action), prog=self._prog)
for name in list(params):
if params[name] is argparse.SUPPRESS:
del params[name]
for name in list(params):
if hasattr(params[name], "__name__"):
params[name] = params[name].__name__
if params.get("choices") is not None:
choices_str = ", ".join([str(c) for c in params["choices"]])
params["choices"] = choices_str
# XXX this is added in Argh vs. argparse.ArgumentDefaultsHelpFormatter
# (avoiding empty strings, otherwise Argparse would die with
# an IndexError in _format_action)
#
if "default" in params:
if params["default"] is None:
params["default"] = "-"
else:
params["default"] = repr(params["default"])
#
# /
return self._get_help_string(action) % params
#: Default formatter (:class:`CustomFormatter`) to be used in implicitly
#: instantiated ArgumentParser.
PARSER_FORMATTER = CustomFormatter
DEFAULT_ARGUMENT_TEMPLATE = "%(default)s"
"""
Default template of argument help message (see issue #64).
The template ``%(default)s`` is used by `argparse` to display the argument's
default value.
"""
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/decorators.py 0000644 0000000 0000000 00000014473 14644537545 013726 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Command decorators
~~~~~~~~~~~~~~~~~~
"""
from typing import Callable, List, Optional, Type
from argh.constants import (
ATTR_ALIASES,
ATTR_ARGS,
ATTR_NAME,
ATTR_WRAPPED_EXCEPTIONS,
ATTR_WRAPPED_EXCEPTIONS_PROCESSOR,
)
from argh.dto import ParserAddArgumentSpec
from argh.utils import CliArgToFuncArgGuessingError, naive_guess_func_arg_name
__all__ = ["aliases", "named", "arg", "wrap_errors"]
def named(new_name: str) -> Callable:
"""
Sets given string as command name instead of the function name.
The string is used verbatim without further processing.
Usage::
@named("load")
def do_load_some_stuff_and_keep_the_original_function_name(args):
...
The resulting command will be available only as ``load``. To add aliases
without renaming the command, check :func:`aliases`.
.. versionadded:: 0.19
"""
def wrapper(func: Callable) -> Callable:
setattr(func, ATTR_NAME, new_name)
return func
return wrapper
def aliases(*names: List[str]) -> Callable:
"""
Defines alternative command name(s) for given function (along with its
original name). Usage::
@aliases("co", "check")
def checkout(args):
...
The resulting command will be available as ``checkout``, ``check`` and ``co``.
.. versionadded:: 0.19
"""
def wrapper(func: Callable) -> Callable:
setattr(func, ATTR_ALIASES, names)
return func
return wrapper
def arg(*args: str, **kwargs) -> Callable:
"""
Declares an argument for given function. Does not register the function
anywhere, nor does it modify the function in any way.
The signature of the decorator matches that of
:meth:`argparse.ArgumentParser.add_argument`, only some keywords are not
required if they can be easily guessed (e.g. you don't have to specify type
or action when an `int` or `bool` default value is supplied).
.. note::
`completer` is an exception; it's not accepted by
`add_argument()` but instead meant to be assigned to the
action returned by that method, see
https://kislyuk.github.io/argcomplete/#specifying-completers
for details.
Typical use case: in combination with ordinary function signatures to add
details that cannot be expressed with that syntax (e.g. help message).
Usage::
from argh import arg
@arg("path", help="path to the file to load")
@arg("--format", choices=["yaml","json"])
@arg("-v", "--verbosity", choices=range(0,3), default=2)
def load(
path: str,
something: str | None = None,
format: str = "json",
dry_run: bool = False,
verbosity: int = 1
) -> None:
loaders = {"json": json.load, "yaml": yaml.load}
loader = loaders[args.format]
data = loader(args.path)
if not args.dry_run:
if verbosity < 1:
print("saving to the database")
put_to_database(data)
In this example:
- `path` declaration is extended with `help`;
- `format` declaration is extended with `choices`;
- `dry_run` declaration is not duplicated;
- `verbosity` is extended with `choices` and the default value is
overridden. (If both function signature and `@arg` define a default
value for an argument, `@arg` wins.)
.. note::
It is recommended to avoid using this decorator unless there's no way
to tune the argument's behaviour or presentation using ordinary
function signatures. Readability counts, don't repeat yourself.
The decorator is likely to be deprecated in the upcoming versions
of Argh in favour of typing hints; see :doc:`the_story`.
"""
def wrapper(func: Callable) -> Callable:
if not args:
raise CliArgToFuncArgGuessingError("at least one CLI arg must be defined")
if "dest" in kwargs:
func_arg_name = kwargs.pop("dest")
else:
func_arg_name = naive_guess_func_arg_name(args)
cli_arg_names = [name.replace("_", "-") for name in args]
completer = kwargs.pop("completer", None)
spec = ParserAddArgumentSpec.make_from_kwargs(
func_arg_name=func_arg_name,
cli_arg_names=cli_arg_names,
parser_add_argument_kwargs=kwargs,
)
if completer:
spec.completer = completer
declared_args = getattr(func, ATTR_ARGS, [])
# The innermost decorator is called first but appears last in the code.
# We need to preserve the expected order of positional arguments, so
# the outermost decorator inserts its value before the innermost's:
declared_args.insert(0, spec)
setattr(func, ATTR_ARGS, declared_args)
return func
return wrapper
def wrap_errors(
errors: Optional[List[Type[Exception]]] = None,
processor: Optional[Callable] = None,
*args,
) -> Callable:
"""
Decorator. Wraps given exceptions into
:class:`~argh.exceptions.CommandError`. Usage::
@wrap_errors([AssertionError])
def foo(x=None, y=None):
assert x or y, "x or y must be specified"
If the assertion fails, its message will be correctly printed and the
stack hidden. This helps to avoid boilerplate code.
:param errors:
A list of exception classes to catch.
:param processor:
A callable that expects the exception object and returns a string.
For example, this renders all wrapped errors in red colour::
from termcolor import colored
def failure(err):
return colored(str(err), "red")
@wrap_errors(processor=failure)
def my_command(...):
...
"""
def wrapper(func: Callable):
if errors:
setattr(func, ATTR_WRAPPED_EXCEPTIONS, errors)
if processor:
setattr(func, ATTR_WRAPPED_EXCEPTIONS_PROCESSOR, processor)
return func
return wrapper
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/dispatching.py 0000644 0000000 0000000 00000043100 14644537545 014043 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Dispatching
~~~~~~~~~~~
"""
import argparse
import inspect
import io
import sys
import warnings
from types import GeneratorType
from typing import IO, Any, Callable, Dict, Iterator, List, Optional, Tuple
from argh.assembling import NameMappingPolicy, add_commands, set_default_command
from argh.completion import autocomplete
from argh.constants import (
ATTR_WRAPPED_EXCEPTIONS,
ATTR_WRAPPED_EXCEPTIONS_PROCESSOR,
DEST_FUNCTION,
PARSER_FORMATTER,
)
from argh.exceptions import CommandError, DispatchingError
__all__ = [
"ArghNamespace",
"dispatch",
"dispatch_command",
"dispatch_commands",
"parse_and_resolve",
"run_endpoint_function",
"PARSER_FORMATTER",
"EntryPoint",
]
class ArghNamespace(argparse.Namespace):
"""
A namespace object which collects the stack of functions.
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._functions_stack: List[Callable] = []
def __setattr__(self, key: str, value: Any) -> None:
if key == DEST_FUNCTION:
# don't register the function under DEST_FUNCTION name.
# If `ArgumentParser.parse_known_args()` sees that we already have
# such attribute, it skips it. However, it goes from the topmost
# parser to subparsers. We need the function mapped to the
# subparser. So we fool the `ArgumentParser` and pretend that we
# didn't get a DEST_FUNCTION attribute; however, in fact we collect
# all its values in a stack. The last item in the stack would be
# the function mapped to the innermost parser — the one we need.
self._functions_stack.append(value)
else:
super().__setattr__(key, value)
def get_function(self) -> Callable:
return self._functions_stack[-1]
def dispatch(
parser: argparse.ArgumentParser,
argv: Optional[List[str]] = None,
add_help_command: bool = False,
completion: bool = True,
output_file: IO = sys.stdout,
errors_file: IO = sys.stderr,
raw_output: bool = False,
namespace: Optional[argparse.Namespace] = None,
skip_unknown_args: bool = False,
always_flush: bool = False,
) -> Optional[str]:
"""
Parses given list of arguments using given parser, calls the relevant
function and prints the result.
Internally calls :func:`~argh.dispatching.parse_and_resolve` and then
:func:`~argh.dispatching.run_endpoint_function`.
:param parser:
the ArgumentParser instance.
:param argv:
a list of strings representing the arguments. If `None`, ``sys.argv``
is used instead. Default is `None`.
:param add_help_command:
if `True`, converts first positional argument "help" to a keyword
argument so that ``help foo`` becomes ``foo --help`` and displays usage
information for "foo". Default is `False`.
.. versionchanged:: 0.30
The default value is now ``False`` instead of ``True``.
.. deprecated:: 0.30
This argument will be removed in v.0.31. The user is expected to
use ``--help`` instead of ``help``.
:param output_file:
A file-like object for output. If `None`, the resulting lines are
collected and returned as a string. Default is ``sys.stdout``.
:param errors_file:
Same as `output_file` but for ``sys.stderr``, and `None` is not accepted.
:param raw_output:
If `True`, results are written to the output file raw, without adding
whitespaces or newlines between yielded strings. Default is `False`.
:param completion:
If `True`, shell tab completion is enabled. Default is `True`. (You
will also need to install it.) See :mod:`argh.completion`.
:param skip_unknown_args:
If `True`, unknown arguments do not cause an error
(`ArgumentParser.parse_known_args` is used).
:param namespace:
.. deprecated:: 0.31
This argument will be removed soon after v0.31.
:param always_flush:
If the output stream is not a terminal (i.e. redirected to a file or
another process), it's probably buffered. In most cases it doesn't
matter.
However, if the output of your program is generated with delays
between the lines and you may want to redirect them to another process
and immediately see the results (e.g. `my_app.py | grep something`),
it's a good idea to force flushing of the buffer.
.. versionadded:: 0.31
By default the exceptions are not wrapped and will propagate. The only
exception that is always wrapped is :class:`~argh.exceptions.CommandError`
which is interpreted as an expected event so the traceback is hidden.
You can also mark arbitrary exceptions as "wrappable" by using the
:func:`~argh.decorators.wrap_errors` decorator.
Wrapped exceptions, or other "expected errors" like parse failures,
will cause a SystemExit to be raised.
"""
if namespace:
warnings.warn(
DeprecationWarning(
"The argument `namespace` in `dispatch()` is deprecated. "
"It will be removed in the next minor version after v0.31."
)
)
# TODO: remove in v0.31+/v1.0
if add_help_command: # pragma: nocover
warnings.warn(
DeprecationWarning(
"The argument `add_help_command` in `dispatch()` is deprecated. "
"The user is expected to type `--help` instead of `help`."
)
)
if argv and argv[0] == "help":
argv.pop(0)
argv.append("--help")
endpoint_function, namespace_obj = parse_and_resolve(
parser=parser,
completion=completion,
argv=argv,
namespace=namespace,
skip_unknown_args=skip_unknown_args,
)
if not endpoint_function:
parser.print_usage(output_file)
return None
return run_endpoint_function(
function=endpoint_function,
namespace_obj=namespace_obj,
output_file=output_file,
errors_file=errors_file,
raw_output=raw_output,
always_flush=always_flush,
)
def parse_and_resolve(
parser: argparse.ArgumentParser,
argv: Optional[List[str]] = None,
completion: bool = True,
namespace: Optional[argparse.Namespace] = None,
skip_unknown_args: bool = False,
) -> Tuple[Optional[Callable], argparse.Namespace]:
"""
.. versionadded:: 0.30
Parses CLI arguments and resolves the endpoint function.
:param namespace:
.. deprecated:: 0.31
This argument will be removed soon after v0.31.
"""
if completion:
autocomplete(parser)
if argv is None:
argv = sys.argv[1:]
if not namespace:
namespace = ArghNamespace()
# this will raise SystemExit if parsing fails
if skip_unknown_args:
namespace_obj, unknown_args = parser.parse_known_args(argv, namespace=namespace)
# store unknown args on the namespace
namespace_obj._unknown_args = unknown_args
else:
namespace_obj = parser.parse_args(argv, namespace=namespace)
function = _get_function_from_namespace_obj(namespace_obj)
return function, namespace_obj
def run_endpoint_function(
function: Callable,
namespace_obj: argparse.Namespace,
output_file: IO = sys.stdout,
errors_file: IO = sys.stderr,
raw_output: bool = False,
always_flush: bool = False,
) -> Optional[str]:
"""
.. versionadded:: 0.30
Extracts arguments from the namespace object, calls the endpoint function
and processes its output.
:param always_flush:
Flush the buffer after every line even if `output_file` is not a TTY.
Turn this off if you don't need dynamic output)
"""
lines = _execute_command(function, namespace_obj, errors_file)
return _process_command_output(lines, output_file, raw_output, always_flush)
def _process_command_output(
lines: Iterator[str],
output_file: Optional[IO],
raw_output: bool,
always_flush: bool,
) -> Optional[str]:
out_io: IO
if output_file is None:
# user wants a string; we create an internal temporary file-like object
# and will return its contents as a string
out_io = io.StringIO()
else:
# normally this is stdout; can be any file
out_io = output_file
# this may raise user exceptions, or SystemExit for wrapped exceptions
for line in lines:
# print the line as soon as it is generated to ensure that it is
# displayed to the user before anything else happens, e.g.
# raw_input() is called
out_io.write(str(line))
if not raw_output:
# in most cases user wants one message per line
out_io.write("\n")
# If it's not a terminal (i.e. redirected to a file or another
# process), it's probably buffered. In most cases it doesn't matter
# but if the output is generated with delays between the lines and we
# may want to monitor it (e.g. `my_app.py | grep something`), it's a
# good idea to force flushing.
if always_flush:
out_io.flush()
if output_file is None:
# user wanted a string; return contents of our temporary file-like obj
out_io.seek(0)
return out_io.read()
return None
def _get_function_from_namespace_obj(
namespace_obj: argparse.Namespace,
) -> Optional[Callable]:
if isinstance(namespace_obj, ArghNamespace):
# our special namespace object keeps the stack of assigned functions
try:
function = namespace_obj.get_function()
except (AttributeError, IndexError):
return None
else:
# a custom (probably vanilla) namespace object keeps the last assigned
# function; this may be wrong but at least something may work
if not hasattr(namespace_obj, DEST_FUNCTION):
return None
function = getattr(namespace_obj, DEST_FUNCTION)
if not hasattr(function, "__call__"):
return None
return function
def _execute_command(
function: Callable, namespace_obj: argparse.Namespace, errors_file: IO
) -> Iterator[str]:
"""
Assumes that `function` is a callable. Tries different approaches
to call it (with `namespace_obj` or with ordinary signature).
Yields the results line by line.
If :class:`~argh.exceptions.CommandError` is raised, its message is
written to the error file, and a SystemExit is raised.
All other exceptions propagate unless marked as wrappable
by :func:`wrap_errors`.
"""
# the function is nested to catch certain exceptions (see below)
def _call():
# Actually call the function
# namespace -> dictionary
def _flat_key(key):
return key.replace("-", "_")
values_by_arg_name = dict(
(_flat_key(k), v) for k, v in vars(namespace_obj).items()
)
# filter the namespace variables so that only those expected
# by the actual function will pass
func_signature = inspect.signature(function)
func_params = func_signature.parameters.values()
positional_names = [
p.name
for p in func_params
if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
]
kwonly_names = [p.name for p in func_params if p.kind == p.KEYWORD_ONLY]
varargs_names = [p.name for p in func_params if p.kind == p.VAR_POSITIONAL]
positional_values = [values_by_arg_name[name] for name in positional_names]
values_by_name = dict((k, values_by_arg_name[k]) for k in kwonly_names)
# *args
if varargs_names:
value = varargs_names[0]
positional_values += values_by_arg_name[value]
# **kwargs
if any(p for p in func_params if p.kind == p.VAR_KEYWORD):
not_kwargs = (
[DEST_FUNCTION] + positional_names + varargs_names + kwonly_names
)
for k in vars(namespace_obj):
normalized_k = _flat_key(k)
if k.startswith("_") or normalized_k in not_kwargs:
continue
values_by_name[normalized_k] = getattr(namespace_obj, k)
result = function(*positional_values, **values_by_name)
# Yield the results
if isinstance(result, (GeneratorType, list, tuple)):
# yield each line ASAP, convert CommandError message to a line
for line in result:
yield line
else:
# yield non-empty non-iterable result as a single line
if result is not None:
yield result
wrappable_exceptions = [CommandError]
wrappable_exceptions += getattr(function, ATTR_WRAPPED_EXCEPTIONS, [])
def default_exception_processor(exc: Exception) -> str:
return f"{exc.__class__.__name__}: {exc}"
try:
result = _call()
for line in result:
yield line
except tuple(wrappable_exceptions) as exc:
processor = getattr(
function, ATTR_WRAPPED_EXCEPTIONS_PROCESSOR, default_exception_processor
)
errors_file.write(str(processor(exc)))
errors_file.write("\n")
# Use code from CommandError if available, otherwise default to 1
code = exc.code if isinstance(exc, CommandError) and exc.code is not None else 1
sys.exit(code)
def dispatch_command(
function: Callable, *args, old_name_mapping_policy=True, **kwargs
) -> None:
"""
A wrapper for :func:`dispatch` that creates a one-command parser.
Uses :attr:`argh.constants.PARSER_FORMATTER`.
:param old_name_mapping_policy:
.. versionadded:: 0.31
If `True`, sets the default argument naming policy to
`~argh.assembling.NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT`, otherwise
to `~argh.assembling.NameMappingPolicy.BY_NAME_IF_KWONLY`.
.. warning:: tho default will be changed to `False` in v.0.33 (or v.1.0).
This::
dispatch_command(foo)
...is a shortcut for::
parser = ArgumentParser()
set_default_command(parser, foo, name_mapping_policy=...)
dispatch(parser)
This function can be also used as a decorator::
@dispatch_command
def main(foo: int = 123) -> int:
return foo + 1
"""
if old_name_mapping_policy:
name_mapping_policy = NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT
else:
name_mapping_policy = NameMappingPolicy.BY_NAME_IF_KWONLY
parser = argparse.ArgumentParser(formatter_class=PARSER_FORMATTER)
set_default_command(parser, function, name_mapping_policy=name_mapping_policy)
dispatch(parser, *args, **kwargs)
def dispatch_commands(
functions: List[Callable], *args, old_name_mapping_policy=True, **kwargs
) -> None:
"""
A wrapper for :func:`dispatch` that creates a parser, adds commands to
the parser and dispatches them.
Uses :attr:`PARSER_FORMATTER`.
:param old_name_mapping_policy:
.. versionadded:: 0.31
If `True`, sets the default argument naming policy to
`~argh.assembling.NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT`, otherwise
to `~argh.assembling.NameMappingPolicy.BY_NAME_IF_KWONLY`.
.. warning:: tho default will be changed to `False` in v.0.33 (or v.1.0).
This::
dispatch_commands([foo, bar])
...is a shortcut for::
parser = ArgumentParser()
add_commands(parser, [foo, bar], name_mapping_policy=...)
dispatch(parser)
"""
if old_name_mapping_policy:
name_mapping_policy = NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT
else:
name_mapping_policy = NameMappingPolicy.BY_NAME_IF_KWONLY
parser = argparse.ArgumentParser(formatter_class=PARSER_FORMATTER)
add_commands(parser, functions, name_mapping_policy=name_mapping_policy)
dispatch(parser, *args, **kwargs)
class EntryPoint:
"""
An object to which functions can be attached and then dispatched.
When called with an argument, the argument (a function) is registered
at this entry point as a command.
When called without an argument, dispatching is triggered with all
previously registered commands.
Usage::
from argh import EntryPoint
app = EntryPoint("main", {"description": "This is a cool app"})
@app
def ls() -> Iterator[int]:
for i in range(10):
yield i
@app
def greet() -> str:
return "hello"
if __name__ == "__main__":
app()
"""
def __init__(
self, name: Optional[str] = None, parser_kwargs: Optional[Dict[str, Any]] = None
) -> None:
self.name = name or "unnamed"
self.commands: List[Callable] = []
self.parser_kwargs = parser_kwargs or {}
def __call__(self, function: Optional[Callable] = None):
if function:
self._register_command(function)
return function
return self._dispatch()
def _register_command(self, function: Callable) -> None:
self.commands.append(function)
def _dispatch(self) -> None:
if not self.commands:
raise DispatchingError(f'no commands for entry point "{self.name}"')
parser = argparse.ArgumentParser(**self.parser_kwargs)
add_commands(parser, self.commands)
dispatch(parser)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/dto.py 0000644 0000000 0000000 00000005401 14644537545 012336 0 ustar 00 """
Data transfer objects for internal usage.
"""
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Type, Union
class NotDefined:
"""
Specifies that an argument should not be passed to
ArgumentParser.add_argument(), even as None
"""
@dataclass
class ParserAddArgumentSpec:
"""
DTO, maps CLI arg(s) onto a function arg.
Ends up in ArgumentParser.add_argument().
"""
func_arg_name: Optional[str] # TODO: make it required (needs rearranging the logic)
cli_arg_names: List[str]
is_required: Union[bool, Type[NotDefined]] = NotDefined
default_value: Any = NotDefined
nargs: Optional[str] = None
other_add_parser_kwargs: Dict[str, Any] = field(default_factory=dict)
# https://kislyuk.github.io/argcomplete/#specifying-completers
completer: Optional[Callable] = None
def update(self, other: "ParserAddArgumentSpec") -> None:
for name in other.cli_arg_names:
if name not in self.cli_arg_names:
self.cli_arg_names.append(name)
if other.is_required != NotDefined:
self.is_required = other.is_required
if other.default_value != NotDefined:
self.default_value = other.default_value
if other.nargs:
self.nargs = other.nargs
if other.completer:
self.completer = other.completer
self.other_add_parser_kwargs.update(other.other_add_parser_kwargs)
def get_all_kwargs(self) -> Dict[str, Any]:
kwargs: Dict[str, Any] = {}
if self.is_required != NotDefined:
kwargs["required"] = self.is_required
if self.default_value != NotDefined:
kwargs["default"] = self.default_value
if self.nargs:
kwargs["nargs"] = self.nargs
return dict(kwargs, **self.other_add_parser_kwargs)
@classmethod
def make_from_kwargs(
cls, func_arg_name, cli_arg_names, parser_add_argument_kwargs: Dict[str, Any]
) -> "ParserAddArgumentSpec":
"""
Constructs and returns a `ParserAddArgumentSpec` instance
according to keyword arguments according to the
`ArgumentParser.add_argument()` signature.
"""
kwargs_copy = parser_add_argument_kwargs.copy()
instance = cls(
func_arg_name=func_arg_name,
cli_arg_names=cli_arg_names,
)
if "required" in kwargs_copy:
instance.is_required = kwargs_copy.pop("required")
if "nargs" in kwargs_copy:
instance.nargs = kwargs_copy.pop("nargs")
if "default" in kwargs_copy:
instance.default_value = kwargs_copy.pop("default")
if kwargs_copy:
instance.other_add_parser_kwargs = kwargs_copy
return instance
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/exceptions.py 0000644 0000000 0000000 00000003403 14644537545 013731 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Exceptions
~~~~~~~~~~
"""
class AssemblingError(Exception):
"""
Raised if the parser could not be configured due to malformed
or conflicting command declarations.
"""
class DispatchingError(Exception):
"""
Raised if the dispatching could not be completed due to misconfiguration
which could not be determined on an earlier stage.
"""
class CommandError(Exception):
"""
Intended to be raised from within a command. The dispatcher wraps this
exception by default and prints its message without traceback, then exits
with exit code 1.
Useful for print-and-exit tasks when you expect a failure and don't want
to startle the ordinary user by the cryptic output.
Consider the following example::
def foo(args):
try:
...
except KeyError as e:
print(u"Could not fetch item: {0}".format(e))
sys.exit(1)
It is exactly the same as::
def bar(args):
try:
...
except KeyError as e:
raise CommandError(u"Could not fetch item: {0}".format(e))
To customize the exit status, pass an integer (as per ``sys.exit()``) to
the ``code`` keyword arg.
This exception can be safely used in both print-style and yield-style
commands (see :doc:`tutorial`).
"""
def __init__(self, *args, code=None):
self.code = code
super(CommandError, self).__init__(*args)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/helpers.py 0000644 0000000 0000000 00000004321 14644537545 013212 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Helpers
~~~~~~~
"""
import argparse
from typing import Optional, Sequence
from argh.assembling import add_commands, set_default_command
from argh.completion import autocomplete
from argh.dispatching import PARSER_FORMATTER, ArghNamespace, dispatch
__all__ = ["ArghParser"]
class ArghParser(argparse.ArgumentParser):
"""
A subclass of :class:`argparse.ArgumentParser` with support for and a
couple of convenience methods.
All methods are but wrappers for stand-alone functions
:func:`~argh.assembling.add_commands`,
:func:`~argh.completion.autocomplete` and
:func:`~argh.dispatching.dispatch`.
Uses :attr:`~argh.dispatching.PARSER_FORMATTER`.
"""
def __init__(self, *args, **kwargs) -> None:
kwargs.setdefault("formatter_class", PARSER_FORMATTER)
super().__init__(*args, **kwargs)
def set_default_command(self, *args, **kwargs) -> None:
"Wrapper for :func:`~argh.assembling.set_default_command`."
return set_default_command(self, *args, **kwargs)
def add_commands(self, *args, **kwargs) -> None:
"Wrapper for :func:`~argh.assembling.add_commands`."
return add_commands(self, *args, **kwargs)
def autocomplete(self) -> None:
"Wrapper for :func:`~argh.completion.autocomplete`."
return autocomplete(self)
def dispatch(self, *args, **kwargs) -> Optional[str]:
"Wrapper for :func:`~argh.dispatching.dispatch`."
return dispatch(self, *args, **kwargs)
def parse_args(
self,
args: Optional[Sequence[str]] = None,
namespace=None,
):
"""
Wrapper for :meth:`argparse.ArgumentParser.parse_args`. If `namespace`
is not defined, :class:`argh.dispatching.ArghNamespace` is used.
This is required for functions to be properly used as commands.
"""
namespace = namespace or ArghNamespace()
return super().parse_args(args, namespace)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/interaction.py 0000644 0000000 0000000 00000004513 14644537545 014072 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Interaction
~~~~~~~~~~~
"""
from typing import Optional
__all__ = ["confirm"]
MAX_CONFIRM_ITERATIONS = 3
def confirm(
action: str, default: Optional[bool] = None, skip: bool = False
) -> Optional[bool]:
"""
A shortcut for typical confirmation prompt.
:param action:
a string describing the action, e.g. "Apply changes". A question mark
will be appended.
:param default:
`bool` or `None`. Determines what happens when user hits :kbd:`Enter`
without typing in a choice. If `True`, default choice is "yes". If
`False`, it is "no". If `None`, the prompt keeps reappearing until user
types in a choice (not necessarily acceptable) or until the number of
iteration reaches the limit. Default is `None`.
:param skip:
`bool`; if `True`, no interactive prompt is used and default choice is
returned (useful for batch mode). Default is `False`.
Usage::
def delete(key, *, silent=False):
item = db.get(Item, args.key)
if confirm(f"Delete {item.title}", default=True, skip=silent):
item.delete()
print("Item deleted.")
else:
print("Operation cancelled.")
Returns `None` on `KeyboardInterrupt` event.
"""
if skip:
return default
# marking the default value with a capital letter
defaults = {
None: ("y", "n"),
True: ("Y", "n"),
False: ("y", "N"),
}
label_yes, label_no = defaults[default]
prompt = f"{action}? ({label_yes}/{label_no})"
choice = None
try:
if default is None:
cnt = 1
while not choice and cnt < MAX_CONFIRM_ITERATIONS:
choice = input(prompt)
cnt += 1
else:
choice = input(prompt)
except KeyboardInterrupt:
return None
if choice in ("yes", "y", "Y"):
return True
if choice in ("no", "n", "N"):
return False
if default is not None:
return default
return None
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/py.typed 0000644 0000000 0000000 00000000032 14644537545 012670 0 ustar 00 # Marker file for PEP-561
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/src/argh/utils.py 0000644 0000000 0000000 00000005662 14644537545 012721 0 ustar 00 #
# Copyright © 2010—2023 Andrey Mikhaylenko and contributors
#
# This file is part of Argh.
#
# Argh is free software under terms of the GNU Lesser
# General Public License version 3 (LGPLv3) as published by the Free
# Software Foundation. See the file README.rst for copying conditions.
#
"""
Utilities
~~~~~~~~~
"""
import argparse
import re
from typing import Tuple
def get_subparsers(
parser: argparse.ArgumentParser, create: bool = False
) -> argparse._SubParsersAction:
"""
Returns the `argparse._SubParsersAction` instance for given
:class:`argparse.ArgumentParser` instance as would have been returned by
:meth:`argparse.ArgumentParser.add_subparsers`. The problem with the latter
is that it only works once and raises an exception on the second attempt,
and the public API seems to lack a method to get *existing* subparsers.
:param create:
If `True`, creates the subparser if it does not exist. Default if
`False`.
"""
# note that ArgumentParser._subparsers is *not* what is returned by
# ArgumentParser.add_subparsers().
if parser._subparsers:
actions = [
a for a in parser._actions if isinstance(a, argparse._SubParsersAction)
]
return actions[0]
if create:
return parser.add_subparsers()
raise SubparsersNotDefinedError()
def unindent(text: str) -> str:
"""
Given a multi-line string, decreases indentation of all lines so that the
first non-empty line has zero indentation and the remaining lines are
adjusted accordingly.
"""
match = re.match("(^|\n)( +)", text)
if not match:
return text
first_line_indentation = match.group(2)
depth = len(first_line_indentation)
return re.sub(rf"(^|\n) {{{depth}}}", "\\1", text)
class SubparsersNotDefinedError(Exception): ...
def naive_guess_func_arg_name(option_strings: Tuple[str, ...]) -> str:
def _opt_to_func_arg_name(opt: str) -> str:
return opt.strip("-").replace("-", "_")
if len(option_strings) == 1:
# the only CLI arg name; adapt and use
return _opt_to_func_arg_name(option_strings[0])
are_args_positional = [not arg.startswith("-") for arg in option_strings]
if any(are_args_positional) and not all(are_args_positional):
raise MixedPositionalAndOptionalArgsError
if all(are_args_positional):
raise TooManyPositionalArgumentNames
for option_string in option_strings:
if option_string.startswith("--"):
# prefixed long; adapt and use
return _opt_to_func_arg_name(option_string[2:])
raise CliArgToFuncArgGuessingError(
f"Unable to convert opt strings {option_strings} to func arg name"
)
class ArghError(Exception): ...
class CliArgToFuncArgGuessingError(ArghError): ...
class TooManyPositionalArgumentNames(CliArgToFuncArgGuessingError): ...
class MixedPositionalAndOptionalArgsError(CliArgToFuncArgGuessingError): ...
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/__init__.py 0000644 0000000 0000000 00000000000 14644537545 012727 0 ustar 00 ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/base.py 0000644 0000000 0000000 00000004046 14644537545 012120 0 ustar 00 """
Common stuff for tests
~~~~~~~~~~~~~~~~~~~~~~
"""
import io
import os
import sys
from collections import namedtuple
from argh import ArghParser
# hacky constructor for default exit value
def CmdResult(out, err, exit_code=None):
_CmdResult = namedtuple("CmdResult", ("out", "err", "exit_code"))
return _CmdResult(out, err, exit_code)
class DebugArghParser(ArghParser):
"(does not print stuff to stderr on exit)"
def exit(self, status=0, message=None):
raise SystemExit(message)
def error(self, message):
self.exit(2, message)
def call_cmd(parser, command_string, **kwargs):
if hasattr(command_string, "split"):
args = command_string.split()
else:
args = command_string
io_out = io.StringIO()
io_err = io.StringIO()
if "output_file" not in kwargs:
kwargs["output_file"] = io_out
kwargs["errors_file"] = io_err
try:
result = parser.dispatch(args, **kwargs)
except SystemExit as e:
result = None
exit_code = e.code or 0 # e.code may be None
else:
exit_code = None
if kwargs.get("output_file") is None:
return CmdResult(out=result, err=io_err.read(), exit_code=exit_code)
io_out.seek(0)
io_err.seek(0)
return CmdResult(out=io_out.read(), err=io_err.read(), exit_code=exit_code)
def run(parser, command_string, kwargs=None, exit=False):
"""Calls the command and returns CmdResult(out, err, exit status),
with exit status None if no SystemExit was raised.
:exit:
if set to `True` and a SystemExit is raised, the status code is returned;
if the exception is not raised, an AssertionError is raised.
"""
kwargs = kwargs or {}
result = call_cmd(parser, command_string, **kwargs)
if exit:
if result.exit_code is None:
raise AssertionError("Did not exit")
return result.exit_code
return result
def get_usage_string(definitions="{cmd} ..."):
prog = os.path.basename(sys.argv[0])
return "usage: " + prog + " [-h] " + definitions + "\n\n"
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_assembling.py 0000644 0000000 0000000 00000066712 14644537545 014401 0 ustar 00 """
Unit Tests For Assembling Phase
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import argparse
from typing import Literal, Optional
from unittest.mock import MagicMock, call, patch
import pytest
import argh
from argh.assembling import AssemblingError, NameMappingPolicy
from argh.dto import ParserAddArgumentSpec
def test_guess_type_from_choices():
given = ParserAddArgumentSpec(
"foo", ["foo"], other_add_parser_kwargs={"choices": [1, 2]}
)
guessed = {"type": int}
assert guessed == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
# do not override a guessable param if already explicitly defined
given = ParserAddArgumentSpec(
"foo",
["foo"],
other_add_parser_kwargs={
"option_strings": ["foo"],
"choices": [1, 2],
"type": "NO_MATTER_WHAT",
},
)
guessed = {}
assert guessed == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
def test_guess_type_from_default():
given = ParserAddArgumentSpec("foo", ["foo"], default_value=1)
guessed = {"type": int}
assert guessed == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
# do not override a guessable param if already explicitly defined
given = ParserAddArgumentSpec(
"foo",
["foo"],
default_value=1,
other_add_parser_kwargs={
"type": "NO_MATTER_WHAT",
},
)
guessed = {}
assert guessed == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
def test_guess_action_from_default():
# positional, default True → ignore
given = ParserAddArgumentSpec("foo", ["foo"], default_value=False)
assert {} == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
# named, default True → store_false
given = ParserAddArgumentSpec("foo", ["--foo"], default_value=False)
guessed = {"action": "store_true"}
assert guessed == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
# positional, default False → ignore
given = ParserAddArgumentSpec("foo", ["foo"], default_value=True)
assert {} == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
# named, True → store_false
given = ParserAddArgumentSpec("foo", ["--foo"], default_value=True)
guessed = {"action": "store_false"}
assert guessed == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
# do not override a guessable param if already explicitly defined
given = ParserAddArgumentSpec(
"foo",
["foo"],
default_value=False,
other_add_parser_kwargs={
"action": "NO_MATTER_WHAT",
},
)
guessed = {}
assert guessed == argh.assembling.guess_extra_parser_add_argument_spec_kwargs(given)
def test_positional_with_default_int():
def func(pos_int_default=123): ...
parser = argh.ArghParser(prog="test")
parser.set_default_command(
func, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_KWONLY
)
assert parser.format_usage() == "usage: test [-h] [pos-int-default]\n"
assert "pos-int-default 123" in parser.format_help()
def test_positional_with_default_bool():
def func(pos_bool_default=False): ...
parser = argh.ArghParser(prog="test")
parser.set_default_command(
func, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_KWONLY
)
assert parser.format_usage() == "usage: test [-h] [pos-bool-default]\n"
assert "pos-bool-default False" in parser.format_help()
def test_set_default_command():
def func(**kwargs):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
[
ParserAddArgumentSpec(
func_arg_name="foo",
cli_arg_names=("foo",),
nargs=argparse.ONE_OR_MORE,
other_add_parser_kwargs={"choices": [1, 2], "help": "me"},
),
ParserAddArgumentSpec(
func_arg_name="bar", cli_arg_names=("-b", "--bar"), default_value=False
),
],
)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
argh.set_default_command(parser, func)
assert parser.add_argument.mock_calls == [
call("foo", nargs=argparse.ONE_OR_MORE, choices=[1, 2], help="me", type=int),
call(
"-b",
"--bar",
default=False,
action="store_true",
help=argh.constants.DEFAULT_ARGUMENT_TEMPLATE,
),
]
assert parser.set_defaults.mock_calls == [call(function=func)]
def test_set_default_command__parser_error():
def func(foo: str) -> str:
return foo
parser_mock = MagicMock(spec=argparse.ArgumentParser)
parser_mock.add_help = False
parser_mock.add_argument.side_effect = argparse.ArgumentError(
None, "my hat's on fire!"
)
with pytest.raises(argh.AssemblingError):
argh.set_default_command(parser_mock, func)
def test_set_default_command__no_func_args():
# TODO: document in changelog
# XXX breaking change in v0.30!
# Old behaviour: @arg declarations would be passed to add_argument().
# (how the hell would it look like though?)
# New behaviour: @arg declarations are ignored because there's no func
# arg to map them onto.
def func():
pass
setattr(
func,
argh.constants.ATTR_ARGS,
[ParserAddArgumentSpec(func_arg_name="x", cli_arg_names=("-x",))],
)
p = argh.ArghParser()
with pytest.raises(argh.AssemblingError) as excinfo:
p.set_default_command(func)
msg = (
"func: cannot extend argument declarations for an endpoint "
"function that takes no arguments."
)
assert msg in str(excinfo.value)
def test_set_default_command__varargs_vs_positional():
def func(*args):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
[ParserAddArgumentSpec(func_arg_name="x", cli_arg_names=("x",))],
)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
with pytest.raises(
AssemblingError, match="func: argument x does not fit function signature: args"
):
parser.set_default_command(func)
def test_set_default_command__varargs_vs_optional():
def func(*args):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
[ParserAddArgumentSpec(func_arg_name="x", cli_arg_names=("-x",))],
)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
with pytest.raises(
AssemblingError, match="func: argument -x does not fit function signature: args"
):
parser.set_default_command(func)
def test_set_default_command__varkwargs_vs_positional():
def func(**kwargs):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
[ParserAddArgumentSpec(func_arg_name="x", cli_arg_names=("x",))],
)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
parser.set_default_command(func)
assert parser.add_argument.mock_calls == [call("x", help="%(default)s")]
assert parser.set_defaults.mock_calls == [call(function=func)]
def test_set_default_command__varkwargs_vs_optional():
def func(**kwargs):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
[ParserAddArgumentSpec(func_arg_name="x", cli_arg_names=("-x",))],
)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
parser.set_default_command(func)
assert parser.add_argument.mock_calls == [call("-x", help="%(default)s")]
assert parser.set_defaults.mock_calls == [call(function=func)]
def test_set_default_command__declared_vs_signature__names_mismatch():
def func(bar):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
(
ParserAddArgumentSpec(
func_arg_name="x",
cli_arg_names=("foo",),
nargs=argparse.ONE_OR_MORE,
other_add_parser_kwargs={"choices": [1, 2], "help": "me"},
),
),
)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
with pytest.raises(
AssemblingError, match="func: argument foo does not fit function signature: bar"
):
argh.set_default_command(parser, func)
def test_set_default_command__declared_vs_signature__same_name_pos_vs_opt():
def func(foo):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
(ParserAddArgumentSpec(func_arg_name="foo", cli_arg_names=("--foo",)),),
)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
import re
with pytest.raises(
AssemblingError,
match=re.escape(
'func: argument "foo" declared as positional (in function signature) and optional (via decorator)'
),
):
argh.set_default_command(parser, func)
@pytest.fixture()
def big_command_with_everything():
# TODO: split into small tests where we'd check each combo and make sure
# they interact as expected (e.g. pos opt arg gets the short form even if
# there's a pos req arg, etc.)
#
# an arg with a unique first letter per arg type + every combination
# of conflicting first letters per every two arg types:
# - positional required (i.e. without a default value)
# - positional optional (i.e. with a default value)
# - named-only required (i.e. kwonly without a default value)
# - named-only optional (i.e. kwonly with a default value)
def func(
alpha_pos_req,
beta_pos_req,
alpha_pos_opt="alpha",
beta_pos_opt_one="beta one",
beta_pos_opt_two="beta two",
gamma_pos_opt="gamma named",
delta_pos_opt="delta named",
theta_pos_opt="theta named",
*args,
gamma_kwonly_opt="gamma kwonly",
delta_kwonly_req,
epsilon_kwonly_req_one,
epsilon_kwonly_req_two,
zeta_kwonly_opt="zeta kwonly",
**kwargs,
):
return (
alpha_pos_req,
beta_pos_req,
alpha_pos_opt,
beta_pos_opt_one,
beta_pos_opt_two,
gamma_pos_opt,
delta_pos_opt,
theta_pos_opt,
gamma_kwonly_opt,
delta_kwonly_req,
epsilon_kwonly_req_one,
epsilon_kwonly_req_two,
zeta_kwonly_opt,
args,
kwargs,
)
yield func
def test_set_default_command_infer_cli_arg_names_from_func_signature__policy_legacy(
big_command_with_everything,
):
name_mapping_policy = NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
argh.set_default_command(
parser, big_command_with_everything, name_mapping_policy=name_mapping_policy
)
help_tmpl = argh.constants.DEFAULT_ARGUMENT_TEMPLATE
assert parser.add_argument.mock_calls == [
call("alpha-pos-req", help="%(default)s"),
call("beta-pos-req", help="%(default)s"),
call("-a", "--alpha-pos-opt", default="alpha", type=str, help=help_tmpl),
call("--beta-pos-opt-one", default="beta one", type=str, help=help_tmpl),
call("--beta-pos-opt-two", default="beta two", type=str, help=help_tmpl),
call("--gamma-pos-opt", default="gamma named", type=str, help=help_tmpl),
call("--delta-pos-opt", default="delta named", type=str, help=help_tmpl),
call("-t", "--theta-pos-opt", default="theta named", type=str, help=help_tmpl),
call("args", nargs=argparse.ZERO_OR_MORE, help=help_tmpl),
call("--gamma-kwonly-opt", default="gamma kwonly", type=str, help=help_tmpl),
call("delta-kwonly-req", help=help_tmpl),
call("epsilon-kwonly-req-one", help=help_tmpl),
call("epsilon-kwonly-req-two", help=help_tmpl),
call(
"-z", "--zeta-kwonly-opt", default="zeta kwonly", type=str, help=help_tmpl
),
]
assert parser.set_defaults.mock_calls == [
call(function=big_command_with_everything)
]
def test_set_default_command_infer_cli_arg_names_from_func_signature__policy_modern(
big_command_with_everything,
):
name_mapping_policy = NameMappingPolicy.BY_NAME_IF_KWONLY
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_defaults = MagicMock()
argh.set_default_command(
parser, big_command_with_everything, name_mapping_policy=name_mapping_policy
)
help_tmpl = argh.constants.DEFAULT_ARGUMENT_TEMPLATE
assert parser.add_argument.mock_calls == [
call("alpha-pos-req", help="%(default)s"),
call("beta-pos-req", help="%(default)s"),
call(
"alpha-pos-opt",
default="alpha",
nargs=argparse.OPTIONAL,
type=str,
help=help_tmpl,
),
call(
"beta-pos-opt-one",
default="beta one",
nargs=argparse.OPTIONAL,
type=str,
help=help_tmpl,
),
call(
"beta-pos-opt-two",
default="beta two",
nargs=argparse.OPTIONAL,
type=str,
help=help_tmpl,
),
call(
"gamma-pos-opt",
default="gamma named",
nargs=argparse.OPTIONAL,
type=str,
help=help_tmpl,
),
call(
"delta-pos-opt",
default="delta named",
nargs=argparse.OPTIONAL,
type=str,
help=help_tmpl,
),
call(
"theta-pos-opt",
default="theta named",
nargs=argparse.OPTIONAL,
type=str,
help=help_tmpl,
),
call("args", nargs=argparse.ZERO_OR_MORE, help=help_tmpl),
call("--gamma-kwonly-opt", default="gamma kwonly", type=str, help=help_tmpl),
call("--delta-kwonly-req", required=True, help=help_tmpl),
call("--epsilon-kwonly-req-one", required=True, help=help_tmpl),
call("--epsilon-kwonly-req-two", required=True, help=help_tmpl),
call(
"-z", "--zeta-kwonly-opt", default="zeta kwonly", type=str, help=help_tmpl
),
]
assert parser.set_defaults.mock_calls == [
call(function=big_command_with_everything)
]
def test_set_default_command_docstring():
def func():
"docstring"
pass
parser = argh.ArghParser()
argh.set_default_command(parser, func)
assert parser.description == "docstring"
def test_set_default_command__varkwargs_sharing_prefix():
def func(*, alpha: str = "Alpha", aleph: str = "Aleph"): ...
parser = argh.ArghParser()
parser.add_argument = MagicMock()
argh.set_default_command(parser, func)
assert parser.add_argument.mock_calls == [
call("--alpha", default="Alpha", type=str, help="%(default)s"),
call("--aleph", default="Aleph", type=str, help="%(default)s"),
]
def test_add_subparsers_when_default_command_exists():
def one():
return 1
def two():
return 2
def three():
return 3
p = argh.ArghParser()
p.set_default_command(one)
p.add_commands([two, three])
ns_default = p.parse_args([])
ns_explicit_two = p.parse_args(["two"])
ns_explicit_three = p.parse_args(["three"])
assert ns_default.get_function() == one
assert ns_explicit_two.get_function() == two
assert ns_explicit_three.get_function() == three
def test_set_default_command_when_subparsers_exist():
def one():
return 1
def two():
return 2
def three():
return 3
p = argh.ArghParser()
p.add_commands([one, two])
p.set_default_command(three)
ns_default = p.parse_args([])
ns_explicit_one = p.parse_args(["one"])
ns_explicit_two = p.parse_args(["two"])
assert ns_explicit_one.get_function() == one
assert ns_explicit_two.get_function() == two
assert ns_default.get_function() == three
def test_set_add_commands_twice():
def one():
return 1
def two():
return 2
p = argh.ArghParser()
p.add_commands([one])
p.add_commands([two])
ns_explicit_one = p.parse_args(["one"])
ns_explicit_two = p.parse_args(["two"])
assert ns_explicit_one.get_function() == one
assert ns_explicit_two.get_function() == two
def test_add_command_with_group_kwargs_but_no_group_name():
def one():
return 1
p = argh.ArghParser()
err_msg = "`group_kwargs` only makes sense with `group_name`"
with pytest.raises(ValueError, match=err_msg):
p.add_commands([one], group_kwargs={"help": "foo"})
def test_set_default_command_varargs():
def func(*file_paths):
yield ", ".join(file_paths)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
argh.set_default_command(parser, func)
assert parser.add_argument.mock_calls == [
call(
"file-paths",
nargs=argparse.ZERO_OR_MORE,
help=argh.constants.DEFAULT_ARGUMENT_TEMPLATE,
),
]
def test_set_default_command_kwargs():
@argh.arg("foo")
@argh.arg("--bar")
def func(x, **kwargs):
pass
parser = argh.ArghParser()
parser.add_argument = MagicMock()
argh.set_default_command(parser, func)
assert parser.add_argument.mock_calls == [
call("x", help=argh.constants.DEFAULT_ARGUMENT_TEMPLATE),
call("foo", help=argh.constants.DEFAULT_ARGUMENT_TEMPLATE),
call("--bar", help=argh.constants.DEFAULT_ARGUMENT_TEMPLATE),
]
def test_kwonlyargs__policy_legacy():
"Correctly processing required and optional keyword-only arguments"
def cmd(foo_pos, bar_pos, *args, foo_kwonly="foo_kwonly", bar_kwonly):
return (foo_pos, bar_pos, args, foo_kwonly, bar_kwonly)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_default_command(
cmd, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT
)
help_tmpl = argh.constants.DEFAULT_ARGUMENT_TEMPLATE
assert parser.add_argument.mock_calls == [
call("foo-pos", help=help_tmpl),
call("bar-pos", help=help_tmpl),
call("args", nargs=argparse.ZERO_OR_MORE, help=help_tmpl),
call("-f", "--foo-kwonly", default="foo_kwonly", type=str, help=help_tmpl),
call("bar-kwonly", help=help_tmpl),
]
def test_kwonlyargs__policy_modern():
"Correctly processing required and optional keyword-only arguments"
def cmd(foo_pos, bar_pos, *args, foo_kwonly="foo_kwonly", bar_kwonly):
return (foo_pos, bar_pos, args, foo_kwonly, bar_kwonly)
parser = argh.ArghParser()
parser.add_argument = MagicMock()
parser.set_default_command(
cmd, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_KWONLY
)
help_tmpl = argh.constants.DEFAULT_ARGUMENT_TEMPLATE
assert parser.add_argument.mock_calls == [
call("foo-pos", help=help_tmpl),
call("bar-pos", help=help_tmpl),
call("args", nargs=argparse.ZERO_OR_MORE, help=help_tmpl),
call("-f", "--foo-kwonly", default="foo_kwonly", type=str, help=help_tmpl),
call("-b", "--bar-kwonly", required=True, help=help_tmpl),
]
@patch("argh.assembling.COMPLETION_ENABLED", True)
def test_custom_argument_completer():
"Issue #33: Enable custom per-argument shell completion"
def func(foo):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
[
ParserAddArgumentSpec(
func_arg_name="foo", cli_arg_names=("foo",), completer="STUB"
)
],
)
p = argh.ArghParser()
p.set_default_command(func)
assert p._actions[-1].completer == "STUB"
@patch("argh.assembling.COMPLETION_ENABLED", False)
def test_custom_argument_completer_no_backend():
"If completion backend is not available, nothing breaks"
def func(foo):
pass
setattr(
func,
argh.constants.ATTR_ARGS,
[
ParserAddArgumentSpec(
func_arg_name="foo", cli_arg_names=("foo",), completer="STUB"
)
],
)
p = argh.ArghParser()
p.set_default_command(func)
assert not hasattr(p._actions[-1], "completer")
@patch("argh.assembling.add_commands")
def test_add_subcommands(mock_add_commands):
mock_parser = MagicMock()
def get_items():
pass
argh.add_subcommands(
mock_parser,
"db",
[get_items],
title="database commands",
help="CRUD for our silly database",
)
mock_add_commands.assert_called_with(
mock_parser,
[get_items],
group_name="db",
group_kwargs={
"title": "database commands",
"help": "CRUD for our silly database",
},
)
@patch("argh.helpers.autocomplete")
def test_arghparser_autocomplete_method(mock_autocomplete):
p = argh.ArghParser()
p.autocomplete()
mock_autocomplete.assert_called()
def test_is_positional():
with pytest.raises(ValueError, match="Expected at least one"):
argh.assembling._is_positional([])
with pytest.raises(ValueError, match="Expected at least one"):
argh.assembling._is_positional([""])
assert argh.assembling._is_positional(["f"]) is True
assert argh.assembling._is_positional(["foo"]) is True
assert argh.assembling._is_positional(["--foo"]) is False
assert argh.assembling._is_positional(["-f"]) is False
assert argh.assembling._is_positional(["-f", "--foo"]) is False
# this spec is invalid but validation is out of scope of the function
# as it only checks if the first argument has the leading dash
assert argh.assembling._is_positional(["-f", "foo"]) is False
def test_typing_hints_only_used_when_arg_deco_not_used():
@argh.arg("foo", type=int)
def func_decorated(foo: Optional[float]): ...
def func_undecorated(bar: Optional[float]): ...
parser = argparse.ArgumentParser()
parser.add_argument = MagicMock()
argh.set_default_command(parser, func_decorated)
assert parser.add_argument.mock_calls == [
call("foo", type=int, help=argh.constants.DEFAULT_ARGUMENT_TEMPLATE),
]
parser = argparse.ArgumentParser()
parser.add_argument = MagicMock()
argh.set_default_command(parser, func_undecorated)
assert parser.add_argument.mock_calls == [
call(
"bar",
nargs="?",
type=float,
help=argh.constants.DEFAULT_ARGUMENT_TEMPLATE,
),
]
def test_typing_hints_overview():
def func(
alpha,
beta: str,
gamma: Optional[int] = None,
*,
delta: float = 1.5,
epsilon: Optional[int] = 42,
zeta: bool = False,
) -> str:
return f"alpha={alpha}, beta={beta}, gamma={gamma}, delta={delta}, epsilon={epsilon}, zeta={zeta}"
parser = argparse.ArgumentParser()
parser.add_argument = MagicMock()
argh.set_default_command(
parser, func, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_KWONLY
)
_extra_kw = {"help": argh.constants.DEFAULT_ARGUMENT_TEMPLATE}
assert parser.add_argument.mock_calls == [
call("alpha", **_extra_kw),
call("beta", type=str, **_extra_kw),
call("gamma", default=None, nargs="?", type=int, **_extra_kw),
call("-d", "--delta", type=float, default=1.5, **_extra_kw),
call("-e", "--epsilon", type=int, default=42, required=False, **_extra_kw),
call("-z", "--zeta", default=False, action="store_true", **_extra_kw),
]
def test_typing_hints_str__policy_by_name_if_has_default():
def func(alpha: str, beta: str = "N/A", *, gamma: str, delta: str = "N/A") -> str:
return f"alpha={alpha}, beta={beta}, gamma={gamma}, delta={delta}"
parser = argparse.ArgumentParser()
parser.add_argument = MagicMock()
argh.set_default_command(
parser, func, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT
)
_extra_kw = {"help": argh.constants.DEFAULT_ARGUMENT_TEMPLATE}
assert parser.add_argument.mock_calls == [
call("alpha", type=str, **_extra_kw),
call("-b", "--beta", default="N/A", type=str, **_extra_kw),
call("gamma", type=str, **_extra_kw),
call("-d", "--delta", default="N/A", type=str, **_extra_kw),
]
def test_typing_hints_str__policy_by_name_if_kwonly():
def func(alpha: str, beta: str = "N/A", *, gamma: str, delta: str = "N/A") -> str:
return f"alpha={alpha}, beta={beta}, gamma={gamma}, delta={delta}"
parser = argparse.ArgumentParser()
parser.add_argument = MagicMock()
argh.set_default_command(
parser, func, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_KWONLY
)
_extra_kw = {"help": argh.constants.DEFAULT_ARGUMENT_TEMPLATE}
assert parser.add_argument.mock_calls == [
call("alpha", type=str, help=argh.constants.DEFAULT_ARGUMENT_TEMPLATE),
call("beta", type=str, default="N/A", nargs="?", **_extra_kw),
call("-g", "--gamma", required=True, type=str, **_extra_kw),
call("-d", "--delta", default="N/A", type=str, **_extra_kw),
]
def test_typing_hints_bool__policy_by_name_if_has_default():
def func(
alpha: bool, beta: bool = False, *, gamma: bool, delta: bool = False
) -> str:
return f"alpha={alpha}, beta={beta}, gamma={gamma}, delta={delta}"
parser = argparse.ArgumentParser()
parser.add_argument = MagicMock()
argh.set_default_command(
parser, func, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT
)
_extra_kw = {"help": argh.constants.DEFAULT_ARGUMENT_TEMPLATE}
assert parser.add_argument.mock_calls == [
call("alpha", type=bool, **_extra_kw),
call("-b", "--beta", default=False, action="store_true", **_extra_kw),
call("gamma", type=bool, **_extra_kw),
call("-d", "--delta", default=False, action="store_true", **_extra_kw),
]
def test_typing_hints_bool__policy_by_name_if_kwonly():
def func(
alpha: bool, beta: bool = False, *, gamma: bool, delta: bool = False
) -> str:
return f"alpha={alpha}, beta={beta}, gamma={gamma}, delta={delta}"
parser = argparse.ArgumentParser()
parser.add_argument = MagicMock()
argh.set_default_command(
parser, func, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_KWONLY
)
_extra_kw = {"help": argh.constants.DEFAULT_ARGUMENT_TEMPLATE}
assert parser.add_argument.mock_calls == [
call("alpha", type=bool, **_extra_kw),
call("beta", type=bool, default=False, nargs="?", **_extra_kw),
call("-g", "--gamma", required=True, type=bool, **_extra_kw),
call("-d", "--delta", default=False, action="store_true", **_extra_kw),
]
def test_typing_hints_literal():
def func(
name: Literal["Alice", "Bob"], *, greeting: Literal["Hello", "Hi"] = "Hello"
) -> str:
return f"{greeting}, {name}!"
parser = argparse.ArgumentParser()
parser.add_argument = MagicMock()
argh.set_default_command(
parser, func, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_KWONLY
)
_extra_kw = {"help": argh.constants.DEFAULT_ARGUMENT_TEMPLATE}
assert parser.add_argument.mock_calls == [
call("name", choices=("Alice", "Bob"), type=str, **_extra_kw),
call(
"-g",
"--greeting",
choices=("Hello", "Hi"),
type=str,
default="Hello",
**_extra_kw,
),
]
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_completion.py 0000644 0000000 0000000 00000002457 14644537545 014422 0 ustar 00 """
Unit Tests For Autocompletion
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from unittest.mock import patch
import argh
@patch("argh.completion.COMPLETION_ENABLED", True)
@patch("argh.completion.argcomplete")
def test_enabled(mock_argcomplete):
parser = argh.ArghParser()
parser.autocomplete()
mock_argcomplete.autocomplete.assert_called_with(parser)
@patch("argh.completion.COMPLETION_ENABLED", False)
@patch("argh.completion.argcomplete")
@patch("argh.completion.os.getenv")
@patch("argh.completion.logger")
def test_disabled_without_bash(mock_logger, mock_getenv, mock_argcomplete):
mock_getenv.return_value = "/bin/sh"
parser = argh.ArghParser()
parser.autocomplete()
mock_argcomplete.assert_not_called()
mock_logger.debug.assert_not_called()
@patch("argh.completion.COMPLETION_ENABLED", False)
@patch("argh.completion.argcomplete")
@patch("argh.completion.os.getenv")
@patch("argh.completion.logger")
def test_disabled_with_bash(mock_logger, mock_getenv, mock_argcomplete):
mock_getenv.return_value = "/bin/bash"
parser = argh.ArghParser()
parser.autocomplete()
mock_argcomplete.assert_not_called()
mock_getenv.assert_called_with("SHELL", "")
mock_logger.debug.assert_called_with(
"Bash completion is not available. Please install argcomplete."
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_decorators.py 0000644 0000000 0000000 00000005507 14644537545 014415 0 ustar 00 """
Unit Tests For Decorators
~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import pytest
import argh
from argh.dto import ParserAddArgumentSpec
from argh.utils import (
CliArgToFuncArgGuessingError,
MixedPositionalAndOptionalArgsError,
TooManyPositionalArgumentNames,
naive_guess_func_arg_name,
)
def test_aliases():
@argh.aliases("one", "two")
def func():
pass
attr = getattr(func, argh.constants.ATTR_ALIASES)
assert attr == ("one", "two")
def test_arg():
@argh.arg("foo", help="my help", nargs="+")
@argh.arg("--bar", default=1)
def func():
pass
attrs = getattr(func, argh.constants.ATTR_ARGS)
assert attrs == [
ParserAddArgumentSpec(
func_arg_name="foo",
cli_arg_names=["foo"],
nargs="+",
other_add_parser_kwargs={
"help": "my help",
},
),
ParserAddArgumentSpec(
func_arg_name="bar",
cli_arg_names=["--bar"],
default_value=1,
),
]
def test_named():
@argh.named("new-name")
def func():
pass
attr = getattr(func, argh.constants.ATTR_NAME)
assert attr == "new-name"
def test_wrap_errors():
@argh.wrap_errors([KeyError, ValueError])
def func():
pass
attr = getattr(func, argh.constants.ATTR_WRAPPED_EXCEPTIONS)
assert attr == [KeyError, ValueError]
def test_wrap_errors_processor():
@argh.wrap_errors(processor="STUB")
def func():
pass
attr = getattr(func, argh.constants.ATTR_WRAPPED_EXCEPTIONS_PROCESSOR)
assert attr == "STUB"
def test_naive_guess_func_arg_name() -> None:
# none (error)
with pytest.raises(CliArgToFuncArgGuessingError):
argh.arg()(lambda foo: foo)
# positional
assert naive_guess_func_arg_name(("foo",)) == "foo"
# positional — more than one (error)
with pytest.raises(TooManyPositionalArgumentNames):
argh.arg("foo", "bar")(lambda foo: foo)
# option
assert naive_guess_func_arg_name(("-x",)) == "x"
assert naive_guess_func_arg_name(("--foo",)) == "foo"
assert naive_guess_func_arg_name(("--foo", "-f")) == "foo"
assert naive_guess_func_arg_name(("-f", "--foo")) == "foo"
assert naive_guess_func_arg_name(("-x", "--foo", "--bar")) == "foo"
with pytest.raises(CliArgToFuncArgGuessingError):
naive_guess_func_arg_name(("-x", "-y"))
# mixed (errors)
with pytest.raises(MixedPositionalAndOptionalArgsError):
argh.arg("foo", "--foo")(lambda foo: foo)
with pytest.raises(MixedPositionalAndOptionalArgsError):
argh.arg("--foo", "foo")(lambda foo: foo)
with pytest.raises(MixedPositionalAndOptionalArgsError):
argh.arg("-f", "foo")(lambda foo: foo)
with pytest.raises(MixedPositionalAndOptionalArgsError):
argh.arg("foo", "-f")(lambda foo: foo)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_dispatching.py 0000644 0000000 0000000 00000016701 14644537545 014543 0 ustar 00 """
Dispatching tests
~~~~~~~~~~~~~~~~~
"""
import argparse
import io
from unittest.mock import Mock, patch
import pytest
import argh
def _dispatch_and_capture(func, command_string, **kwargs):
if hasattr(command_string, "split"):
args = command_string.split()
else:
args = command_string
_io = io.StringIO()
if "output_file" not in kwargs:
kwargs["output_file"] = _io
result = argh.dispatch_command(func, args, **kwargs)
if kwargs.get("output_file") is None:
return result
else:
_io.seek(0)
return _io.read()
def run_func(func, command_string, **kwargs):
try:
result = _dispatch_and_capture(func, command_string, **kwargs)
except SystemExit:
raise
else:
return result
@patch("argh.dispatching.argparse.ArgumentParser")
@patch("argh.dispatching.dispatch")
@patch("argh.dispatching.set_default_command")
def test_dispatch_command(mock_set_default_command, mock_dispatch, mock_parser_class):
def func():
pass
argh.dispatching.dispatch_command(func)
mock_parser_class.assert_called_once()
mock_parser = mock_parser_class.return_value
mock_set_default_command.assert_called_with(
mock_parser,
func,
name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
)
mock_dispatch.assert_called_with(mock_parser)
@pytest.mark.parametrize("always_flush", [True, False])
def test_run_endpoint_function__always_flush(always_flush):
def func():
return ["first line", "second line"]
out_io = Mock(spec=io.StringIO)
argh.dispatching.run_endpoint_function(
func, argparse.Namespace(), output_file=out_io, always_flush=always_flush
)
if always_flush:
assert out_io.flush.call_count == 2
else:
out_io.flush.assert_not_called()
@patch("argh.dispatching.parse_and_resolve")
@patch("argh.dispatching.run_endpoint_function")
def test_dispatch_command_two_stage(mock_run_endpoint_function, mock_parse_and_resolve):
def func() -> str:
return "function output"
mock_parser = Mock(argparse.ArgumentParser)
mock_parser.parse_args.return_value = argparse.Namespace(foo=123)
argv = ["foo", "bar", "baz"]
completion = False
mock_output_file = Mock(io.TextIOBase)
mock_errors_file = Mock(io.TextIOBase)
raw_output = False
skip_unknown_args = False
always_flush = True
mock_endpoint_function = Mock()
mock_namespace = Mock(argparse.Namespace)
mock_namespace_obj = Mock(argparse.Namespace)
mock_parse_and_resolve.return_value = (mock_endpoint_function, mock_namespace_obj)
mock_run_endpoint_function.return_value = "run_endpoint_function retval"
retval = argh.dispatching.dispatch(
parser=mock_parser,
argv=argv,
completion=completion,
namespace=mock_namespace,
skip_unknown_args=skip_unknown_args,
output_file=mock_output_file,
errors_file=mock_errors_file,
raw_output=raw_output,
always_flush=always_flush,
)
mock_parse_and_resolve.assert_called_with(
parser=mock_parser,
argv=argv,
completion=completion,
namespace=mock_namespace,
skip_unknown_args=skip_unknown_args,
)
mock_run_endpoint_function.assert_called_with(
function=mock_endpoint_function,
namespace_obj=mock_namespace_obj,
output_file=mock_output_file,
errors_file=mock_errors_file,
raw_output=raw_output,
always_flush=always_flush,
)
assert retval == "run_endpoint_function retval"
@patch("argh.dispatching.argparse.ArgumentParser")
@patch("argh.dispatching.dispatch")
@patch("argh.dispatching.add_commands")
def test_dispatch_commands(mock_add_commands, mock_dispatch, mock_parser_class):
def func():
pass
argh.dispatching.dispatch_commands([func])
mock_parser_class.assert_called_once()
mock_parser = mock_parser_class.return_value
mock_add_commands.assert_called_with(
mock_parser,
[func],
name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
)
mock_dispatch.assert_called_with(mock_parser)
@patch("argh.dispatching.dispatch")
@patch("argh.dispatching.add_commands")
@patch("argparse.ArgumentParser")
def test_entrypoint(ap_cls_mock, add_commands_mock, dispatch_mock):
entrypoint = argh.EntryPoint("my cool app")
# no commands
with pytest.raises(argh.exceptions.DispatchingError) as excinfo:
entrypoint()
assert excinfo.exconly().endswith(
'DispatchingError: no commands for entry point "my cool app"'
)
mocked_parser = Mock()
ap_cls_mock.return_value = mocked_parser
# a single command
@entrypoint
def greet():
return "hello"
entrypoint()
assert add_commands_mock.called
add_commands_mock.assert_called_with(mocked_parser, [greet])
assert dispatch_mock.called
dispatch_mock.assert_called_with(mocked_parser)
# multiple commands
add_commands_mock.reset_mock()
dispatch_mock.reset_mock()
@entrypoint
def hit():
return "knight with a chicken"
entrypoint()
assert add_commands_mock.called
add_commands_mock.assert_called_with(mocked_parser, [greet, hit])
assert dispatch_mock.called
dispatch_mock.assert_called_with(mocked_parser)
@patch("argh.dispatching.dispatch")
@patch("argh.dispatching.set_default_command")
@patch("argparse.ArgumentParser")
def test_dispatch_command_naming_policy(
parser_cls_mock, set_default_command_mock, dispatch_mock
):
def func(): ...
parser_mock = Mock()
parser_cls_mock.return_value = parser_mock
argh.dispatching.dispatch_command(func)
set_default_command_mock.assert_called_with(
parser_mock,
func,
name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
)
set_default_command_mock.reset_mock()
argh.dispatching.dispatch_command(func, old_name_mapping_policy=True)
set_default_command_mock.assert_called_with(
parser_mock,
func,
name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
)
set_default_command_mock.reset_mock()
argh.dispatching.dispatch_command(func, old_name_mapping_policy=False)
set_default_command_mock.assert_called_with(
parser_mock,
func,
name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_KWONLY,
)
@patch("argh.dispatching.dispatch")
@patch("argh.dispatching.add_commands")
@patch("argparse.ArgumentParser")
def test_dispatch_commands_naming_policy(
parser_cls_mock, add_commands_mock, dispatch_mock
):
def func(): ...
parser_mock = Mock()
parser_cls_mock.return_value = parser_mock
argh.dispatching.dispatch_commands(func)
add_commands_mock.assert_called_with(
parser_mock,
func,
name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
)
add_commands_mock.reset_mock()
argh.dispatching.dispatch_commands(func, old_name_mapping_policy=True)
add_commands_mock.assert_called_with(
parser_mock,
func,
name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
)
add_commands_mock.reset_mock()
argh.dispatching.dispatch_commands(func, old_name_mapping_policy=False)
add_commands_mock.assert_called_with(
parser_mock,
func,
name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_KWONLY,
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_dto.py 0000644 0000000 0000000 00000006001 14644537545 013024 0 ustar 00 """
Unit Tests For the Argument DTO
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from argh.dto import ParserAddArgumentSpec
def test_update_empty_dto() -> None:
def stub_completer(): ...
dto = ParserAddArgumentSpec(
func_arg_name="foo",
cli_arg_names=["-f"],
)
other_dto = ParserAddArgumentSpec(
func_arg_name="bar",
cli_arg_names=["-f", "--foo"],
is_required=True,
default_value=123,
nargs="+",
other_add_parser_kwargs={"knights": "Ni!"},
completer=stub_completer,
)
dto.update(other_dto)
assert dto == ParserAddArgumentSpec(
func_arg_name="foo",
cli_arg_names=["-f", "--foo"],
is_required=True,
default_value=123,
nargs="+",
other_add_parser_kwargs={"knights": "Ni!"},
completer=stub_completer,
)
def test_update_full_dto() -> None:
def stub_completer_one(): ...
def stub_completer_two(): ...
dto = ParserAddArgumentSpec(
func_arg_name="foo",
cli_arg_names=["-f"],
nargs="?",
is_required=True,
default_value=123,
other_add_parser_kwargs={"'tis but a": "scratch"},
completer=stub_completer_one,
)
other_dto = ParserAddArgumentSpec(
func_arg_name="bar",
cli_arg_names=["-f", "--foo"],
nargs="+",
is_required=False,
default_value=None,
other_add_parser_kwargs={"knights": "Ni!"},
completer=stub_completer_two,
)
dto.update(other_dto)
assert dto == ParserAddArgumentSpec(
func_arg_name="foo",
cli_arg_names=["-f", "--foo"],
is_required=False,
default_value=None,
nargs="+",
other_add_parser_kwargs={"knights": "Ni!", "'tis but a": "scratch"},
completer=stub_completer_two,
)
class TestGetAllKwargs: ...
def test_make_from_kwargs_minimal() -> None:
dto = ParserAddArgumentSpec.make_from_kwargs("foo", ["-f", "--foo"], {})
assert dto == ParserAddArgumentSpec(
func_arg_name="foo", cli_arg_names=["-f", "--foo"]
)
def test_make_from_kwargs_full() -> None:
dto = ParserAddArgumentSpec.make_from_kwargs(
"foo",
["-f", "--foo"],
{
"action": "some action",
"nargs": "?",
"default": None,
"type": str,
"choices": [1, 2, 3],
"required": False,
"help": "some help",
"metavar": "FOOOOO",
"dest": "foo_dest",
"some arbitrary key": "and its value",
},
)
assert dto == ParserAddArgumentSpec(
func_arg_name="foo",
cli_arg_names=["-f", "--foo"],
is_required=False,
default_value=None,
nargs="?",
other_add_parser_kwargs={
"action": "some action",
"type": str,
"choices": [1, 2, 3],
"help": "some help",
"metavar": "FOOOOO",
"dest": "foo_dest",
"some arbitrary key": "and its value",
},
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_integration.py 0000644 0000000 0000000 00000077107 14644537545 014600 0 ustar 00 """
Integration Tests
~~~~~~~~~~~~~~~~~
"""
import argparse
import re
import sys
import unittest.mock as mock
from enum import Enum
import pytest
import argh
from argh.assembling import NameMappingPolicy
from argh.exceptions import AssemblingError
from argh.utils import unindent
from .base import CmdResult as R
from .base import DebugArghParser, get_usage_string, run
if sys.version_info < (3, 10):
HELP_OPTIONS_LABEL = "optional arguments"
else:
HELP_OPTIONS_LABEL = "options"
def test_set_default_command_integration():
def cmd(*, foo=1):
return foo
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "") == R(out="1\n", err="")
assert run(parser, "--foo 2") == R(out="2\n", err="")
assert run(parser, "--help", exit=True) == 0
def test_set_default_command_integration_merging():
@argh.arg("--foo", help="bar")
def cmd(*, foo=1):
return foo
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "") == R(out="1\n", err="")
assert run(parser, "--foo 2") == R(out="2\n", err="")
assert "bar" in parser.format_help()
#
# Function can be added to parser as is
#
def test_simple_function_no_args():
def cmd():
yield 1
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "") == R(out="1\n", err="")
def test_simple_function_positional():
def cmd(x):
yield x
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "", exit=True) == "the following arguments are required: x"
assert run(parser, "foo") == R(out="foo\n", err="")
def test_simple_function_defaults():
def cmd(*, x="foo"):
yield x
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "") == R(out="foo\n", err="")
assert run(parser, "bar", exit=True) == "unrecognized arguments: bar"
assert run(parser, "--x bar") == R(out="bar\n", err="")
def test_simple_function_varargs():
def func(*file_paths):
# `paths` is the single positional argument with nargs="*"
yield ", ".join(file_paths)
parser = DebugArghParser()
parser.set_default_command(func)
assert run(parser, "") == R(out="\n", err="")
assert run(parser, "foo") == R(out="foo\n", err="")
assert run(parser, "foo bar") == R(out="foo, bar\n", err="")
def test_simple_function_kwargs():
@argh.arg("foo")
@argh.arg("--bar")
def cmd(**kwargs):
# `kwargs` contain all arguments not fitting ArgSpec.args and .varargs.
# if ArgSpec.keywords in None, all @arg()'s will have to fit ArgSpec.args
for k in sorted(kwargs):
yield f"{k}: {kwargs[k]}"
parser = DebugArghParser()
parser.set_default_command(cmd)
message = "the following arguments are required: foo"
assert run(parser, "", exit=True) == message
assert run(parser, "hello") == R(out="bar: None\nfoo: hello\n", err="")
assert run(parser, "--bar 123", exit=True) == message
assert run(parser, "hello --bar 123") == R(out="bar: 123\nfoo: hello\n", err="")
def test_all_specs_in_one():
@argh.arg("foo")
@argh.arg("--bar")
@argh.arg("fox")
@argh.arg("--baz")
def cmd(foo, *args, bar=1, **kwargs):
yield f"foo: {foo}"
yield f"bar: {bar}"
yield f"*args: {args}"
for k in sorted(kwargs):
yield f"** {k}: {kwargs[k]}"
parser = DebugArghParser()
parser.set_default_command(cmd)
# 1) bar=1 is treated as --bar so positionals from @arg that go **kwargs
# will still have higher priority than bar.
# 2) *args, a positional with nargs="*", sits between two required
# positionals (foo and fox), so it gets nothing.
assert run(parser, "one two") == R(
out="foo: one\n" "bar: 1\n" "*args: ()\n" "** baz: None\n" "** fox: two\n",
err="",
)
# two required positionals (foo and fox) get an argument each and one extra
# is left; therefore the middle one is given to *args.
assert run(parser, "one two three") == R(
out="foo: one\n"
"bar: 1\n"
"*args: ('two',)\n"
"** baz: None\n"
"** fox: three\n",
err="",
)
# two required positionals (foo and fox) get an argument each and two extra
# are left; both are given to *args (it's greedy).
assert run(parser, "one two three four") == R(
out="foo: one\n"
"bar: 1\n"
"*args: ('two', 'three')\n"
"** baz: None\n"
"** fox: four\n",
err="",
)
def test_arg_merged():
"""@arg merges into function signature."""
@argh.arg("my", help="a moose once bit my sister")
@argh.arg("-b", "--brain", help="i am made entirely of wood")
def gumby(my, *, brain=None):
return my, brain, "hurts"
parser = DebugArghParser("PROG")
parser.set_default_command(gumby)
help_msg = parser.format_help()
assert "a moose once bit my sister" in help_msg
assert "i am made entirely of wood" in help_msg
def test_arg_mismatch_positional():
"""An `@arg("positional")` must match function signature."""
@argh.arg("bogus-argument")
def confuse_a_cat(vet, *, funny_things=123):
return vet, funny_things
parser = DebugArghParser("PROG")
with pytest.raises(AssemblingError) as excinfo:
parser.set_default_command(confuse_a_cat)
msg = (
"confuse_a_cat: argument bogus-argument does not fit "
"function signature: vet, -f/--funny-things"
)
assert msg in str(excinfo.value)
def test_arg_mismatch_flag():
"""An `@arg("--flag")` must match function signature."""
@argh.arg("--bogus-argument")
def confuse_a_cat(vet, *, funny_things=123):
return vet, funny_things
parser = DebugArghParser("PROG")
with pytest.raises(AssemblingError) as excinfo:
parser.set_default_command(confuse_a_cat)
msg = (
"confuse_a_cat: argument --bogus-argument does not fit "
"function signature: vet, -f/--funny-things"
)
assert msg in str(excinfo.value)
def test_arg_mismatch_positional_vs_flag():
"""An `@arg("arg")` must match a positional arg in function signature."""
@argh.arg("foo")
def func(*, foo=123):
return foo
parser = DebugArghParser("PROG")
with pytest.raises(AssemblingError) as excinfo:
parser.set_default_command(func)
msg = (
'func: argument "foo" declared as optional (in function signature)'
" and positional (via decorator)"
)
assert msg in str(excinfo.value)
def test_arg_mismatch_flag_vs_positional():
"""An `@arg("--flag")` must match a keyword in function signature."""
@argh.arg("--foo")
def func(foo):
return foo
parser = DebugArghParser("PROG")
with pytest.raises(AssemblingError) as excinfo:
parser.set_default_command(func)
msg = (
'func: argument "foo" declared as positional (in function signature)'
" and optional (via decorator)"
)
assert msg in str(excinfo.value)
class TestErrorWrapping:
def _get_parrot(self):
def parrot(*, dead=False):
if dead:
raise ValueError("this parrot is no more")
else:
return "beautiful plumage"
return parrot
def test_error_raised(self):
parrot = self._get_parrot()
parser = DebugArghParser()
parser.set_default_command(parrot)
assert run(parser, "") == R("beautiful plumage\n", "")
with pytest.raises(ValueError) as excinfo:
run(parser, "--dead")
assert re.match("this parrot is no more", str(excinfo.value))
def test_error_wrapped(self):
parrot = self._get_parrot()
wrapped_parrot = argh.wrap_errors([ValueError])(parrot)
parser = DebugArghParser()
parser.set_default_command(wrapped_parrot)
assert run(parser, "") == R("beautiful plumage\n", "")
assert run(parser, "--dead") == R(
"", "ValueError: this parrot is no more\n", exit_code=1
)
def test_processor(self):
parrot = self._get_parrot()
wrapped_parrot = argh.wrap_errors([ValueError])(parrot)
def failure(err):
return "ERR: " + str(err) + "!"
processed_parrot = argh.wrap_errors(processor=failure)(wrapped_parrot)
parser = argh.ArghParser()
parser.set_default_command(processed_parrot)
assert run(parser, "--dead") == R(
"", "ERR: this parrot is no more!\n", exit_code=1
)
def test_stderr_vs_stdout(self):
@argh.wrap_errors([KeyError])
def func(key):
db = {"a": 1}
return db[key]
parser = argh.ArghParser()
parser.set_default_command(func)
assert run(parser, "a") == R(out="1\n", err="")
assert run(parser, "b") == R(out="", err="KeyError: 'b'\n", exit_code=1)
def test_argv():
def echo(text):
return f"you said {text}"
parser = DebugArghParser()
parser.add_commands([echo])
_argv = sys.argv
sys.argv = sys.argv[:1] + ["echo", "hi there"]
assert run(parser, None) == R("you said hi there\n", "")
sys.argv = _argv
def test_commands_not_defined():
parser = DebugArghParser()
assert run(parser, "", {"raw_output": True}).out == parser.format_usage()
assert run(parser, "").out == parser.format_usage()
assert "unrecognized arguments" in run(parser, "foo", exit=True)
assert "unrecognized arguments" in run(parser, "--foo", exit=True)
def test_command_not_chosen():
def cmd(args):
return 1
parser = DebugArghParser()
parser.add_commands([cmd])
# returns a help message and doesn't exit
assert "usage:" in run(parser, "").out
def test_invalid_choice():
def cmd(args):
return 1
# root level command
parser = DebugArghParser()
parser.add_commands([cmd])
assert "invalid choice" in run(parser, "bar", exit=True)
# exits with an informative error
assert run(parser, "--bar", exit=True) == "unrecognized arguments: --bar"
# nested command
parser = DebugArghParser()
parser.add_commands([cmd], group_name="nest")
assert "invalid choice" in run(parser, "nest bar", exit=True)
# exits with an informative error
assert run(parser, "nest --bar", exit=True) == "unrecognized arguments: --bar"
def test_unrecognized_arguments():
def cmd():
return 1
# single-command parser
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "--bar", exit=True) == "unrecognized arguments: --bar"
assert run(parser, "bar", exit=True) == "unrecognized arguments: bar"
# multi-command parser
parser = DebugArghParser()
parser.add_commands([cmd])
assert run(parser, "cmd --bar", exit=True) == "unrecognized arguments: --bar"
assert run(parser, "cmd bar", exit=True) == "unrecognized arguments: bar"
def test_echo():
"A simple command is resolved to a function."
def echo(text):
return f"you said {text}"
parser = DebugArghParser()
parser.add_commands([echo])
assert run(parser, "echo foo") == R(out="you said foo\n", err="")
def test_bool_action():
"Action `store_true`/`store_false` is inferred from default value."
def parrot(*, dead=False):
return "this parrot is no more" if dead else "beautiful plumage"
parser = DebugArghParser()
parser.add_commands([parrot])
assert run(parser, "parrot").out == "beautiful plumage\n"
assert run(parser, "parrot --dead").out == "this parrot is no more\n"
def test_bare_group_name():
"A command can be resolved to a function, not a group_name."
def hello():
return "hello world"
parser = DebugArghParser()
parser.add_commands([hello], group_name="greet")
# without arguments
# returns a help message and doesn't exit
assert "usage:" in run(parser, "greet").out
# with an argument
# exits with an informative error
message = "unrecognized arguments: --name=world"
assert run(parser, "greet --name=world", exit=True) == message
def test_function_under_group_name():
"A subcommand is resolved to a function."
def hello(*, name="world"):
return f"Hello {name}!"
def howdy(buddy):
return f"Howdy {buddy}?"
parser = DebugArghParser()
parser.add_commands([hello, howdy], group_name="greet")
assert run(parser, "greet hello").out == "Hello world!\n"
assert run(parser, "greet hello --name=John").out == "Hello John!\n"
assert run(parser, "greet hello John", exit=True) == "unrecognized arguments: John"
# exits with an informative error
message = "the following arguments are required: buddy"
assert message in run(parser, "greet howdy --name=John", exit=True)
assert run(parser, "greet howdy John").out == "Howdy John?\n"
def test_explicit_cmd_name():
@argh.named("new-name")
def orig_name():
return "ok"
parser = DebugArghParser()
parser.add_commands([orig_name])
assert "invalid choice" in run(parser, "orig-name", exit=True)
assert run(parser, "new-name").out == "ok\n"
def test_aliases():
@argh.aliases("alias2", "alias3")
def alias1():
return "ok"
parser = DebugArghParser()
parser.add_commands([alias1])
assert run(parser, "alias1").out == "ok\n"
assert run(parser, "alias2").out == "ok\n"
assert run(parser, "alias3").out == "ok\n"
def test_help():
parser = DebugArghParser()
# assert the commands don't fail
assert run(parser, "--help", exit=True) == 0
assert run(parser, "greet --help", exit=True) == 0
assert run(parser, "greet hello --help", exit=True) == 0
def test_arg_order():
"""Positional arguments are resolved in the order in which the @arg
decorators are defined.
"""
def cmd(foo, bar):
return foo, bar
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "foo bar").out == "foo\nbar\n"
def test_raw_output():
"If the raw_output flag is set, no extra whitespace is added"
def cmd(foo, bar):
return foo, bar
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "foo bar").out == "foo\nbar\n"
assert run(parser, "foo bar", {"raw_output": True}).out == "foobar"
def test_output_file():
def cmd():
return "Hello world!"
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "").out == "Hello world!\n"
assert run(parser, "", {"output_file": None}).out == "Hello world!\n"
def test_command_error():
def whiner_plain(*, code=1):
raise argh.CommandError("I feel depressed.", code=code)
def whiner_iterable():
yield "Hello..."
raise argh.CommandError("I feel depressed.")
parser = DebugArghParser()
parser.add_commands([whiner_plain, whiner_iterable])
assert run(parser, "whiner-plain") == R(
out="", err="CommandError: I feel depressed.\n", exit_code=1
)
assert run(parser, "whiner-plain --code=127") == R(
out="", err="CommandError: I feel depressed.\n", exit_code=127
)
assert run(parser, "whiner-iterable") == R(
out="Hello...\n", err="CommandError: I feel depressed.\n", exit_code=1
)
@pytest.mark.parametrize(
"argparse_namespace_class", [argparse.Namespace, argh.dispatching.ArghNamespace]
)
def test_get_function_from_namespace_obj(argparse_namespace_class):
argparse_namespace = argparse_namespace_class()
def func():
pass
retval = argh.dispatching._get_function_from_namespace_obj(argparse_namespace)
assert retval is None
setattr(argparse_namespace, argh.constants.DEST_FUNCTION, "")
retval = argh.dispatching._get_function_from_namespace_obj(argparse_namespace)
assert retval is None
setattr(argparse_namespace, argh.constants.DEST_FUNCTION, func)
retval = argh.dispatching._get_function_from_namespace_obj(argparse_namespace)
assert retval == func
def test_normalized_keys():
"""Underscores in function args are converted to dashes and back."""
def cmd(a_b):
return a_b
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "hello").out == "hello\n"
@mock.patch("argh.assembling.COMPLETION_ENABLED", True)
def test_custom_argument_completer():
"Issue #33: Enable custom per-argument shell completion"
@argh.arg("foo", completer="STUB")
def func(foo):
pass
parser = argh.ArghParser()
parser.set_default_command(func)
assert parser._actions[-1].completer == "STUB"
def test_class_members():
"Issue #34: class members as commands"
class Controller:
var = 123
def instance_meth(self, value):
return value, self.var
@classmethod
def class_meth(cls, value):
return value, cls.var
@staticmethod
def static_meth(value):
return value, "w00t?"
@staticmethod
def static_meth2(value):
return value, "huh!"
controller = Controller()
parser = DebugArghParser()
parser.add_commands(
[
controller.instance_meth,
controller.class_meth,
controller.static_meth,
Controller.static_meth2,
]
)
assert run(parser, "instance-meth foo").out == "foo\n123\n"
assert run(parser, "class-meth foo").out == "foo\n123\n"
assert run(parser, "static-meth foo").out == "foo\nw00t?\n"
assert run(parser, "static-meth2 foo").out == "foo\nhuh!\n"
def test_kwonlyargs__policy_legacy():
"Correct dispatch in presence of keyword-only arguments"
def cmd(*args, foo="1", bar, baz="3", **kwargs):
return f"foo='{foo}' bar='{bar}' baz='{baz}' args={args} kwargs={kwargs}"
parser = DebugArghParser(prog="pytest")
parser.set_default_command(
cmd, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT
)
expected_usage = "usage: pytest [-h] [-f FOO] [--baz BAZ] [args ...] bar\n"
if sys.version_info < (3, 9):
# https://github.com/python/cpython/issues/82619
expected_usage = (
"usage: pytest [-h] [-f FOO] [--baz BAZ] [args [args ...]] bar\n"
)
assert parser.format_usage() == expected_usage
assert (
run(parser, "--baz=baz! one two").out
== "foo='1' bar='two' baz='baz!' args=('one',) kwargs={}\n"
)
assert (
run(parser, "test --foo=do").out
== "foo='do' bar='test' baz='3' args=() kwargs={}\n"
)
def test_kwonlyargs__policy_modern():
"Correct dispatch in presence of keyword-only arguments"
def cmd(*args, foo="1", bar, baz="3", **kwargs):
return f"foo='{foo}' bar='{bar}' baz='{baz}' args={args} kwargs={kwargs}"
parser = DebugArghParser(prog="pytest")
parser.set_default_command(
cmd, name_mapping_policy=NameMappingPolicy.BY_NAME_IF_KWONLY
)
expected_usage = "usage: pytest [-h] [-f FOO] --bar BAR [--baz BAZ] [args ...]\n"
if sys.version_info < (3, 9):
# https://github.com/python/cpython/issues/82619
expected_usage = (
"usage: pytest [-h] [-f FOO] --bar BAR [--baz BAZ] [args [args ...]]\n"
)
assert parser.format_usage() == expected_usage
assert (
run(parser, "--baz=baz! one two --bar=bar!").out
== "foo='1' bar='bar!' baz='baz!' args=('one', 'two') kwargs={}\n"
)
message = "the following arguments are required: --bar"
assert run(parser, "test --foo=do", exit=True) == message
def test_default_arg_values_in_help():
"Argument defaults should appear in the help message implicitly"
@argh.arg("name", default="Basil")
@argh.arg("--task", default="hang the Moose")
@argh.arg("--note", help="why is it a remarkable animal?")
def remind(
name,
*,
task=None,
reason="there are creatures living in it",
note="it can speak English",
):
return "Oh what is it now, can't you leave me in peace..."
parser = DebugArghParser()
parser.set_default_command(remind)
help_normalised = re.sub(r"\s+", " ", parser.format_help())
assert "name 'Basil'" in help_normalised
# argh#228 — argparse in Python before 3.13 duplicated the placeholder in help
if sys.version_info < (3, 13):
assert "-t TASK, --task TASK 'hang the Moose'" in help_normalised
assert (
"-r REASON, --reason REASON 'there are creatures living in it'"
in help_normalised
)
# explicit help message is not obscured by the implicit one
# but is still present
assert (
"-n NOTE, --note NOTE why is it a remarkable animal? "
"(default: 'it can speak English')"
) in help_normalised
else:
assert "-t, --task TASK 'hang the Moose'" in help_normalised
assert (
"-r, --reason REASON 'there are creatures living in it'" in help_normalised
)
# explicit help message is not obscured by the implicit one
# but is still present
assert (
"-n, --note NOTE why is it a remarkable animal? "
"(default: 'it can speak English')"
) in help_normalised
def test_default_arg_values_in_help__regression():
"Empty string as default value → empty help string → broken argparse"
def foo(*, bar=""):
return bar
parser = DebugArghParser()
parser.set_default_command(foo)
# doesn't break
parser.format_help()
# argh#228 — argparse in Python before 3.13 duplicated the placeholder in help
if sys.version_info < (3, 13):
expected_line = "-b BAR, --bar BAR ''"
# note the empty str repr ^^^
else:
expected_line = "-b, --bar BAR ''"
# note the empty str repr ^^^
# now check details
assert expected_line in parser.format_help()
def test_help_formatting_is_preserved():
"Formatting of docstrings should not be messed up in help messages"
def func():
"""
Sample function.
Parameters:
foo: float
An example argument.
bar: bool
Another argument.
"""
return "hello"
parser = DebugArghParser()
parser.set_default_command(func)
assert unindent(func.__doc__) in parser.format_help()
def test_prog(capsys: pytest.CaptureFixture[str]):
"Program name propagates from sys.argv[0]"
def cmd(*, foo=1):
return foo
parser = DebugArghParser()
parser.add_commands([cmd])
usage = get_usage_string()
assert run(parser, "-h", exit=True) == 0
captured = capsys.readouterr()
assert captured.out.startswith(usage)
def test_unknown_args():
def cmd(*, foo=1):
return foo
parser = DebugArghParser()
parser.set_default_command(cmd)
get_usage_string("[-f FOO]")
assert run(parser, "--foo 1") == R(out="1\n", err="")
assert run(parser, "--bar 1", exit=True) == "unrecognized arguments: --bar 1"
assert run(parser, "--bar 1", exit=False, kwargs={"skip_unknown_args": True}) == R(
out="1\n", err=""
)
def test_add_commands_unknown_name_mapping_policy():
def func(foo): ...
parser = argh.ArghParser(prog="myapp")
class UnsuitablePolicyContainer(Enum):
FOO = "Ni!!!"
with pytest.raises(
NotImplementedError,
match="Unknown name mapping policy UnsuitablePolicyContainer.FOO",
):
parser.add_commands([func], name_mapping_policy=UnsuitablePolicyContainer.FOO)
def test_add_commands_no_overrides1(capsys: pytest.CaptureFixture[str]):
def first_func(*, foo=123):
"""Owl stretching time"""
def second_func():
pass
parser = argh.ArghParser(prog="myapp")
parser.add_commands(
[first_func, second_func],
)
run(parser, "--help", exit=True)
captured = capsys.readouterr()
assert (
captured.out
== unindent(
f"""
usage: myapp [-h] {{first-func,second-func}} ...
positional arguments:
{{first-func,second-func}}
first-func Owl stretching time
second-func
{HELP_OPTIONS_LABEL}:
-h, --help show this help message and exit
"""
)[1:]
)
def test_add_commands_no_overrides2(capsys: pytest.CaptureFixture[str]):
def first_func(*, foo=123):
"""Owl stretching time"""
def second_func():
pass
parser = argh.ArghParser(prog="myapp")
parser.add_commands([first_func, second_func])
run(parser, "first-func --help", exit=True)
captured = capsys.readouterr()
# argh#228 — argparse in Python before 3.13 duplicated the placeholder in help
if sys.version_info < (3, 13):
arg_help_lines = (
" -h, --help show this help message and exit\n"
" -f FOO, --foo FOO 123"
)
else:
arg_help_lines = (
" -h, --help show this help message and exit\n" " -f, --foo FOO 123"
)
assert (
captured.out
== unindent(
f"""
usage: myapp first-func [-h] [-f FOO]
Owl stretching time
{HELP_OPTIONS_LABEL}:
{arg_help_lines}
"""
)[1:]
)
def test_add_commands_group_overrides1(capsys: pytest.CaptureFixture[str]):
"""
When `group_kwargs` is passed to `add_commands()`, its members override
whatever was specified on function level.
"""
def first_func(*, foo=123):
"""Owl stretching time"""
return foo
def second_func():
pass
parser = argh.ArghParser(prog="myapp")
parser.add_commands(
[first_func, second_func],
group_name="my-group",
group_kwargs={
"help": "group help override",
"description": "group description override",
},
)
run(parser, "--help", exit=True)
captured = capsys.readouterr()
assert (
captured.out
== unindent(
f"""
usage: myapp [-h] {{my-group}} ...
positional arguments:
{{my-group}}
my-group
{HELP_OPTIONS_LABEL}:
-h, --help show this help message and exit
"""
)[1:]
)
def test_add_commands_group_overrides2(capsys: pytest.CaptureFixture[str]):
"""
When `group_kwargs` is passed to `add_commands()`, its members override
whatever was specified on function level.
"""
def first_func(*, foo=123):
"""Owl stretching time"""
return foo
def second_func():
pass
parser = argh.ArghParser(prog="myapp")
parser.add_commands(
[first_func, second_func],
group_name="my-group",
group_kwargs={
"help": "group help override",
"description": "group description override",
},
)
run(parser, "my-group --help", exit=True)
captured = capsys.readouterr()
assert (
captured.out
== unindent(
f"""
usage: myapp my-group [-h] {{first-func,second-func}} ...
{HELP_OPTIONS_LABEL}:
-h, --help show this help message and exit
subcommands:
group description override
{{first-func,second-func}}
group help override
first-func Owl stretching time
second-func
"""
)[1:]
)
def test_add_commands_group_overrides3(capsys: pytest.CaptureFixture[str]):
"""
When `group_kwargs` is passed to `add_commands()`, its members override
whatever was specified on function level.
"""
def first_func(*, foo=123):
"""Owl stretching time"""
return foo
def second_func():
pass
parser = argh.ArghParser(prog="myapp")
parser.add_commands(
[first_func, second_func],
group_name="my-group",
group_kwargs={
"help": "group help override",
"description": "group description override",
},
)
run(parser, "my-group first-func --help", exit=True)
captured = capsys.readouterr()
# argh#228 — argparse in Python before 3.13 duplicated the placeholder in help
if sys.version_info < (3, 13):
arg_help_lines = (
" -h, --help show this help message and exit\n"
" -f FOO, --foo FOO 123"
)
else:
arg_help_lines = (
" -h, --help show this help message and exit\n" " -f, --foo FOO 123"
)
assert (
captured.out
== unindent(
f"""
usage: myapp my-group first-func [-h] [-f FOO]
Owl stretching time
{HELP_OPTIONS_LABEL}:
{arg_help_lines}
"""
)[1:]
)
def test_add_commands_func_overrides1(capsys: pytest.CaptureFixture[str]):
"""
When `func_kwargs` is passed to `add_commands()`, its members override
whatever was specified on function level.
"""
def first_func(*, foo=123):
"""Owl stretching time"""
pass
def second_func():
pass
parser = argh.ArghParser(prog="myapp")
parser.add_commands(
[first_func, second_func],
func_kwargs={
"help": "func help override",
"description": "func description override",
},
)
run(parser, "--help", exit=True)
captured = capsys.readouterr()
assert (
captured.out
== unindent(
f"""
usage: myapp [-h] {{first-func,second-func}} ...
positional arguments:
{{first-func,second-func}}
first-func func help override
second-func func help override
{HELP_OPTIONS_LABEL}:
-h, --help show this help message and exit
"""
)[1:]
)
def test_add_commands_func_overrides2(capsys: pytest.CaptureFixture[str]):
"""
When `func_kwargs` is passed to `add_commands()`, its members override
whatever was specified on function level.
"""
def first_func(*, foo=123):
"""Owl stretching time"""
pass
def second_func():
pass
parser = argh.ArghParser(prog="myapp")
parser.add_commands(
[first_func, second_func],
func_kwargs={
"help": "func help override",
"description": "func description override",
},
)
run(parser, "first-func --help", exit=True)
captured = capsys.readouterr()
# argh#228 — argparse in Python before 3.13 duplicated the placeholder in help
if sys.version_info < (3, 13):
arg_help_lines = (
" -h, --help show this help message and exit\n"
" -f FOO, --foo FOO 123"
)
else:
arg_help_lines = (
" -h, --help show this help message and exit\n" " -f, --foo FOO 123"
)
assert (
captured.out
== unindent(
f"""
usage: myapp first-func [-h] [-f FOO]
func description override
{HELP_OPTIONS_LABEL}:
{arg_help_lines}
"""
)[1:]
)
def test_action_count__only_arg_decorator():
@argh.arg("-v", "--verbose", action="count", default=0)
def func(**kwargs):
verbosity = kwargs.get("verbose")
return f"verbosity: {verbosity}"
parser = DebugArghParser()
parser.set_default_command(func)
assert run(parser, "").out == "verbosity: 0\n"
assert run(parser, "-v").out == "verbosity: 1\n"
assert run(parser, "-vvvv").out == "verbosity: 4\n"
def test_action_count__mixed():
@argh.arg("-v", "--verbose", action="count")
def func(*, verbose=0):
return f"verbosity: {verbose}"
parser = DebugArghParser()
parser.set_default_command(func)
assert run(parser, "").out == "verbosity: 0\n"
assert run(parser, "-v").out == "verbosity: 1\n"
assert run(parser, "-vvvv").out == "verbosity: 4\n"
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_interaction.py 0000644 0000000 0000000 00000003770 14644537545 014567 0 ustar 00 """
Interaction Tests
~~~~~~~~~~~~~~~~~
"""
import unittest.mock as mock
import argh
def parse_choice(choice, **kwargs):
with mock.patch("argh.interaction.input", lambda prompt: choice):
return argh.confirm("test", **kwargs)
def test_simple():
assert parse_choice("") is None
assert parse_choice("", default=None) is None
assert parse_choice("", default=True) is True
assert parse_choice("", default=False) is False
assert parse_choice("y") is True
assert parse_choice("y", default=True) is True
assert parse_choice("y", default=False) is True
assert parse_choice("y", default=None) is True
assert parse_choice("n") is False
assert parse_choice("n", default=True) is False
assert parse_choice("n", default=False) is False
assert parse_choice("n", default=None) is False
assert parse_choice("x") is None
def test_prompt():
"Prompt is properly formatted"
prompts = []
def raw_input_mock(prompt):
prompts.append(prompt)
with mock.patch("argh.interaction.input", raw_input_mock):
argh.confirm("do smth")
assert prompts[-1] == "do smth? (y/n)"
argh.confirm("do smth", default=None)
assert prompts[-1] == "do smth? (y/n)"
argh.confirm("do smth", default=True)
assert prompts[-1] == "do smth? (Y/n)"
argh.confirm("do smth", default=False)
assert prompts[-1] == "do smth? (y/N)"
@mock.patch("argh.interaction.input")
def test_encoding(mock_input):
"Unicode is accepted as prompt message"
msg = "привет"
argh.confirm(msg)
mock_input.assert_called_once_with("привет? (y/n)")
@mock.patch("argh.interaction.input")
def test_skip(mock_input):
retval = argh.confirm("test", default=123, skip=True)
assert retval == 123
mock_input.assert_not_called()
@mock.patch("argh.interaction.input")
def test_keyboard_interrupt(mock_input):
mock_input.side_effect = KeyboardInterrupt
retval = argh.confirm("test")
assert retval is None
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_mapping_policies.py 0000644 0000000 0000000 00000015613 14644537545 015571 0 ustar 00 import sys
from argparse import ArgumentParser, Namespace
from typing import Callable, List, Optional
import pytest
from argh.assembling import (
ArgumentNameMappingError,
NameMappingPolicy,
infer_argspecs_from_function,
)
POLICIES = list(NameMappingPolicy) + [None]
@pytest.mark.parametrize("name_mapping_policy", POLICIES)
def test_no_args(name_mapping_policy) -> None:
def func() -> None: ...
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
assert_usage(parser, "usage: test [-h]")
@pytest.mark.parametrize("name_mapping_policy", POLICIES)
def test_one_positional(name_mapping_policy) -> None:
def func(alpha: str) -> str:
return f"{alpha}"
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
assert_usage(parser, "usage: test [-h] alpha")
assert_parsed(parser, ["hello"], Namespace(alpha="hello"))
@pytest.mark.parametrize("name_mapping_policy", POLICIES)
def test_two_positionals(name_mapping_policy) -> None:
def func(alpha: str, beta: str) -> str:
return f"{alpha}, {beta}"
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
assert_usage(parser, "usage: test [-h] alpha beta")
assert_parsed(parser, ["one", "two"], Namespace(alpha="one", beta="two"))
@pytest.mark.parametrize(
"name_mapping_policy,expected_usage",
[
(
NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
"usage: test [-h] [-b BETA] alpha",
),
(NameMappingPolicy.BY_NAME_IF_KWONLY, "usage: test [-h] alpha [beta]"),
],
)
def test_two_positionals_one_with_default(name_mapping_policy, expected_usage) -> None:
def func(alpha: str, beta: int = 123) -> str:
return f"{alpha}, {beta}"
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
assert_usage(parser, expected_usage)
assert_parsed(parser, ["one"], Namespace(alpha="one", beta=123))
if name_mapping_policy == NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT:
assert_parsed(
parser, ["one", "--beta", "two"], Namespace(alpha="one", beta="two")
)
elif name_mapping_policy == NameMappingPolicy.BY_NAME_IF_KWONLY:
assert_parsed(parser, ["one", "two"], Namespace(alpha="one", beta="two"))
@pytest.mark.parametrize("name_mapping_policy", POLICIES)
def test_varargs(name_mapping_policy) -> None:
def func(*file_paths) -> str:
return f"{file_paths}"
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
expected_usage = "usage: test [-h] [file-paths ...]"
# TODO: remove once we drop support for Python 3.8
if sys.version_info < (3, 9):
# https://github.com/python/cpython/issues/82619
expected_usage = "usage: test [-h] [file-paths [file-paths ...]]"
assert_usage(parser, expected_usage)
@pytest.mark.parametrize(
"name_mapping_policy,expected_usage",
[
(NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT, "usage: test [-h] alpha beta"),
(NameMappingPolicy.BY_NAME_IF_KWONLY, "usage: test [-h] -b BETA alpha"),
(None, "usage: test [-h] -b BETA alpha"),
],
)
def test_varargs_between_positional_and_kwonly__no_defaults(
name_mapping_policy, expected_usage
) -> None:
def func(alpha, *, beta) -> str:
return f"{alpha}, {beta}"
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
assert_usage(parser, expected_usage)
@pytest.mark.parametrize(
"name_mapping_policy,expected_usage",
[
(
NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
"usage: test [-h] [-a ALPHA] [-b BETA]",
),
(NameMappingPolicy.BY_NAME_IF_KWONLY, "usage: test [-h] [-b BETA] [alpha]"),
],
)
def test_varargs_between_positional_and_kwonly__with_defaults(
name_mapping_policy, expected_usage
) -> None:
def func(alpha: int = 1, *, beta: int = 2) -> str:
return f"{alpha}, {beta}"
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
assert_usage(parser, expected_usage)
def test_varargs_between_positional_and_kwonly__with_defaults__no_explicit_policy() -> (
None
):
def func(alpha: int = 1, *, beta: int = 2) -> str:
return f"{alpha}, {beta}"
with pytest.raises(ArgumentNameMappingError) as exc:
_make_parser_for_function(func, name_mapping_policy=None)
assert (
'Argument "alpha" in function "func"\n'
"is not keyword-only but has a default value."
) in str(exc.value)
# TODO: remove in v.0.33 if it happens, otherwise in v1.0.
def test_positional_with_defaults_without_kwonly__no_explicit_policy() -> None:
def func(alpha: str, beta: int = 1) -> str:
return f"{alpha} {beta}"
message_pattern = 'Argument "beta" in function "func"\nis not keyword-only but has a default value.'
with pytest.warns(DeprecationWarning, match=message_pattern):
parser = _make_parser_for_function(func, name_mapping_policy=None)
assert_usage(parser, "usage: test [-h] [-b BETA] alpha")
@pytest.mark.parametrize("name_mapping_policy", POLICIES)
def test_kwargs(name_mapping_policy) -> None:
def func(**kwargs) -> str:
return f"{kwargs}"
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
assert_usage(parser, "usage: test [-h]")
@pytest.mark.parametrize(
"name_mapping_policy,expected_usage",
[
(
NameMappingPolicy.BY_NAME_IF_HAS_DEFAULT,
"usage: test [-h] [-b BETA] [-d DELTA] alpha gamma",
),
(
NameMappingPolicy.BY_NAME_IF_KWONLY,
"usage: test [-h] -g GAMMA [-d DELTA] alpha [beta]",
),
],
)
def test_all_types_mixed_no_named_varargs(name_mapping_policy, expected_usage) -> None:
def func(alpha: str, beta: int = 1, *, gamma: str, delta: int = 2) -> str:
return f"{alpha}, {beta}, {gamma}, {delta}"
parser = _make_parser_for_function(func, name_mapping_policy=name_mapping_policy)
assert_usage(parser, expected_usage)
def _make_parser_for_function(
func: Callable,
name_mapping_policy: Optional[NameMappingPolicy] = None,
) -> ArgumentParser:
parser = ArgumentParser(prog="test")
parser_add_argument_specs = infer_argspecs_from_function(
function=func, name_mapping_policy=name_mapping_policy
)
for parser_add_argument_spec in parser_add_argument_specs:
parser.add_argument(
*parser_add_argument_spec.cli_arg_names,
**parser_add_argument_spec.get_all_kwargs(),
)
return parser
def assert_usage(parser: ArgumentParser, expected_usage: str) -> None:
if not expected_usage.endswith("\n"):
expected_usage += "\n"
assert expected_usage == parser.format_usage()
def assert_parsed(
parser: ArgumentParser, argv: List[str], expected_result: Namespace
) -> None:
parsed = parser.parse_args(argv)
assert parsed == expected_result
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1720893285.4768457
argh-0.31.3/tests/test_regressions.py 0000644 0000000 0000000 00000017277 14644537545 014622 0 ustar 00 """
Regression tests
~~~~~~~~~~~~~~~~
"""
import sys
from typing import List, Optional, TextIO
import pytest
import argh
from .base import DebugArghParser, run
def test_regression_issue12():
"""
Issue #12: @command was broken if there were more than one argument
to begin with same character (i.e. short option names were inferred
incorrectly).
"""
def cmd(*, foo=1, fox=2):
yield f"foo {foo}, fox {fox}"
parser = DebugArghParser()
parser.set_default_command(cmd)
assert run(parser, "").out == "foo 1, fox 2\n"
assert run(parser, "--foo 3").out == "foo 3, fox 2\n"
assert run(parser, "--fox 3").out == "foo 1, fox 3\n"
assert "unrecognized" in run(parser, "-f 3", exit=True)
def test_regression_issue12_help_flag():
"""
Issue #12: if an argument starts with "h", e.g. "--host",
ArgumentError is raised because "--help" is always added by argh
without decorators.
"""
def ddos(*, host="localhost"):
return f"so be it, {host}!"
# no help → no conflict
parser = DebugArghParser("PROG", add_help=False)
parser.set_default_command(ddos)
assert run(parser, "-h 127.0.0.1").out == "so be it, 127.0.0.1!\n"
# help added → conflict → short name ignored
parser = DebugArghParser("PROG", add_help=True)
parser.set_default_command(ddos)
assert run(parser, "-h 127.0.0.1", exit=True) == 0
def test_regression_issue27():
"""
Issue #27: store_true is not set for inferred bool argument.
:Reason: when @command was refactored, it stopped using @arg, but it is
it was there that guesses (choices→type, default→type and
default→action) were made.
"""
def parrot(*, dead=False):
return "this parrot is no more" if dead else "beautiful plumage"
def grenade(*, count=3):
if count == 3:
return "Three shall be the number thou shalt count"
else:
return "{0!r} is right out".format(count)
parser = DebugArghParser()
parser.add_commands([parrot, grenade])
# default → type (int)
assert run(parser, "grenade").out == (
"Three shall be the number " "thou shalt count\n"
)
assert run(parser, "grenade --count 5").out == "5 is right out\n"
# default → action (store_true)
assert run(parser, "parrot").out == "beautiful plumage\n"
assert run(parser, "parrot --dead").out == "this parrot is no more\n"
def test_regression_issue31():
"""
Issue #31: Argh fails with parameter action type 'count' if a default
value is provided.
:Reason: assembling._guess() would infer type from default value without
regard to the action. _CountAction does not accept argument "type".
:Solution: restricted type inferring to actions "store" and "append".
"""
@argh.arg("-v", "--verbose", dest="verbose", action="count", default=0)
def cmd(**kwargs):
yield kwargs.get("verbose", -1)
parser = DebugArghParser()
parser.set_default_command(cmd)
assert "0\n" == run(parser, "").out
assert "1\n" == run(parser, "-v").out
assert "2\n" == run(parser, "-vv").out
def test_regression_issue47():
@argh.arg("--foo-bar", default="full")
def func(foo_bar):
return "hello"
parser = DebugArghParser()
with pytest.raises(argh.assembling.AssemblingError) as excinfo:
parser.set_default_command(func)
msg = (
'func: argument "foo_bar" declared as positional (in function '
"signature) and optional (via decorator). If you've just migrated "
"from Argh v.0.29, please check the new default NameMappingPolicy. "
"Perhaps you need to replace `func(x=1)` with `func(*, x=1)`?"
)
assert excinfo.exconly().endswith(msg)
def test_regression_issue76():
"""
Issue #76: optional arguments defaulting to the empty string break --help.
This is also tested in integration tests but in a different way.
"""
def cmd(*, foo=""):
pass
parser = DebugArghParser()
parser.set_default_command(cmd)
run(parser, "--help", exit=True)
def test_regression_issue104():
"""
Issue #76: Bug in the way **kwargs is handled
**kwargs handling was broken in the case that required (no default
value) positional argument names contained underscores.
"""
def cmd(foo_foo, bar_bar, *, baz_baz=5, bip_bip=9, **kwargs):
return "\n".join(
[str(foo_foo), str(bar_bar), str(baz_baz), str(bip_bip), str(kwargs)]
)
parser = DebugArghParser()
parser.set_default_command(cmd)
expected = "abc\ndef\n8\n9\n{}\n"
assert run(parser, "abc def --baz-baz 8").out == expected
def test_regression_issue204():
"""
Issue #204: `asdict(ParserAddArgumentSpec)` used `deepcopy` which would
lead to "TypeError: cannot pickle..." if e.g. a default value contained an
un-pickle-able object.
We should avoid `deepcopy()` in standard operations.
"""
def func(*, x: TextIO = sys.stdout) -> None: ...
parser = DebugArghParser()
parser.set_default_command(func)
def test_regression_issue208():
@argh.arg("foo_bar", help="fooooo")
def func(foo_bar):
return foo_bar
parser = DebugArghParser()
parser.set_default_command(func)
def test_regression_issue212_orig_use_case():
"""
Issue #212: a combination of nargs with list as default value would result
in a nested list instead of a flat list.
Variation: original use case (default value via decorator).
"""
@argh.arg("paths", nargs="*", default=["one", "two"])
def func(paths: List[str]):
return f"{paths}"
parser = DebugArghParser()
parser.set_default_command(func)
assert run(parser, "").out == "['one', 'two']\n"
assert run(parser, "alpha").out == "['alpha']\n"
assert run(parser, "alpha beta gamma").out == "['alpha', 'beta', 'gamma']\n"
def test_regression_issue212_funcsig_centric_positional():
"""
Issue #212: a combination of nargs with list as default value would result
in a nested list instead of a flat list.
Variation: default value via function signature (positional).
"""
@argh.arg("paths", nargs="*")
def func(paths: Optional[List[str]] = ["one", "two"]):
return f"{paths}"
parser = DebugArghParser()
parser.set_default_command(
func, name_mapping_policy=argh.assembling.NameMappingPolicy.BY_NAME_IF_KWONLY
)
assert run(parser, "").out == "['one', 'two']\n"
assert run(parser, "alpha").out == "['alpha']\n"
assert run(parser, "alpha beta gamma").out == "['alpha', 'beta', 'gamma']\n"
def test_regression_issue212_funcsig_centric_named():
"""
Issue #212: a combination of nargs with list as default value would result
in a nested list instead of a flat list.
Variation: default value via function signature (named).
"""
@argh.arg("--paths", nargs="*")
def func(*, paths: Optional[List[str]] = ["one", "two"]):
return f"{paths}"
parser = DebugArghParser()
parser.set_default_command(func)
assert run(parser, "").out == "['one', 'two']\n"
assert run(parser, "--paths alpha").out == "['alpha']\n"
assert run(parser, "--paths alpha beta gamma").out == "['alpha', 'beta', 'gamma']\n"
def test_regression_issue224():
"""
Issue #224: @arg param `dest` was ignored and Argh was unable to map the
declaration onto the function signature.
Use case: expose a function argument with a different name in the CLI.
"""
@argh.arg("-l", dest="list_files")
def func(*, list_files=False):
return f"list_files={list_files}"
parser = DebugArghParser()
parser.set_default_command(func)
assert run(parser, "").out == "list_files=False\n"
assert run(parser, "-l").out == "list_files=True\n"
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1720893285.480846
argh-0.31.3/tests/test_typing_hints.py 0000644 0000000 0000000 00000003753 14644537545 014770 0 ustar 00 from typing import List, Literal, Optional, Union
import pytest
from argh.assembling import TypingHintArgSpecGuesser
@pytest.mark.parametrize("arg_type", TypingHintArgSpecGuesser.BASIC_TYPES)
def test_simple_types(arg_type):
guess = TypingHintArgSpecGuesser.typing_hint_to_arg_spec_params
# just the basic type
assert guess(arg_type) == {"type": arg_type}
# basic type or None
assert guess(Optional[arg_type]) == {
"type": arg_type,
"required": False,
}
assert guess(Union[None, arg_type]) == {"required": False}
# multiple basic types: the first one is used and None is looked up
assert guess(Union[arg_type, str, None]) == {
"type": arg_type,
"required": False,
}
assert guess(Union[str, arg_type, None]) == {
"type": str,
"required": False,
}
def test_list():
guess = TypingHintArgSpecGuesser.typing_hint_to_arg_spec_params
assert guess(list) == {"nargs": "*"}
assert guess(List) == {"nargs": "*"}
assert guess(Optional[list]) == {"nargs": "*", "required": False}
assert guess(Optional[List]) == {"nargs": "*", "required": False}
assert guess(List[str]) == {"nargs": "*", "type": str}
assert guess(List[int]) == {"nargs": "*", "type": int}
assert guess(Optional[List[str]]) == {"nargs": "*", "type": str, "required": False}
assert guess(Optional[List[tuple]]) == {"nargs": "*", "required": False}
assert guess(List[list]) == {"nargs": "*"}
assert guess(List[tuple]) == {"nargs": "*"}
def test_literal():
guess = TypingHintArgSpecGuesser.typing_hint_to_arg_spec_params
assert guess(Literal["a"]) == {"choices": ("a",), "type": str}
assert guess(Literal["a", "b"]) == {"choices": ("a", "b"), "type": str}
assert guess(Literal[1]) == {"choices": (1,), "type": int}
@pytest.mark.parametrize("arg_type", (dict, tuple))
def test_unusable_types(arg_type):
guess = TypingHintArgSpecGuesser.typing_hint_to_arg_spec_params
assert guess(arg_type) == {}
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1720893285.480846
argh-0.31.3/tests/test_utils.py 0000644 0000000 0000000 00000002467 14644537545 013412 0 ustar 00 """
Unit Tests For Utility Functions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from argparse import ArgumentParser, _SubParsersAction
import pytest
from argh.utils import SubparsersNotDefinedError, get_subparsers, unindent
def test_util_unindent():
"Self-test the unindent() helper function"
# target case
one = """
a
b
c
"""
assert (
unindent(one)
== """
a
b
c
"""
)
# edge case: lack of indentation on first non-empty line
two = """
a
b
c
"""
assert unindent(two) == two
# edge case: unexpectedly unindented in between
three = """
a
b
c
"""
assert (
unindent(three)
== """
a
b
c
"""
)
def test_get_subparsers_existing() -> None:
parser = ArgumentParser()
parser.add_subparsers(help="hello")
sub_parsers_action = get_subparsers(parser)
assert isinstance(sub_parsers_action, _SubParsersAction)
assert sub_parsers_action.help == "hello"
def test_get_subparsers_create() -> None:
parser = ArgumentParser()
sub_parsers_action = get_subparsers(parser, create=True)
assert isinstance(sub_parsers_action, _SubParsersAction)
def test_get_subparsers_error() -> None:
parser = ArgumentParser()
with pytest.raises(SubparsersNotDefinedError):
get_subparsers(parser)
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1720893285.480846
argh-0.31.3/tox.ini 0000644 0000000 0000000 00000002025 14644537545 011000 0 ustar 00 [tox]
envlist =
py38
py39
py310
py311
py312
py313
pypy3
as-module
lint
docs
skipdist = true
isolated_build = true
skip_missing_interpreters = true
[gh-actions]
# https://github.com/ymyzk/tox-gh-actions
python =
3.8: py38
3.9: py39
3.10: py310
3.11: py311,lint,as-module
3.12: py312
3.13: py313
pypy-3.9: pypy3
pypy-3.10: pypy3
[testenv]
description = run unit tests
extras = test
commands =
pytest --cov=argh --cov-report html --cov-fail-under 100 {posargs:tests}
setenv =
PYTHONPATH=src
[testenv:as-module]
description = run unit tests, ensure they don't depend on specific prog name
commands =
python -m pytest {posargs:tests}
[testenv:docs]
description = build the HTML docs using sphinx-build
extras = docs
changedir = docs/
allowlist_externals = rm
commands =
rm -rf docs/build
sphinx-build . build --color -W --keep-going -n -b html {posargs}
[testenv:lint]
description = verify with linters
extras = linters
commands =
pre-commit run -a
argh-0.31.3/PKG-INFO 0000644 0000000 0000000 00000016330 00000000000 010506 0 ustar 00 Metadata-Version: 2.1
Name: argh
Version: 0.31.3
Summary: Plain Python functions as CLI commands without boilerplate
Keywords: cli,command line,argparse,optparse,argument,option
Author-email: Andy Mikhaylenko
Maintainer-email: Andy Mikhaylenko
Requires-Python: >=3.8
Description-Content-Type: text/x-rst
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Software Development :: User Interfaces
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Dist: argcomplete >= 2.0 ; extra == "completion"
Requires-Dist: sphinx >= 7.2 ; extra == "docs"
Requires-Dist: sphinx-pyproject == 0.3 ; extra == "docs"
Requires-Dist: sphinx_rtd_theme >= 2.0 ; extra == "docs"
Requires-Dist: readthedocs-sphinx-search == 0.3.2 ; extra == "docs"
Requires-Dist: pre-commit >= 3.4.0 ; extra == "linters"
Requires-Dist: tox >= 4.11.3 ; extra == "test"
Requires-Dist: pytest >= 7.4 ; extra == "test"
Requires-Dist: pytest-cov >= 4.1 ; extra == "test"
Project-URL: Discussions, https://github.com/neithere/argh/discussions
Project-URL: Documentation, https://argh.readthedocs.io/en/latest
Project-URL: Homepage, https://github.com/neithere/argh
Project-URL: Issue Tracker, https://github.com/neithere/argh/issues
Project-URL: Releases, https://github.com/neithere/argh/releases
Provides-Extra: completion
Provides-Extra: docs
Provides-Extra: linters
Provides-Extra: test
Argh: The Effortless CLI
========================
.. image:: https://github.com/neithere/argh/actions/workflows/lint-and-test.yml/badge.svg
:target: https://github.com/neithere/argh/actions/workflows/lint-and-test.yml
.. image:: https://img.shields.io/pypi/format/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://img.shields.io/pypi/status/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://img.shields.io/pypi/v/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://img.shields.io/pypi/pyversions/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://img.shields.io/pypi/dd/argh.svg
:target: https://pypi.python.org/pypi/argh
.. image:: https://readthedocs.org/projects/argh/badge/?version=stable
:target: http://argh.readthedocs.org/en/stable/
.. image:: https://readthedocs.org/projects/argh/badge/?version=latest
:target: http://argh.readthedocs.org/en/latest/
**The power of Argparse with plain Python functions!**
Building a command-line interface? Found yourself uttering "argh!" while
struggling with the API of `argparse`? Don't like the complexity but need
the power?
`Argh` builds on the power of `argparse` (which comes with Python) and makes it
really easy to use. It eliminates the complex API and lets you "dispatch"
ordinary Python functions as CLI commands.
Installation
------------
::
$ pip install argh
Example
-------
.. code-block:: python
import argh
def verify_paths(paths: list[str], *, verbose: bool = False):
"""
Verify that all given paths exist.
"""
for path in paths:
if verbose:
print(f"Checking {path}...")
assert os.path.exists(path)
argh.dispatch_command(verify_paths)
Now you can run the script like this:
.. code-block:: bash
$ python app.py foo.txt bar/quux.txt
$ python app.py foo.txt bar/quux.txt --verbose
Checking foo.txt...
Checking bar/quux.txt...
$ python app.py -h
usage: app.py [-h] [-v] [paths ...]
Verify that all given paths exist.
positional arguments:
paths -
options:
-h, --help show this help message and exit
-v, --verbose False
Please check the documentation for examples of multiple commands, modularity,
help generation, advanced type annotations inspection, decorators and more:
* `Quick Start `_
* `Tutorial `_
Why Argh?
---------
`Argh`-powered applications are *simple* but *flexible*:
:Pythonic, KISS:
Commands are plain Python functions. Almost no CLI-specific API to learn.
:Reusable:
Endpoint functions can be used directly outside of CLI context.
:Static typing friendly:
100% of the code including endpoint functions can be type-checked.
Argh is driven primarily by type annotations.
:DRY:
Don't Repeat Yourself. The amount of boilerplate code is minimal.
Among other things, `Argh` will:
* infer command name from function name;
* infer arguments from function signature;
* infer argument types, actions and much more from annotations.
:Modular:
Declaration of commands can be decoupled from assembling and dispatching.
:Layered:
The complexity of code raises with requirements.
:Transparent:
You can directly access `argparse.ArgumentParser` if needed.
:Subcommands:
Easily nested commands. Argh isolates the complexity of subparsers.
:NIH free:
`Argh` supports *completion*, *progress bars* and everything else by being
friendly to excellent 3rd-party libraries. No need to reinvent the wheel.
:Compact:
No dependencies apart from Python's standard library.
Links
-----
See also the `project page on GitHub`_, `documentation`_ and `PyPI page`_.
.. _project page on GitHub: http://github.com/neithere/argh/
.. _documentation: http://argh.readthedocs.org
.. _PyPI page: http://pypi.python.org/pypi/argh
Author
------
Developed by Andrey Mikhaylenko since 2010.
See `contributors `_
for a list of contributors to this library.
Contribute
----------
The fastest way to improve this project is to submit tested and documented
patches or detailed bug reports.
Donate
------
You can `donate via Liberapay`_. This may speed up development or simply
make the original author happy :)
.. _donate via Liberapay: https://liberapay.com/neithere/donate
Licensing
---------
Argh is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Argh 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Argh. If not, see .