././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1637807370.3033462
taskw-1.3.1/ 0000775 0001750 0001750 00000000000 00000000000 014214 5 ustar 00acoddington acoddington ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/LICENSE.txt 0000664 0001750 0001750 00000104513 00000000000 016043 0 ustar 00acoddington acoddington 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 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/MANIFEST.in 0000664 0001750 0001750 00000000272 00000000000 015753 0 ustar 00acoddington acoddington include README.rst
include LICENSE.txt
include requirements.txt
include test_requirements.txt
include .tox_tests.sh
include tox.ini
include setup.cfg
recursive-include taskw/test/data *
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1637807370.3033462
taskw-1.3.1/PKG-INFO 0000664 0001750 0001750 00000012374 00000000000 015320 0 ustar 00acoddington acoddington Metadata-Version: 1.1
Name: taskw
Version: 1.3.1
Summary: Python bindings for your taskwarrior database
Home-page: http://github.com/ralphbean/taskw
Author: Ralph Bean
Author-email: ralph.bean@gmail.com
License: GPLv3+
Description:
This is a python API for the `taskwarrior `_ command
line tool.
It contains two implementations: ``taskw.TaskWarriorShellout`` and
``taskw.TaskWarriorDirect``. The first implementation is the supported one
recommended by the upstream taskwarrior core project. It uses the ``task
export`` and ``task import`` commands to manipulate the task database. The
second implementation opens the task db file itself and directly manipulates
it. It exists for backwards compatibility, but should only be used when
necessary.
Build Status
------------
.. |master| image:: https://secure.travis-ci.org/ralphbean/taskw.png?branch=master
:alt: Build Status - master branch
:target: http://travis-ci.org/#!/ralphbean/taskw
.. |develop| image:: https://secure.travis-ci.org/ralphbean/taskw.png?branch=develop
:alt: Build Status - develop branch
:target: http://travis-ci.org/#!/ralphbean/taskw
+----------+-----------+
| Branch | Status |
+==========+===========+
| master | |master| |
+----------+-----------+
| develop | |develop| |
+----------+-----------+
Getting taskw
-------------
Installing
++++++++++
Using ``taskw`` requires that you first install `taskwarrior
`_.
Installing it from http://pypi.python.org/pypi/taskw is easy with ``pip``::
$ pip install taskw
The Source
++++++++++
You can find the source on github at http://github.com/ralphbean/taskw
Examples
--------
Looking at tasks
++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> tasks = w.load_tasks()
>>> tasks.keys()
['completed', 'pending']
>>> type(tasks['pending'])
>>> type(tasks['pending'][0])
Adding tasks
++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> w.task_add("Eat food")
>>> w.task_add("Take a nap", priority="H", project="life", due="1359090000")
Retrieving tasks
++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> w.get_task(id=5)
Updating tasks
++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> id, task = w.get_task(id=14)
>>> task['project'] = 'Updated project name'
>>> w.task_update(task)
Deleting tasks
++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> w.task_delete(id=3)
Completing tasks
++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> w.task_done(id=46)
Being Flexible
++++++++++++++
You can point ``taskw`` at different taskwarrior databases.
>>> from taskw import TaskWarrior
>>> w = TaskWarrior(config_filename="~/some_project/.taskrc")
>>> w.task_add("Use 'taskw'.")
Looking at the config
+++++++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> config = w.load_config()
>>> config['data']['location']
'/home/threebean/.task'
>>> config['_forcecolor']
'yes'
Using Python-appropriate Types (Dates, UUIDs, etc)
++++++++++++++++++++++++++++++++++++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior(marshal=True)
>>> w.get_task(id=10)
(10,
{
'description': 'Hello there!',
'entry': datetime.datetime(2014, 3, 14, 14, 18, 40, tzinfo=tzutc())
'id': 10,
'project': 'Saying Hello',
'status': 'pending',
'uuid': UUID('4882751a-3966-4439-9675-948b1152895c')
}
)
Keywords: taskwarrior task
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: License :: OSI Approved :: GNU General Public License (GPL)
Classifier: Intended Audience :: Developers
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/README.rst 0000664 0001750 0001750 00000007005 00000000000 015705 0 ustar 00acoddington acoddington taskw - Python API for the taskwarrior DB
=========================================
.. split here
This is a python API for the `taskwarrior `_ command
line tool.
It contains two implementations: ``taskw.TaskWarriorShellout`` and
``taskw.TaskWarriorDirect``. The first implementation is the supported one
recommended by the upstream taskwarrior core project. It uses the ``task
export`` and ``task import`` commands to manipulate the task database. The
second implementation opens the task db file itself and directly manipulates
it. It exists for backwards compatibility, but should only be used when
necessary.
Build Status
------------
.. |master| image:: https://secure.travis-ci.org/ralphbean/taskw.png?branch=master
:alt: Build Status - master branch
:target: http://travis-ci.org/#!/ralphbean/taskw
.. |develop| image:: https://secure.travis-ci.org/ralphbean/taskw.png?branch=develop
:alt: Build Status - develop branch
:target: http://travis-ci.org/#!/ralphbean/taskw
+----------+-----------+
| Branch | Status |
+==========+===========+
| master | |master| |
+----------+-----------+
| develop | |develop| |
+----------+-----------+
Getting taskw
-------------
Installing
++++++++++
Using ``taskw`` requires that you first install `taskwarrior
`_.
Installing it from http://pypi.python.org/pypi/taskw is easy with ``pip``::
$ pip install taskw
The Source
++++++++++
You can find the source on github at http://github.com/ralphbean/taskw
Examples
--------
Looking at tasks
++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> tasks = w.load_tasks()
>>> tasks.keys()
['completed', 'pending']
>>> type(tasks['pending'])
>>> type(tasks['pending'][0])
Adding tasks
++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> w.task_add("Eat food")
>>> w.task_add("Take a nap", priority="H", project="life", due="1359090000")
Retrieving tasks
++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> w.get_task(id=5)
Updating tasks
++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> id, task = w.get_task(id=14)
>>> task['project'] = 'Updated project name'
>>> w.task_update(task)
Deleting tasks
++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> w.task_delete(id=3)
Completing tasks
++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> w.task_done(id=46)
Being Flexible
++++++++++++++
You can point ``taskw`` at different taskwarrior databases.
>>> from taskw import TaskWarrior
>>> w = TaskWarrior(config_filename="~/some_project/.taskrc")
>>> w.task_add("Use 'taskw'.")
Looking at the config
+++++++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior()
>>> config = w.load_config()
>>> config['data']['location']
'/home/threebean/.task'
>>> config['_forcecolor']
'yes'
Using Python-appropriate Types (Dates, UUIDs, etc)
++++++++++++++++++++++++++++++++++++++++++++++++++
>>> from taskw import TaskWarrior
>>> w = TaskWarrior(marshal=True)
>>> w.get_task(id=10)
(10,
{
'description': 'Hello there!',
'entry': datetime.datetime(2014, 3, 14, 14, 18, 40, tzinfo=tzutc())
'id': 10,
'project': 'Saying Hello',
'status': 'pending',
'uuid': UUID('4882751a-3966-4439-9675-948b1152895c')
}
)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295332.0
taskw-1.3.1/requirements.txt 0000664 0001750 0001750 00000000041 00000000000 017473 0 ustar 00acoddington acoddington six
python-dateutil
pytz
kitchen
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1637807370.3033462
taskw-1.3.1/setup.cfg 0000664 0001750 0001750 00000000142 00000000000 016032 0 ustar 00acoddington acoddington [tool:pytest]
norecursedirs = lib
addopts = -p no:warnings
[egg_info]
tag_build =
tag_date = 0
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1637806930.0
taskw-1.3.1/setup.py 0000664 0001750 0001750 00000004274 00000000000 015735 0 ustar 00acoddington acoddington import os
import sys
import uuid
from setuptools import setup, find_packages
f = open('README.rst')
long_description = f.read().strip()
long_description = long_description.split('split here', 1)[1]
f.close()
REQUIREMENTS_FILES = {
'test': 'test_requirements.txt',
'install': 'requirements.txt',
}
REQUIREMENTS = {}
for category, filename in REQUIREMENTS_FILES.items():
requirements_path = os.path.join(
os.path.dirname(__file__),
filename
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except ImportError:
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
REQUIREMENTS[category] = requirements
if sys.version_info < (2, 7):
REQUIREMENTS['test'].append('unittest2')
REQUIREMENTS['install'].append('ordereddict')
setup(name='taskw',
version='1.3.1',
description="Python bindings for your taskwarrior database",
long_description=long_description,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"License :: OSI Approved :: GNU General Public License (GPL)",
"Intended Audience :: Developers",
],
keywords='taskwarrior task',
author='Ralph Bean',
author_email='ralph.bean@gmail.com',
url='http://github.com/ralphbean/taskw',
license='GPLv3+',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=REQUIREMENTS['install'],
entry_points="""
# -*- Entry points: -*-
""",
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1637807370.2993462
taskw-1.3.1/taskw/ 0000775 0001750 0001750 00000000000 00000000000 015345 5 ustar 00acoddington acoddington ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/__init__.py 0000664 0001750 0001750 00000000727 00000000000 017464 0 ustar 00acoddington acoddington from taskw.warrior import (
TaskWarrior,
TaskWarriorDirect,
TaskWarriorShellout,
TaskWarriorExperimental,
)
from taskw.utils import clean_task, encode_task, decode_task
from taskw.utils import encode_task_experimental
__all__ = [
TaskWarrior,
TaskWarriorShellout,
TaskWarriorDirect,
TaskWarriorExperimental, # This is deprecated. Use TaskWarriorShellout
clean_task,
encode_task,
decode_task,
encode_task_experimental,
]
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/exceptions.py 0000664 0001750 0001750 00000001116 00000000000 020077 0 ustar 00acoddington acoddington import sys
class TaskwarriorError(Exception):
def __init__(self, command, stderr, stdout, code):
self.command = command
self.stderr = stderr.strip()
self.stdout = stdout.strip()
self.code = code
super(TaskwarriorError, self).__init__(self.stderr)
def __unicode__(self):
return "%r #%s; stderr:\"%s\"; stdout:\"%s\"" % (
self.command,
self.code,
self.stderr,
self.stdout,
)
def __str__(self):
return self.__unicode__().encode(sys.getdefaultencoding(), 'replace')
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1637807370.2993462
taskw-1.3.1/taskw/fields/ 0000775 0001750 0001750 00000000000 00000000000 016613 5 ustar 00acoddington acoddington ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/fields/__init__.py 0000664 0001750 0001750 00000000536 00000000000 020730 0 ustar 00acoddington acoddington from .base import Field
from .annotationarray import AnnotationArrayField
from .array import ArrayField
from .commaseparateduuid import CommaSeparatedUUIDField
from .choice import ChoiceField
from .date import DateField
from .duration import DurationField
from .numeric import NumericField
from .string import StringField
from .uuid import UUIDField
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/fields/annotationarray.py 0000664 0001750 0001750 00000003663 00000000000 022406 0 ustar 00acoddington acoddington from dateutil.parser import parse
import six
from .array import ArrayField
from .base import DirtyableList
class Annotation(six.text_type):
""" A special type of string that we'll use for storing annotations.
This is, for all intents and purposes, really just a string, but
it does allow us to store additional information if we have it -- in
this application: the annotation's entry date.
"""
def __new__(self, description, entry=None):
return six.text_type.__new__(self, description)
def __init__(self, description, entry=None):
self._entry = entry
super(Annotation, self).__init__()
@property
def entry(self):
if self._entry:
return parse(self._entry)
return self._entry
class AnnotationArrayField(ArrayField):
""" A special case of the ArrayField handling idiosyncrasies of Annotations
Taskwarrior will currently return to you a dictionary of values --
the annotation's date and description -- for each annotation, but
given that we cannot create annotations with a date, let's instead
return something that behaves like a string (but from which you can
extract an entry date if one exists).
"""
def deserialize(self, value):
if not value:
value = DirtyableList([])
elements = []
for annotation in value:
if isinstance(annotation, dict):
elements.append(
Annotation(
annotation['description'],
annotation['entry'],
)
)
else:
elements.append(Annotation(annotation))
return super(AnnotationArrayField, self).deserialize(elements)
def serialize(self, value):
if not value:
value = []
return super(AnnotationArrayField, self).serialize(
[six.text_type(entry) for entry in value]
)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/fields/array.py 0000664 0001750 0001750 00000000617 00000000000 020307 0 ustar 00acoddington acoddington from .base import DirtyableList, Field
class ArrayField(Field):
def deserialize(self, value):
if not value:
value = DirtyableList([])
return DirtyableList(value)
def serialize(self, value):
if not value:
value = []
if not hasattr(value, '__iter__'):
raise ValueError("Value must be list or tuple.")
return value
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/fields/base.py 0000664 0001750 0001750 00000003367 00000000000 020110 0 ustar 00acoddington acoddington import copy
import sys
import six
class Field(object):
def __init__(self, label=None, read_only=False):
self._label = label
self._read_only = read_only
super(Field, self).__init__()
@property
def read_only(self):
return self._read_only
@property
def label(self):
return self._label
def deserialize(self, value):
return value
def serialize(self, value):
return value
def __str__(self):
if sys.version_info >= (3, ):
return self.label
return self.__unicode__().encode(sys.getdefaultencoding(), 'replace')
def __unicode__(self):
return self.label
def __repr__(self):
return "<{cls} '{label}'>".format(
cls=six.text_type(self.__class__.__name__),
label=six.text_type(self) if self._label else '(No Label)',
)
def __eq__(self, other):
if self.label != other.label:
return False
if self.read_only != other.read_only:
return False
if self.__class__ != other.__class__:
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
class Dirtyable(object):
""" Superclass for all objects implementing trackability."""
def __init__(self, value=None):
self._original_value = copy.deepcopy(value)
super(Dirtyable, self).__init__(value)
def get_changes(self, keep=False):
if self._original_value == self:
return {}
result = (self._original_value, self)
if not keep:
self._original_value = copy.deepcopy(self)
return result
class DirtyableList(Dirtyable, list):
pass
class DirtyableDict(Dirtyable, dict):
pass
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/fields/choice.py 0000664 0001750 0001750 00000002216 00000000000 020420 0 ustar 00acoddington acoddington from .base import Field
class ChoiceField(Field):
def __init__(
self,
choices=None,
nullable=False,
case_sensitive=False,
**kwargs
):
self._choices = choices if choices else []
self._case_sensitive = case_sensitive
super(ChoiceField, self).__init__(**kwargs)
def is_valid_choice(self, value):
if value is None and value not in self._choices:
return False
if value is None and value in self._choices:
return True
if self._case_sensitive and value in self._choices:
return True
elif (
not self._case_sensitive
and value.upper() in [v.upper() for v in self._choices if v]
):
return True
elif self._case_sensitive and value in self._choices:
return True
return False
def serialize(self, value):
if not self.is_valid_choice(value):
raise ValueError(
"'%s' is not a valid choice; choices: %s" % (
value,
self._choices,
)
)
return value
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295332.0
taskw-1.3.1/taskw/fields/commaseparateduuid.py 0000664 0001750 0001750 00000002355 00000000000 023046 0 ustar 00acoddington acoddington from __future__ import absolute_import
from distutils.version import LooseVersion
import uuid
from .base import DirtyableList, Field
class CommaSeparatedUUIDField(Field):
version = LooseVersion('2.4')
def deserialize(self, value):
if not value:
return DirtyableList([])
# In task-2.5, this moved from a comma-separated string to a real list.
# here we allow a migration path where old splitable strings are
# handled as well as newschool lists.
if hasattr(value, 'split'):
value = value.split(',')
return DirtyableList([uuid.UUID(v) for v in value])
def serialize(self, value):
if not value:
value = []
if not hasattr(value, '__iter__'):
raise ValueError("Value must be list or tuple, not %r." % value)
if self.version < LooseVersion('2.5'):
return ','.join([str(v) for v in value])
else:
# We never hit this second code branch now. taskwarrior changed
# API slightly in version 2.5, but we're just going to go with
# backwards compatibility for now.
# Some day we should switch wholesale to the new path.
return [str(v) for v in value]
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/fields/date.py 0000664 0001750 0001750 00000001643 00000000000 020106 0 ustar 00acoddington acoddington import datetime
import dateutil
from dateutil.parser import parse
import pytz
from taskw.utils import DATE_FORMAT
from .base import Field
class DateField(Field):
def deserialize(self, value):
if not value:
return value
value = parse(value)
if not value.tzinfo:
value = value.replace(tzinfo=pytz.utc)
return value
def serialize(self, value):
if isinstance(value, datetime.datetime):
if not value.tzinfo:
# Dates not having timezone information should be
# assumed to be in local time
value = value.replace(tzinfo=dateutil.tz.tzlocal())
# All times should be converted to UTC before serializing
value = value.astimezone(pytz.utc).strftime(DATE_FORMAT)
elif isinstance(value, datetime.date):
value = value.strftime(DATE_FORMAT)
return value
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/fields/duration.py 0000664 0001750 0001750 00000000354 00000000000 021014 0 ustar 00acoddington acoddington from .string import StringField
class DurationField(StringField):
""" In the future this will handle transforming recurrence patterns.
See https://github.com/taskwarrior/task/blob/2.3.0/src/Duration.cpp#L41
"""
pass
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295418.0
taskw-1.3.1/taskw/fields/numeric.py 0000664 0001750 0001750 00000002077 00000000000 020635 0 ustar 00acoddington acoddington import numbers
from .base import Field
class NumericField(Field):
def serialize(self, value):
if not isinstance(value, numbers.Number):
if value:
raise ValueError("Value must be numeric.")
return value
def deserialize(self, value):
if value is None:
return value
elif isinstance(value, str):
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
elif isinstance(value, int) or isinstance(value, float):
# already desialized
return value
else:
raise ValueError("Unhandled type [{}] passed during deserialization for value [{}]"
.format(type(value), value))
# If we've made it this far, somehow Taskwarrior has
# a non-numeric value stored in this field; this shouldn't
# happen, but it's probably inappropriate to blow up.
return value
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295332.0
taskw-1.3.1/taskw/fields/string.py 0000664 0001750 0001750 00000002130 00000000000 020467 0 ustar 00acoddington acoddington import logging
import six
from taskw.utils import encode_replacements_experimental
from .base import Field
logger = logging.getLogger(__name__)
class StringField(Field):
def deserialize(self, value):
# If value is None, let's just let it pass through
if not value:
return value
if not isinstance(value, six.string_types):
value = six.text_type(value)
for left, right in six.iteritems(encode_replacements_experimental):
value = value.replace(right, left)
return value
def serialize(self, value):
# If value is None let it pass through
if not value:
return value
if not isinstance(value, six.string_types):
string_value = six.text_type(value)
logger.debug(
"Value %s serialized to string as '%s'",
repr(value),
string_value
)
value = string_value
for left, right in six.iteritems(encode_replacements_experimental):
value = value.replace(left, right)
return value
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/fields/uuid.py 0000664 0001750 0001750 00000000655 00000000000 020141 0 ustar 00acoddington acoddington from __future__ import absolute_import
import uuid
from .base import Field
class UUIDField(Field):
def deserialize(self, value):
if not value:
return value
return uuid.UUID(value)
def serialize(self, value):
if isinstance(value, uuid.UUID):
value = str(value)
else:
# Just to make sure it's a UUID
uuid.UUID(value)
return value
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295332.0
taskw-1.3.1/taskw/task.py 0000664 0001750 0001750 00000020774 00000000000 016673 0 ustar 00acoddington acoddington import json
import logging
import os
import sys
import six
from taskw.fields import (
AnnotationArrayField,
ArrayField,
ChoiceField,
CommaSeparatedUUIDField,
DateField,
DurationField,
Field,
NumericField,
StringField,
UUIDField,
)
from taskw.fields.base import Dirtyable, DirtyableList, DirtyableDict
# Sentinel value for not specifying a default
UNSPECIFIED = object()
logger = logging.getLogger(__name__)
class Task(dict):
FIELDS = {
'annotations': AnnotationArrayField(label='Annotations'),
'depends': CommaSeparatedUUIDField(label='Depends Upon'),
'description': StringField(label='Description'),
'due': DateField(label='Due'),
'end': DateField(label='Ended'),
'entry': DateField(label='Entered'),
'id': NumericField(label='ID', read_only=True),
'imask': NumericField(label='Imask', read_only=True),
'mask': StringField(label='Mask', read_only=True),
'modified': DateField(label='Modified'),
'parent': StringField(label='Parent'),
'priority': ChoiceField(
choices=[None, 'H', 'M', 'L', ],
case_sensitive=False,
label='Priority'
),
'project': StringField(label='Project'),
'recur': DurationField(label='Recurrence'),
'scheduled': DateField(label='Scheduled'),
'start': DateField(label='Started'),
'status': ChoiceField(
choices=[
'pending',
'completed',
'deleted',
'waiting',
'recurring',
],
case_sensitive=False,
label='Status',
),
'tags': ArrayField(label='Tags'),
'until': DateField(label='Until'),
'urgency': NumericField(label='Urgency', read_only=True),
'uuid': UUIDField(label='UUID'),
'wait': DateField(label='Wait'),
}
def __init__(self, data, udas=None):
udas = udas or {}
self._fields = self.FIELDS.copy()
self._fields.update(udas)
self._changes = []
processed = {}
for k, v in six.iteritems(data):
processed[k] = self._deserialize(k, v, self._fields)
super(Task, self).__init__(processed)
@classmethod
def from_stub(cls, data, udas=None):
""" Create a Task from an already deserialized dict. """
udas = udas or {}
fields = cls.FIELDS.copy()
fields.update(udas)
processed = {}
for k, v in six.iteritems(data):
processed[k] = cls._serialize(k, v, fields)
return cls(processed, udas)
@classmethod
def from_input(cls, input_file=sys.stdin, modify=False, udas=None):
"""
Create a Task directly from stdin by reading one line. If modify=True,
two lines are expected, which is consistent with the Taskwarrior hook
system. The first line is interpreted as the original state of the Task,
and the second one as the new, modified state.
:param input_file: Input file. Defaults to sys.stdin.
:param modify: Flag for on-modify hook event. Defaults to False.
:param udas: Taskrc udas. Defaults to None.
:return Task
"""
original_task = input_file.readline().strip()
if modify:
modified_task = input_file.readline().strip()
return cls(json.loads(modified_task), udas=udas)
return cls(json.loads(original_task), udas=udas)
@classmethod
def _get_converter_for_field(cls, field, default=None, fields=None):
fields = fields or {}
converter = fields.get(field, None)
if not converter:
return default if default else Field()
return converter
@classmethod
def _deserialize(cls, key, value, fields):
""" Marshal incoming data into Python objects."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.deserialize(value)
@classmethod
def _serialize(cls, key, value, fields):
""" Marshal outgoing data into Taskwarrior's JSON format."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.serialize(value)
def _field_is_writable(self, key):
converter = self._get_converter_for_field(key, fields=self._fields)
if converter.read_only:
return False
return True
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def _record_change(self, key, from_, to):
self._changes.append((key, from_, to))
def get_changes(self, serialized=False, keep=False):
""" Get a journal of changes that have occurred
:param `serialized`:
Return changes in the serialized format used by TaskWarrior.
:param `keep_changes`:
By default, the list of changes is reset after running
``.get_changes``; set this to `True` if you would like to
keep the changes recorded following running this command.
:returns: A dictionary of 2-tuples of changes, where the key is the
name of the field that has changed, and the value is a 2-tuple
containing the original value and the final value respectively.
"""
results = {}
# Check for explicitly-registered changes
for k, f, t in self._changes:
if k not in results:
results[k] = [f, None]
results[k][1] = (
self._serialize(k, t, self._fields)
if serialized else t
)
# Check for changes on subordinate items
for k, v in six.iteritems(self):
if isinstance(v, Dirtyable):
result = v.get_changes(keep=keep)
if result:
if not k in results:
results[k] = [result[0], None]
results[k][1] = (
self._serialize(k, result[1], self._fields)
if serialized else result[1]
)
# Clear out recorded changes
if not keep:
self._changes = []
return results
def update(self, values, force=False):
""" Update this task dictionary
:returns: A dictionary mapping field names specified to be updated
and a boolean value indicating whether the field was changed.
"""
results = {}
for k, v in six.iteritems(values):
results[k] = self.__setitem__(k, v, force=force)
return results
def set(self, key, value):
""" Set a key's value regardless of whether a change is seen."""
return self.__setitem__(key, value, force=True)
def serialized(self):
""" Returns a serialized representation of this task."""
serialized = {}
for k, v in six.iteritems(self):
serialized[k] = self._serialize(k, v, self._fields)
return serialized
def serialized_changes(self, keep=False):
serialized = {}
for k, v in six.iteritems(self.get_changes(keep=keep)):
# Here, `v` is a 2-tuple of the field's original value
# and the field's new value.
_, to = v
serialized[k] = self._serialize(k, to, self._fields)
return serialized
def __setitem__(self, key, value, force=False):
if isinstance(value, dict) and not isinstance(value, DirtyableDict):
value = DirtyableDict(value)
elif isinstance(value, list) and not isinstance(value, DirtyableList):
value = DirtyableList(value)
existing_value = self.get(key)
if force or value != existing_value:
if force or existing_value or value:
# Do not attempt to record changes if both the existing
# and previous values are Falsy. We cannot distinguish
# between `''` and `None` for...reasons.
self._record_change(
key,
self.get(key),
value,
)
# Serialize just to make sure we can; it's better to throw
# this error early.
self._serialize(key, value, self._fields)
# Also make sure we raise an error if this field isn't
# writable at all.
if not self._field_is_writable(key):
raise ValueError("%s is a read-only field", key)
super(Task, self).__setitem__(key, value)
return True
return False
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295691.0
taskw-1.3.1/taskw/taskrc.py 0000664 0001750 0001750 00000011547 00000000000 017216 0 ustar 00acoddington acoddington import codecs
import logging
import os
from taskw.fields import (
ChoiceField,
DateField,
DurationField,
NumericField,
StringField
)
logger = logging.getLogger(__name__)
def sanitize(line):
comment_position = line.find('#')
if comment_position < 0:
return line.strip()
return line[:comment_position].strip()
class TaskRc(dict):
""" Access the user's taskRC using a dictionary-like interface.
There is a downside, though:
Unfortunately, collapsing our configuration into a dict has a
jarring limitation -- we can't store both of the following
simultaneously:
* color = on
* color.header = something
In this module, we err on the side of storing subkeys rather than the
actual value in situations where both are necessary.
Please forgive me.
"""
UDA_TYPE_MAP = {
'date': DateField,
'duration': DurationField,
'numeric': NumericField,
'string': StringField,
}
def __init__(self, path=None, overrides=None):
self.overrides = overrides if overrides else {}
if path:
self.path = os.path.normpath(
os.path.expanduser(
path
)
)
config = self._read(self.path)
else:
self.path = None
config = {}
super(TaskRc, self).__init__(config)
def _add_to_tree(self, config, key, value):
key_parts = key.split('.')
cursor = config
for part in key_parts[0:-1]:
if part not in cursor:
cursor[part] = {}
# See class docstring -- we can't store both a value and
# a dict in the same place.
if not isinstance(cursor[part], dict):
cursor[part] = {}
cursor = cursor[part]
cursor[key_parts[-1]] = value
return config
def _merge_trees(self, left, right):
if left is None:
left = {}
for key, value in right.items():
# See class docstring -- we can't store both a value and
# a dict in the same place.
if not isinstance(left, dict):
left = {}
if isinstance(value, dict):
left[key] = self._merge_trees(left.get(key), value)
else:
left[key] = value
return left
def _read(self, path):
config = {}
with codecs.open(path, 'r', 'utf8') as config_file:
for raw_line in config_file.readlines():
line = sanitize(raw_line)
if not line:
continue
if line.startswith('include '):
try:
left, right = line.split(' ')
config = self._merge_trees(
config,
TaskRc(right.strip())
)
except ValueError:
logger.exception(
"Error encountered while adding TaskRc at "
"'%s' (from TaskRc file at '%s')",
right.strip(),
self.path
)
else:
try:
left, right = line.split('=', 1)
key = left.strip()
value = right.strip()
config = self._add_to_tree(config, key, value)
except ValueError:
logger.exception(
"Error encountered while processing configuration "
"setting '%s' (from TaskRc file at '%s')",
line,
self.path,
)
return self._merge_trees(config, self.overrides)
def __delitem__(self, *args):
raise TypeError('TaskRc objects are immutable')
def __setitem__(self, item, value):
raise TypeError('TaskRc objects are immutable')
def update(self, value):
raise TypeError('TaskRc objects are immutable')
def get_udas(self):
raw_udas = self.get('uda', {})
udas = {}
for k, v in raw_udas.items():
tw_type = v.get('type', '')
label = v.get('label', None)
choices = v.get('values', None)
kwargs = {}
cls = self.UDA_TYPE_MAP.get(tw_type, StringField)
if choices:
cls = ChoiceField
kwargs['choices'] = choices.split(',')
if label:
kwargs['label'] = label
udas[k] = cls(**kwargs)
return udas
def __unicode__(self):
return 'TaskRc file at {path}'.format(
path=self.path
)
def __str__(self):
return self.__unicode__().encode('utf-8', 'REPLACE')
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1637807370.3033462
taskw-1.3.1/taskw/test/ 0000775 0001750 0001750 00000000000 00000000000 016324 5 ustar 00acoddington acoddington ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/test/__init__.py 0000664 0001750 0001750 00000000000 00000000000 020423 0 ustar 00acoddington acoddington ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1637807370.3033462
taskw-1.3.1/taskw/test/data/ 0000775 0001750 0001750 00000000000 00000000000 017235 5 ustar 00acoddington acoddington ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/test/data/default.taskrc 0000664 0001750 0001750 00000000204 00000000000 022066 0 ustar 00acoddington acoddington data.location = ~/.task
alpha.one = yes
alpha.two = 2
beta.one = TRUE
include taskw/test/data/included.taskrc
gamma.one = TRUE
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295332.0
taskw-1.3.1/taskw/test/data/empty.taskrc 0000664 0001750 0001750 00000000000 00000000000 021572 0 ustar 00acoddington acoddington ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/test/data/included.taskrc 0000664 0001750 0001750 00000000233 00000000000 022233 0 ustar 00acoddington acoddington beta.one = FALSE
gamma.one = FALSE
uda.a.type = numeric
uda.a.label = Alpha
uda.b.type = string
uda.b.label = Beta
uda.b.values = Strontium-90,Hydrogen-3
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1637806905.0
taskw-1.3.1/taskw/test/test_datas.py 0000664 0001750 0001750 00000045315 00000000000 021041 0 ustar 00acoddington acoddington import os
import shutil
import tempfile
import datetime
import dateutil.tz
import pytest
from taskw import TaskWarriorDirect, TaskWarriorShellout
TASK = {'description': "task 2 http://www.google.com/",
'entry': "1325011643",
'project': "work",
'start': "1326079920", 'status': "pending",
'uuid': "c1c431ea-f0dc-4683-9a20-e64fcfa65fd1"}
class _BaseTestDB(object):
def setup(self):
# Sometimes the 'task' command line tool is not installed.
if self.should_skip():
pytest.skip(
"%r unsupported on this system" % (self.class_to_test)
)
# Create some temporary config stuff
fd, fname = tempfile.mkstemp(prefix='taskw-testsrc')
dname = tempfile.mkdtemp(prefix='taskw-tests-data')
with open(fname, 'w') as f:
f.writelines([
'data.location=%s\n' % dname,
'uda.somestring.label=Testing String\n',
'uda.somestring.type=string\n',
'uda.somedate.label=Testing Date\n',
'uda.somedate.type=date\n',
'uda.somenumber.label=Testing Number\n',
'uda.somenumber.type=numeric\n',
])
# Create empty .data files
for piece in ['completed', 'pending', 'undo']:
with open(os.path.sep.join([dname, piece + '.data']), 'w'):
pass
# Save names for .tearDown()
self.fname, self.dname = fname, dname
# Create the taskwarrior db object that each test will use.
self.tw = self.class_to_test(config_filename=fname)
# Create a taskwarrior db object for tests where marshal=True,
# but only for TaskwarriorShellout
if self.class_to_test == TaskWarriorShellout:
self.tw_marshal = self.class_to_test(config_filename=fname,
marshal=True)
def tearDown(self):
os.remove(self.fname)
shutil.rmtree(self.dname)
def test_has_two_categories(self):
tasks = self.tw.load_tasks()
assert len(tasks) == 2
assert 'pending' in tasks
assert 'completed' in tasks
def test_empty_db(self):
tasks = self.tw.load_tasks()
assert len(sum(tasks.values(), [])) == 0
def test_add(self):
self.tw.task_add("foobar")
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
def test_unchanging_load_tasks(self):
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 0
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 0
def test_completion_raising_unspecified(self):
with pytest.raises(KeyError):
self.tw.task_done()
def test_completing_task_by_id_unspecified(self):
self.tw.task_add("foobar")
self.tw.task_done(id=1)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 0
assert len(tasks['completed']) == 1
assert len(sum(tasks.values(), [])) == 1
assert tasks['completed'][0]['end'] is not None
assert tasks['completed'][0]['status'] == 'completed'
def test_completing_task_by_id_specified(self):
self.tw.task_add("foobar")
self.tw.task_done(id=1)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 0
assert len(tasks['completed']) == 1
assert len(sum(tasks.values(), [])) == 1
assert tasks['completed'][0]['status'] == 'completed'
def test_completing_task_by_id_retrieved(self):
task = self.tw.task_add("foobar")
self.tw.task_done(id=task['id'])
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 0
assert len(tasks['completed']) == 1
assert len(sum(tasks.values(), [])) == 1
assert tasks['completed'][0]['status'] == 'completed'
def test_completing_task_by_uuid(self):
self.tw.task_add("foobar")
uuid = self.tw.load_tasks()['pending'][0]['uuid']
self.tw.task_done(uuid=uuid)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 0
assert len(tasks['completed']) == 1
assert len(sum(tasks.values(), [])) == 1
assert tasks['completed'][0]['status'] == 'completed'
def test_get_task_mismatch(self):
self.tw.task_add("foobar")
self.tw.task_add("bazbar")
uuid = self.tw.load_tasks()['pending'][0]['uuid']
with pytest.raises(KeyError):
self.tw.get_task(id=2, uuid=uuid) # which one?
def test_updating_task(self):
self.tw.task_add("foobar")
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
task = tasks['pending'][0]
task["priority"] = "L"
self.tw.task_update(task)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
assert tasks['pending'][0]['priority'] == 'L'
# For compatibility with the direct and shellout modes.
# Shellout returns more information.
try:
# Shellout mode returns the correct urgency, so,
# let's just not compare for now.
del tasks['pending'][0]['urgency']
del task['urgency']
# Also, experimental mode returns the id. So, avoid comparing.
del tasks['pending'][0]['id']
# Task 2.2.0 adds a "modified" field, so delete this.
del tasks['pending'][0]['modified']
except Exception:
pass
# But Task 2.4.0 puts the modified field in earlier
if 'modified' in task:
del task['modified']
assert tasks['pending'][0] == task
def test_update_exc(self):
task = dict(description="lol")
with pytest.raises(KeyError):
self.tw.task_update(task)
def test_add_complicated(self):
self.tw.task_add(
"foobar",
uuid="1234-1234",
project="some_project"
)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
def test_add_timestamp(self):
self.tw.task_add(
"foobar",
uuid="1234-1234",
project="some_project",
entry="20110101T000000Z",
)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
assert tasks['pending'][0]['entry'] == "20110101T000000Z"
def test_add_datetime(self):
self.tw.task_add(
"foobar",
uuid="1234-1234",
project="some_project",
entry=datetime.datetime(2011, 1, 1, tzinfo=dateutil.tz.tzutc()),
)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
# The exact string we get back is dependent on your current TZ
# ... we'll just "roughly" test it instead of mocking.
assert(tasks['pending'][0]['entry'].startswith("20110101T"))
def test_add_with_uda_string(self):
self.tw.task_add(
"foobar",
somestring="this is a uda",
)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
task = tasks['pending'][0]
assert task['somestring'] == "this is a uda"
def test_add_with_uda_date(self):
self.tw.task_add(
"foobar",
somedate=datetime.datetime(2011, 1, 1, tzinfo=dateutil.tz.tzutc()),
)
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
task = tasks['pending'][0]
assert(task['somedate'].startswith("20110101T"))
def test_remove_uda_string(self):
# Check that a string UDA is removed from a task when its
# value is set to None
task = self.tw.task_add(
"foobar",
somestring='this is a uda',
)
task['somestring'] = None
id, task = self.tw.task_update(task)
with pytest.raises(KeyError):
task['somestring']
def test_remove_uda_date(self):
# Check that a date UDA is removed from a task when its
# value is set to None
task = self.tw.task_add(
"foobar",
somedate=datetime.datetime(2011, 1, 1),
)
task['somedate'] = None
id, task = self.tw.task_update(task)
with pytest.raises(KeyError):
task['somedate']
def test_remove_uda_numeric(self):
# Check that a numeric UDA is removed from a task when its
# value is set to None
task = self.tw.task_add(
"foobar",
somenumber=15,
)
task['somenumber'] = None
id, task = self.tw.task_update(task)
with pytest.raises(KeyError):
task['somenumber']
def test_completing_completed_task(self):
task = self.tw.task_add("foobar")
self.tw.task_done(uuid=task['uuid'])
with pytest.raises(ValueError):
self.tw.task_done(uuid=task['uuid'])
def test_updating_completed_task(self):
task = self.tw.task_add("foobar")
task = self.tw.task_done(uuid=task['uuid'])
task['priority'] = 'L'
id, task = self.tw.task_update(task)
assert task['priority'] == 'L'
def test_get_task_completed(self):
task = self.tw.task_add("foobar")
task = self.tw.task_done(uuid=task['uuid'])
id, _task = self.tw.get_task(uuid=task['uuid'])
assert id is None
assert _task['uuid'] == task['uuid']
def test_load_task_pending_command(self):
tasks = self.tw.load_tasks(command='pending')
assert len(tasks) == 1
assert 'pending' in tasks
def test_load_task_completed_command(self):
tasks = self.tw.load_tasks(command='completed')
assert len(tasks) == 1
assert 'completed' in tasks
def test_load_task_with_unknown_command(self):
with pytest.raises(ValueError):
self.tw.load_tasks(command='foobar')
def test_updating_deleted_task(self):
task = self.tw.task_add("foobar")
task = self.tw.task_delete(uuid=task['uuid'])
task['priority'] = 'L'
id, task = self.tw.task_update(task)
assert task['priority'] == 'L'
def test_delete(self):
task = self.tw.task_add("foobar")
self.tw.task_delete(uuid=task['uuid'])
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 0
def test_delete_already_deleted(self):
task = self.tw.task_add("foobar")
self.tw.task_delete(uuid=task['uuid'])
with pytest.raises(ValueError):
self.tw.task_delete(uuid=task['uuid'])
def test_load_tasks_with_one_each(self):
self.tw.task_add("foobar1")
task2 = self.tw.task_add("foobar2")
task2 = self.tw.task_done(uuid=task2['uuid'])
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 1
assert len(tasks['completed']) == 1
# For issue #26, I thought this would raise an exception...
self.tw.get_task(description='foobar1')
class TestDBDirect(_BaseTestDB):
class_to_test = TaskWarriorDirect
def test_delete_completed(self):
task = self.tw.task_add("foobar")
task = self.tw.task_done(uuid=task['uuid'])
self.tw.task_delete(uuid=task['uuid'])
tasks = self.tw.load_tasks()
assert len(tasks['pending']) == 0
assert len(tasks['completed']) == 1
def should_skip(self):
return False
class TestDBShellout(_BaseTestDB):
class_to_test = TaskWarriorShellout
def should_skip(self):
""" If 'task' is not installed, we can't run these tests. """
return not TaskWarriorShellout.can_use()
def test_filtering_simple(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
tasks = self.tw.filter_tasks({
'description.contains': 'foobar2',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 2
def test_filtering_brace(self):
self.tw.task_add("[foobar1]")
self.tw.task_add("[foobar2]")
tasks = self.tw.filter_tasks({
'description.contains': '[foobar2]',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 2
def test_filtering_quote(self):
self.tw.task_add("[foobar1]")
self.tw.task_add("\"foobar2\"")
tasks = self.tw.filter_tasks({
'description.contains': '"foobar2"',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 2
def test_filtering_plus(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foobar+")
tasks = self.tw.filter_tasks({
'description.contains': '"foobar+"',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 3
def test_filtering_minus(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foobar-")
tasks = self.tw.filter_tasks({
'description.contains': '"foobar-"',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 3
def test_filtering_colon(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foobar:")
tasks = self.tw.filter_tasks({
'description.contains': 'foobar:',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 3
def test_filtering_qmark(self):
self.tw.task_add("foobar1")
self.tw.task_add("foo?bar")
tasks = self.tw.filter_tasks({
'description.contains': 'oo?ba',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 2
def test_filtering_qmark_not_contains(self):
self.tw.task_add("foobar1")
self.tw.task_add("foo?bar")
tasks = self.tw.filter_tasks({
'description': 'foo?bar',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 2
def test_filtering_semicolon(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foo;bar")
tasks = self.tw.filter_tasks({
'description.contains': 'foo;bar',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 3
def test_filtering_question_mark(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foo?bar")
tasks = self.tw.filter_tasks({
'description.contains': 'foo?bar',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 3
def test_filtering_slash(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foo/bar")
tasks = self.tw.filter_tasks({
'description.contains': '"foo/bar"',
})
assert len(tasks) == 1
assert tasks[0]['id'] == 3
def test_filtering_logic_disjunction(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foobar3")
tasks = self.tw.filter_tasks({
'or': [
('description.has', 'foobar1'),
('description.has', 'foobar3'),
]
})
assert len(tasks) == 2
assert tasks[0]['id'] == 1
assert tasks[1]['id'] == 3
def test_filtering_logic_conjunction(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foobar3")
tasks = self.tw.filter_tasks({
'and': [
('description.has', 'foobar1'),
('description.has', 'foobar3'),
]
})
assert len(tasks) == 0
def test_filtering_logic_conjunction_junction_whats_your_function(self):
self.tw.task_add("foobar1")
self.tw.task_add("foobar2")
self.tw.task_add("foobar3")
tasks = self.tw.filter_tasks({
'and': [
('description', 'foobar1'),
],
'or': [
('status', 'pending'),
('status', 'waiting'),
]
})
assert len(tasks) == 1
def test_annotation_escaping(self):
original = {'description': 're-opening the issue'}
self.tw.task_add('foobar')
task = self.tw.load_tasks()['pending'][0]
task['annotations'] = [original]
self.tw.task_update(task)
task = self.tw.load_tasks()['pending'][0]
self.tw.task_update(task)
assert len(task['annotations']) == 1
assert task['annotations'][0]['description'] == original['description']
def test_remove_uda_string_marshal(self):
# Check that a string UDA is removed from a task when its
# value is set to None
task = self.tw_marshal.task_add(
"foobar",
somestring='this is a uda',
)
task['somestring'] = None
id, task = self.tw_marshal.task_update(task)
with pytest.raises(KeyError):
task['somestring']
def test_remove_uda_date_marshal(self):
# Check that a date UDA is removed from a task when its
# value is set to None
task = self.tw_marshal.task_add(
"foobar",
somedate=datetime.datetime(2011, 1, 1),
)
task['somedate'] = None
id, task = self.tw_marshal.task_update(task)
with pytest.raises(KeyError):
task['somedate']
def test_remove_uda_numeric_marshal(self):
# Check that a numeric UDA is removed from a task when its
# value is set to None
task = self.tw_marshal.task_add(
"foobar",
somenumber=15,
)
task['somenumber'] = None
id, task = self.tw_marshal.task_update(task)
with pytest.raises(KeyError):
task['somenumber']
def test_add_and_retrieve_uda_string_url(self):
arbitrary_url = "http://www.someurl.com/1084/"
self.tw.config_overrides['uda'] = {
'someurl': {
'label': 'Some URL',
'type': 'string'
}
}
self.tw.task_add(
"foobar",
someurl=arbitrary_url,
)
results = self.tw.filter_tasks({
'someurl.is': arbitrary_url
})
assert len(results) == 1
task = results[0]
assert task['someurl'] == arbitrary_url
def test_add_and_retrieve_uda_string_url_in_parens(self):
arbitrary_url = "http://www.someurl.com/1084/"
self.tw.config_overrides['uda'] = {
'someurl': {
'label': 'Some URL',
'type': 'string'
}
}
self.tw.task_add(
"foobar",
someurl=arbitrary_url,
)
results = self.tw.filter_tasks({
'and': [
('someurl.is', arbitrary_url),
],
})
assert len(results) == 1
task = results[0]
assert task['someurl'] == arbitrary_url
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/test/test_fields.py 0000664 0001750 0001750 00000031605 00000000000 021210 0 ustar 00acoddington acoddington import datetime
import uuid
import sys
from dateutil.tz import tzlocal
from pytz import UTC, timezone
import six
from taskw import fields
from taskw.fields.annotationarray import Annotation
if sys.version_info >= (2, 7):
from unittest import TestCase
else:
from unittest2 import TestCase
class TestAnnotationArrayField(TestCase):
def setUp(self):
self.field = fields.AnnotationArrayField()
def test_serialize_none(self):
actual_result = self.field.serialize(None)
expected_result = []
self.assertEqual(actual_result, expected_result)
def test_serialize_annotations_into_strings(self):
value = [
Annotation("something", "20240101T010101Z"),
Annotation("something else")
]
expected_serialized = ["something", "something else"]
actual_serialized = self.field.serialize(value)
self.assertEqual(actual_serialized, expected_serialized)
for entry in actual_serialized:
self.assertTrue(
isinstance(entry, six.text_type)
)
def test_deserialize_fully_formed_entries_to_stringey_things(self):
# Note that this test is *identical* in conditions and actions
# to the below, but we are asserting that we can extract treat
# the returned entries just as if they were strings.
value = [
{
'description': 'Coddingtonbear\'s birthday',
'entry': '19840302T000000Z'
},
{
'description': 'Coddingtonbear\'s partner\'s birthday',
'entry': '19850711T000000Z',
}
]
expected_results = [
value[0]['description'],
value[1]['description'],
]
actual_results = self.field.deserialize(value)
self.assertEqual(expected_results, actual_results)
def test_deserialize_fully_formed_entries_to_annotation_objects(self):
# Note that this test is *identical* in conditions and actions
# to the above, but we are asserting that we can extract a little
# bit more information from the returned objects.
value = [
{
'description': 'Coddingtonbear\'s birthday',
'entry': '19840302T000000Z'
},
{
'description': 'Coddingtonbear\'s partner\'s birthday',
'entry': '19850711T000000Z',
}
]
expected_results = [
Annotation(value[0]['description'], value[0]['entry']),
Annotation(value[1]['description'], value[1]['entry']),
]
actual_results = self.field.deserialize(value)
self.assertEqual(expected_results, actual_results)
self.assertEqual(expected_results[0].entry.year, 1984)
self.assertEqual(expected_results[1].entry.year, 1985)
class TestArrayField(TestCase):
def setUp(self):
self.field = fields.ArrayField()
def test_serialize_none(self):
actual_result = self.field.serialize(None)
expected_result = []
self.assertEqual(actual_result, expected_result)
def test_serialize_not_ok(self):
arbitrary_inappropriate_value = 1
with self.assertRaises(ValueError):
self.field.serialize(arbitrary_inappropriate_value)
def test_serialize_ok(self):
arbitrary_list = [1, 2, 3]
actual_result = self.field.serialize(arbitrary_list)
expected_result = arbitrary_list
self.assertEqual(actual_result, expected_result)
class TestChoiceField(TestCase):
def test_serialize_ok(self):
field = fields.ChoiceField(
choices=['A', 'B', 'C'],
nullable=False,
case_sensitive=True,
)
acceptable_value = 'A'
actual_value = field.serialize(acceptable_value)
expected_value = acceptable_value
self.assertEqual(actual_value, expected_value)
def test_serialize_wrong_case(self):
field = fields.ChoiceField(
choices=['A', 'B', 'C'],
nullable=False,
case_sensitive=True,
)
unacceptable_wrong_case = 'a'
with self.assertRaises(ValueError):
field.serialize(unacceptable_wrong_case)
def test_serialize_none_unacceptable(self):
field = fields.ChoiceField(
choices=['A', 'B', 'C'],
nullable=False,
case_sensitive=True,
)
unacceptable_none_value = None
with self.assertRaises(ValueError):
field.serialize(unacceptable_none_value)
def test_serialize_none_acceptable(self):
field = fields.ChoiceField(
choices=[None, 'A', 'B', 'C'],
case_sensitive=True,
)
acceptable_none_value = None
actual_value = field.serialize(acceptable_none_value)
expected_value = acceptable_none_value
self.assertEqual(actual_value, expected_value)
def test_serialize_case_insensitive(self):
field = fields.ChoiceField(
choices=['A', 'B', 'C'],
nullable=False,
case_sensitive=False,
)
value_wrong_case = 'a'
actual_value = field.serialize(value_wrong_case)
expected_value = value_wrong_case
self.assertEqual(actual_value, expected_value)
class TestCommaSeparatedUUIDField(TestCase):
def setUp(self):
self.field = fields.CommaSeparatedUUIDField()
def test_serialize_single_uuid(self):
single_uuid = [uuid.uuid4()]
actual_value = self.field.serialize(single_uuid)
expected_value = str(single_uuid[0])
self.assertEqual(actual_value, expected_value)
def test_serialize_mulitple_values(self):
many_uuids = [
uuid.uuid4(),
uuid.uuid4(),
uuid.uuid4(),
]
actual_value = self.field.serialize(many_uuids)
expected_value = ','.join([str(u) for u in many_uuids])
self.assertEqual(actual_value, expected_value)
def test_deserialize_uuid_string(self):
arbitrary_uuids = [uuid.uuid4(), uuid.uuid4()]
uuid_strings = ','.join([str(u) for u in arbitrary_uuids])
actual_value = self.field.deserialize(uuid_strings)
expected_value = arbitrary_uuids
self.assertEqual(actual_value, expected_value)
def test_deserialize_uuid_string_undashed(self):
arbitrary_uuids = [uuid.uuid4(), uuid.uuid4()]
uuid_strings = ','.join([u.hex for u in arbitrary_uuids])
actual_value = self.field.deserialize(uuid_strings)
expected_value = arbitrary_uuids
self.assertEqual(actual_value, expected_value)
class TestDateField(TestCase):
def setUp(self):
self.field = fields.DateField()
def test_deserialize_none(self):
actual_value = self.field.deserialize(None)
expected_value = None
self.assertEqual(actual_value, expected_value)
def test_deserialize_naive(self):
arbitrary_year = 2014
arbitrary_month = 3
arbitrary_day = 2
arbitrary_hour = 9
arbitrary_minute = 10
arbitrary_second = 3
naive_date_string = (
'{year}-{month}-{day}T{hour}:{minute}:{second}'.format(
year=arbitrary_year,
month=arbitrary_month,
day=arbitrary_day,
hour=arbitrary_hour,
minute=arbitrary_minute,
second=arbitrary_second,
)
)
actual_value = self.field.deserialize(naive_date_string)
expected_value = datetime.datetime(
arbitrary_year,
arbitrary_month,
arbitrary_day,
arbitrary_hour,
arbitrary_minute,
arbitrary_second,
tzinfo=UTC
)
self.assertEqual(actual_value, expected_value)
def test_deserialize_nonnaive(self):
arbitrary_year = 2014
arbitrary_month = 3
arbitrary_day = 2
arbitrary_hour = 9
arbitrary_minute = 10
arbitrary_second = 3
nonnaive_date_string = (
'{year}-{month}-{day}T{hour}:{minute}:{second}Z'.format(
year=arbitrary_year,
month=arbitrary_month,
day=arbitrary_day,
hour=arbitrary_hour,
minute=arbitrary_minute,
second=arbitrary_second,
)
)
actual_value = self.field.deserialize(nonnaive_date_string)
expected_value = datetime.datetime(
arbitrary_year,
arbitrary_month,
arbitrary_day,
arbitrary_hour,
arbitrary_minute,
arbitrary_second,
tzinfo=UTC
)
self.assertEqual(actual_value, expected_value)
def test_serialize_none(self):
actual_value = self.field.serialize(None)
expected_value = None
self.assertEqual(actual_value, expected_value)
def test_serialize_naive(self):
arbitrary_year = 2014
arbitrary_month = 3
arbitrary_day = 2
arbitrary_hour = 9
arbitrary_minute = 10
arbitrary_second = 3
arbitrary_date = datetime.datetime(
arbitrary_year,
arbitrary_month,
arbitrary_day,
arbitrary_hour,
arbitrary_minute,
arbitrary_second,
)
actual_value = self.field.serialize(arbitrary_date)
expected_value = UTC.normalize(
arbitrary_date.replace(tzinfo=tzlocal())
).strftime('%Y%m%dT%H%M%SZ')
self.assertEqual(actual_value, expected_value)
def test_serialize_nonnaive(self):
arbitrary_year = 2014
arbitrary_month = 3
arbitrary_day = 2
arbitrary_hour = 9
arbitrary_minute = 10
arbitrary_second = 3
arbitrary_date = datetime.datetime(
arbitrary_year,
arbitrary_month,
arbitrary_day,
arbitrary_hour,
arbitrary_minute,
arbitrary_second,
tzinfo=timezone('America/Los_Angeles')
)
actual_value = self.field.serialize(arbitrary_date)
expected_value = UTC.normalize(
arbitrary_date
).strftime('%Y%m%dT%H%M%SZ')
self.assertEqual(actual_value, expected_value)
class TestNumericField(TestCase):
def setUp(self):
self.field = fields.NumericField()
def test_deserialize_float(self):
arbitrary_float = '214.8'
actual_value = self.field.deserialize(arbitrary_float)
expected_value = 214.8
self.assertEqual(actual_value, expected_value)
def test_deserialize_integer(self):
arbitrary_integer = '214'
actual_value = self.field.deserialize(arbitrary_integer)
expected_value = 214
self.assertEqual(actual_value, expected_value)
def test_deserialize_and_lo_and_behold_it_wasnt_numeric(self):
arbitrary_string = 'alpha'
actual_value = self.field.deserialize(arbitrary_string)
expected_value = arbitrary_string
self.assertEqual(actual_value, expected_value)
def test_numeric_value(self):
arbitrary_numeric_value = 10
actual_value = self.field.serialize(arbitrary_numeric_value)
expected_value = arbitrary_numeric_value
self.assertEqual(actual_value, expected_value)
def test_nonnumeric_value(self):
arbitrary_nonnumeric_value = 'alpha'
with self.assertRaises(ValueError):
self.field.serialize(arbitrary_nonnumeric_value)
class TestStringField(TestCase):
def setUp(self):
self.field = fields.StringField()
def test_deserialize_string(self):
serialized_string = '&open;hello&close;'
actual_value = self.field.deserialize(serialized_string)
expected_value = '[hello]'
self.assertEqual(actual_value, expected_value)
def test_serialize_string(self):
unserialized_string = '[hello]'
actual_value = self.field.serialize(unserialized_string)
expected_value = '&open;hello&close;'
self.assertEqual(actual_value, expected_value)
class TestUUIDField(TestCase):
def setUp(self):
self.field = fields.UUIDField()
def test_serialize(self):
arbitrary_uuid = uuid.uuid4()
actual_result = self.field.serialize(arbitrary_uuid)
expected_result = str(arbitrary_uuid)
self.assertEqual(actual_result, expected_result)
def test_deserialize_dashed(self):
arbitrary_uuid = uuid.uuid4()
dashed_uuid = str(arbitrary_uuid)
actual_result = self.field.deserialize(dashed_uuid)
expected_result = arbitrary_uuid
self.assertEqual(actual_result, expected_result)
def test_deserialize_undashed(self):
arbitrary_uuid = uuid.uuid4()
dashed_uuid = arbitrary_uuid.hex
actual_result = self.field.deserialize(dashed_uuid)
expected_result = arbitrary_uuid
self.assertEqual(actual_result, expected_result)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1637806905.0
taskw-1.3.1/taskw/test/test_recursive.py 0000664 0001750 0001750 00000004150 00000000000 021744 0 ustar 00acoddington acoddington import os
import shutil
import tempfile
import pytest
from taskw import TaskWarriorShellout
TASK = {'description': "task 2 http://www.google.com/",
'entry': "1325011643",
'project': "work",
'start': "1326079920", 'status': "pending",
'uuid': "c1c431ea-f0dc-4683-9a20-e64fcfa65fd1"}
class TestRecursibe(object):
def setup(self):
if not TaskWarriorShellout.can_use():
# Sometimes the 'task' command line tool is not installed.
pytest.skip("taskwarrior not installed")
# Create some temporary config stuff
fd, fname = tempfile.mkstemp(prefix='taskw-testsrc')
dname = tempfile.mkdtemp(prefix='taskw-tests-data')
with open(fname, 'w') as f:
f.writelines([
'data.location=%s\n' % dname,
'uda.somestring.label=Testing String\n',
'uda.somestring.type=string\n',
'uda.somedate.label=Testing Date\n',
'uda.somedate.type=date\n',
'uda.somenumber.label=Testing Number\n',
'uda.somenumber.type=numeric\n',
])
# Create empty .data files
for piece in ['completed', 'pending', 'undo']:
with open(os.path.sep.join([dname, piece + '.data']), 'w'):
pass
# Save names for .tearDown()
self.fname, self.dname = fname, dname
# Create the taskwarrior db object that each test will use.
self.tw = TaskWarriorShellout(config_filename=fname, marshal=True)
def tearDown(self):
os.remove(self.fname)
shutil.rmtree(self.dname)
def test_set_dep_on_one_uuid(self):
task1 = self.tw.task_add('task1')
task2 = self.tw.task_add('task2', depends=[task1['uuid']])
assert task2['depends'][0] == task1['uuid']
def test_set_dep_on_two_uuid(self):
task1 = self.tw.task_add('task1')
task2 = self.tw.task_add('task2')
depends = [task1['uuid'], task2['uuid']]
task3 = self.tw.task_add('task3', depends=depends)
assert set(task3['depends']) == set([task1['uuid'], task2['uuid']])
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295332.0
taskw-1.3.1/taskw/test/test_task.py 0000664 0001750 0001750 00000016352 00000000000 020706 0 ustar 00acoddington acoddington import copy
import datetime
import uuid
from unittest import TestCase
import pytz
import six
from dateutil.tz import tzutc
from taskw.task import Task
class TestTaskDirtyability(TestCase):
def setUp(self):
self.task = Task({
'uuid': str(uuid.uuid4()),
'description': 'Something important',
'due': (
datetime.datetime.now().replace(tzinfo=pytz.UTC)
+ datetime.timedelta(hours=1)
).strftime('%Y%m%dT%H%M%SZ'),
'tags': ['one', 'two', 'three'],
})
def test_append_when_absent(self):
self.task['annotations'] = []
self.task['annotations'].append('awesome')
self.assertEqual(self.task['annotations'], ['awesome'])
def test_append_when_absent_but_with_tags(self):
self.task = Task({'uuid': str(uuid.uuid4()), 'description': 'Test'})
self.task['tags'] = []
self.task['tags'].append('awesome')
self.assertEqual(self.task['tags'], ['awesome'])
def test_marks_date_changed(self):
original_due_date = self.task['due']
new_due_date = datetime.datetime.now().replace(tzinfo=pytz.UTC)
self.task['due'] = new_due_date
expected_changes = {'due': (original_due_date, new_due_date)}
actual_changes = self.task.get_changes()
self.assertEqual(list(six.iterkeys(actual_changes)), ['due'])
# Use assertAlmostEqual to allow for millisecond loss when
# converting to string in setUp
self.assertAlmostEqual(
expected_changes['due'][0],
actual_changes['due'][0],
delta=datetime.timedelta(seconds=1)
)
self.assertAlmostEqual(
expected_changes['due'][1],
actual_changes['due'][1],
delta=datetime.timedelta(seconds=1)
)
def test_marks_tags_changed(self):
original_tags = copy.deepcopy(self.task['tags'])
new_tag = 'alpha'
self.task['tags'].append(new_tag)
expected_tags = copy.deepcopy(original_tags)
expected_tags.append(new_tag)
expected_changes = {'tags': [original_tags, expected_tags]}
actual_changes = self.task.get_changes()
self.assertEqual(actual_changes, expected_changes)
def test_does_not_mark_unchanged(self):
self.task['description'] = self.task['description']
expected_changes = {}
actual_changes = self.task.get_changes()
self.assertEqual(actual_changes, expected_changes)
def test_does_not_allow_changing_id(self):
with self.assertRaises(ValueError):
self.task['id'] = 10
class TestTaskMarshalling(TestCase):
def test_serialize(self):
arbitrary_serialized_data = {
'depends': ','.join([
str(uuid.uuid4()),
str(uuid.uuid4()),
]),
'description': '&open;Something important',
'due': (
datetime.datetime.now().replace(tzinfo=pytz.UTC)
+ datetime.timedelta(hours=1)
).strftime('%Y%m%dT%H%M%SZ'),
'tags': ['one', 'two', 'three'],
'urgency': 10,
'uuid': str(uuid.uuid4()),
}
task = Task(arbitrary_serialized_data)
expected_result = arbitrary_serialized_data
actual_result = task.serialized()
self.assertEqual(actual_result, expected_result)
def test_deserialize(self):
arbitrary_depends_uuids = [uuid.uuid4(), uuid.uuid4()]
arbitrary_description = '[one'
arbitrary_due_date = (
datetime.datetime.now().replace(tzinfo=pytz.UTC)
+ datetime.timedelta(hours=1)
)
arbitrary_tags = ['one', 'two', ]
arbitrary_urgency = 10
arbitrary_uuid = uuid.uuid4()
serialized = {
'depends': ','.join([str(u) for u in arbitrary_depends_uuids]),
'description': arbitrary_description.replace('[', '&open;'),
'due': arbitrary_due_date.strftime('%Y%m%dT%H%M%SZ'),
'tags': arbitrary_tags,
'urgency': arbitrary_urgency,
'uuid': str(arbitrary_uuid)
}
task = Task(serialized)
self.assertEqual(task['depends'], arbitrary_depends_uuids)
self.assertEqual(task['description'], arbitrary_description)
# Loss of milliseconds when converting to string
self.assertAlmostEqual(
task['due'],
arbitrary_due_date,
delta=datetime.timedelta(seconds=1)
)
self.assertEqual(task['tags'], arbitrary_tags)
self.assertEqual(task['urgency'], arbitrary_urgency)
self.assertEqual(task['uuid'], arbitrary_uuid)
def test_composition(self):
arbitrary_serialized_data = {
'depends': ','.join([
str(uuid.uuid4()),
str(uuid.uuid4()),
]),
'description': '&open;Something important',
'due': (
datetime.datetime.now().replace(tzinfo=pytz.UTC)
+ datetime.timedelta(hours=1)
).strftime('%Y%m%dT%H%M%SZ'),
'tags': ['one', 'two', 'three'],
'urgency': 10,
'uuid': str(uuid.uuid4()),
}
expected_result = arbitrary_serialized_data
after_composition = Task(
Task(
Task(
arbitrary_serialized_data
).serialized()
).serialized()
).serialized()
self.assertEqual(after_composition, expected_result)
def test_from_input(self):
input_add_data = six.StringIO(
'{'
'"description":"Go to Camelot",'
'"entry":"20180618T030242Z",'
'"status":"pending",'
'"start":"20181012T110605Z",'
'"uuid":"daa3ff05-f716-482e-bc35-3e1601e50778"'
'}')
input_modify_data = six.StringIO(
'\n'.join([
input_add_data.getvalue(),
(
'{'
'"description":"Go to Camelot again",'
'"entry":"20180618T030242Z",'
'"status":"pending",'
'"start":"20181012T110605Z",'
'"uuid":"daa3ff05-f716-482e-bc35-3e1601e50778"'
'}'
),
]),
)
on_add_task = Task.from_input(input_file=input_add_data)
assert on_add_task.get('description') == "Go to Camelot"
assert on_add_task.get('entry') == datetime.datetime(2018, 6, 18, 3, 2, 42, tzinfo=tzutc())
assert on_add_task.get('status') == "pending"
assert on_add_task.get('start') == datetime.datetime(2018, 10, 12, 11, 6, 5, tzinfo=tzutc())
assert on_add_task.get('uuid') == uuid.UUID("daa3ff05-f716-482e-bc35-3e1601e50778")
on_modify_task = Task.from_input(input_file=input_modify_data, modify=True)
assert on_modify_task.get('description') == "Go to Camelot again"
assert on_modify_task.get('entry') == datetime.datetime(2018, 6, 18, 3, 2, 42, tzinfo=tzutc())
assert on_modify_task.get('status') == "pending"
assert on_modify_task.get('start') == datetime.datetime(2018, 10, 12, 11, 6, 5, tzinfo=tzutc())
assert on_modify_task.get('uuid') == uuid.UUID("daa3ff05-f716-482e-bc35-3e1601e50778")
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1568597346.0
taskw-1.3.1/taskw/test/test_taskrc.py 0000664 0001750 0001750 00000007301 00000000000 021225 0 ustar 00acoddington acoddington import os
import sys
from taskw.warrior import TaskWarrior
from taskw.taskrc import TaskRc
from taskw.fields import NumericField, ChoiceField
if sys.version_info >= (2, 7):
from unittest import TestCase
else:
from unittest2 import TestCase
class TestBasicLoading(TestCase):
def setUp(self):
self.path_to_taskrc = os.path.join(
os.path.dirname(__file__),
'data/default.taskrc',
)
def test_load_config(self):
expected = {
'data': {
'location': '~/.task'
},
'alpha': {
'one': 'yes',
'two': '2',
},
'beta': {
'one': 'FALSE',
},
'gamma': {
'one': 'TRUE',
},
'uda': {
'a': {
'type': 'numeric',
'label': 'Alpha',
},
'b': {
'type': 'string',
'label': 'Beta',
'values': 'Strontium-90,Hydrogen-3',
}
}
}
config = TaskWarrior.load_config(self.path_to_taskrc)
self.assertEqual(config, expected)
class TestTaskRc(TestCase):
def setUp(self):
self.path_to_taskrc = os.path.join(
os.path.dirname(__file__),
'data/default.taskrc',
)
self.taskrc = TaskRc(self.path_to_taskrc)
def test_taskrc_parsing(self):
expected_config = {
'data': {
'location': '~/.task'
},
'alpha': {
'one': 'yes',
'two': '2',
},
'beta': {
'one': 'FALSE',
},
'gamma': {
'one': 'TRUE',
},
'uda': {
'a': {
'type': 'numeric',
'label': 'Alpha',
},
'b': {
'type': 'string',
'label': 'Beta',
'values': 'Strontium-90,Hydrogen-3',
}
}
}
self.assertEqual(self.taskrc, expected_config)
def test_get_udas(self):
expected_udas = {
'a': NumericField(label='Alpha'),
'b': ChoiceField(
label='Beta',
choices=['Strontium-90', 'Hydrogen-3'],
),
}
actual_udas = self.taskrc.get_udas()
self.assertEqual(actual_udas, expected_udas)
def test_config_overrides(self):
overrides = {
'uda': {
'd': {
'type': 'string',
'label': 'Delta',
}
},
'alpha': {
'two': '3',
}
}
taskrc = TaskRc(self.path_to_taskrc, overrides=overrides)
expected_config = {
'data': {
'location': '~/.task'
},
'alpha': {
'one': 'yes',
'two': '3',
},
'beta': {
'one': 'FALSE',
},
'gamma': {
'one': 'TRUE',
},
'uda': {
'a': {
'type': 'numeric',
'label': 'Alpha',
},
'b': {
'type': 'string',
'label': 'Beta',
'values': 'Strontium-90,Hydrogen-3',
},
'd': {
'type': 'string',
'label': 'Delta',
}
}
}
self.assertEqual(taskrc, expected_config)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607300452.0
taskw-1.3.1/taskw/test/test_utils.py 0000664 0001750 0001750 00000014004 00000000000 021074 0 ustar 00acoddington acoddington import datetime
import random
import dateutil.tz
import pytz
import six
from taskw.utils import (
convert_dict_to_override_args,
decode_task,
encode_task,
encode_task_experimental,
DATE_FORMAT,
clean_ctrl_chars,
)
TASK = {'description': "task 2 http://www.google.com/",
'entry': "1325011643",
'project': "work",
'due': "1359090000",
'start': "1326079920", 'status': "pending",
'uuid': "c1c431ea-f0dc-4683-9a20-e64fcfa65fd1"}
TASK_LEADING_WS = TASK.copy()
TASK_LEADING_WS.update({'description': " task 3"})
def shuffled(l):
new = list(l)
random.shuffle(new)
return new
class TestUtils(object):
def test_no_side_effects(self):
orig = TASK.copy()
decode_task(encode_task(TASK))
assert orig == TASK
def test_with_escaped_quotes(self):
expected = {'this': r'has a "quote" in it.'}
line = r'[this:"has a \"quote\" in it."]'
r = decode_task(line)
assert r == expected
def test_with_escaped_quotes_roundtrip(self):
expected = {'this': r'has a "quote" in it.'}
line = r'[this:"has a \"quote\" in it."]'
r = decode_task(encode_task(decode_task(line)))
assert r == expected
def test_with_escaped_quotes_full(self):
line = r'[this:"has a \"quote\" in it."]'
r = encode_task(decode_task(line))
assert r == r
def test_with_backticks(self):
expected = {'this': r'has a fucking `backtick` in it'}
line = r'[this:"has a fucking `backtick` in it"]'
r = decode_task(line)
assert r == expected
r = decode_task(encode_task(decode_task(line)))
assert r == expected
def test_with_backslashes(self):
expected = {'andthis': r'has a fucking \backslash in it'}
line = r'[andthis:"has a fucking \\backslash in it"]'
r = decode_task(line)
assert r == expected
r = decode_task(encode_task(decode_task(line)))
assert r == expected
def test_with_unicode(self):
expected = {
six.text_type('andthis'): (
six.text_type('has a fucking \\backslash in it')
)
}
line = r'[andthis:"has a fucking \\backslash in it"]'
r = decode_task(line)
assert r == expected
r = decode_task(encode_task(decode_task(line)))
assert r == expected
def test_decode(self):
r = decode_task(encode_task(TASK))
assert r == TASK
def test_decode_leading_whitespace_in_value(self):
r = decode_task(encode_task(TASK_LEADING_WS))
assert r == TASK_LEADING_WS
def test_composition(self):
assert TASK == decode_task(encode_task(TASK))
def test_double_composition(self):
assert TASK == decode_task(encode_task(decode_task(encode_task(TASK))))
def test_ordering(self):
task1 = dict(shuffled(TASK.items()))
task2 = dict(shuffled(TASK.items()))
assert encode_task(task1) == encode_task(task2)
def test_taskwarrior_null_encoding_bug_workaround(self):
task = {
'priority': ''
}
actual_encoded = encode_task_experimental(task)[0]
expected_encoded = "priority:"
assert actual_encoded == expected_encoded
def test_encodes_dates(self):
arbitrary_date = datetime.date(2014, 3, 2)
task = {
'arbitrary_field': arbitrary_date
}
actual_encoded_task = encode_task_experimental(task)
expected_encoded_task = encode_task_experimental(
{
'arbitrary_field': arbitrary_date.strftime(DATE_FORMAT)
}
)
assert actual_encoded_task == expected_encoded_task
def test_encodes_naive_datetimes(self):
arbitrary_naive_datetime = datetime.datetime.now()
task = {
'arbitrary_field': arbitrary_naive_datetime
}
actual_encoded_task = encode_task_experimental(task)
expected_encoded_task = encode_task_experimental(
{
'arbitrary_field': (
arbitrary_naive_datetime
.replace(tzinfo=dateutil.tz.tzlocal())
.astimezone(pytz.utc).strftime(DATE_FORMAT)
)
}
)
assert actual_encoded_task == expected_encoded_task
def test_encodes_zoned_datetimes(self):
arbitrary_timezone = pytz.timezone('America/Los_Angeles')
arbitrary_zoned_datetime = datetime.datetime.now().replace(
tzinfo=arbitrary_timezone
)
task = {
'arbitrary_field': arbitrary_zoned_datetime
}
actual_encoded_task = encode_task_experimental(task)
expected_encoded_task = encode_task_experimental(
{
'arbitrary_field': (
arbitrary_zoned_datetime
.astimezone(pytz.utc).strftime(DATE_FORMAT)
)
}
)
assert actual_encoded_task == expected_encoded_task
def test_convert_dict_to_override_args(self):
overrides = {
'one': {
'two': 1,
'three': {
'alpha': 'a'
},
'four': 'lorem ipsum',
},
'two': {
}
}
expected_overrides = [
'rc.one.two=1',
'rc.one.three.alpha=a',
'rc.one.four="lorem ipsum"',
]
actual_overrides = convert_dict_to_override_args(overrides)
assert set(actual_overrides) == set(expected_overrides)
class TestCleanExecArg(object):
def test_clean_null(self):
assert b"" == clean_ctrl_chars(b"\x00")
def test_all_ctrl_chars(self):
""" Test that most (but not all) control characters are removed """
# input = bytes(range(0x20))
input = b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' # For python 2 compatibility
assert b"\t\n\v\f\r" == clean_ctrl_chars(input)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607300452.0
taskw-1.3.1/taskw/test/test_warrior.py 0000664 0001750 0001750 00000004024 00000000000 021422 0 ustar 00acoddington acoddington import tempfile
import os
import shutil
from unittest import TestCase
from taskw.warrior import TaskWarrior
class TestTaskWarrior(TestCase):
def setUp(self):
self.taskdata = tempfile.mkdtemp()
taskrc = os.path.join(os.path.dirname(__file__), 'data/empty.taskrc')
self.taskwarrior = TaskWarrior(
config_filename=taskrc,
config_overrides={'data.location': self.taskdata})
# Just a sanity check to make sure that after the setup, the list of
# tasks is empty, otherwise we are probably using the current user's
# TASKDATA and we should not continue.
assert self.taskwarrior.load_tasks() == {'completed': [], 'pending': []}
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.taskdata)
def test_add_task_foobar(self):
""" Add a task with description 'foobar' and checks that the task is
indeed created """
self.taskwarrior.task_add("foobar")
tasks = self.taskwarrior.load_tasks()
assert len(tasks['pending']) == 1
assert tasks['pending'][0]['description'] == 'foobar'
def test_add_task_null_char(self):
""" Try adding a task where the description contains a NULL character
(0x00). This should not fail but instead simply add a task with the
same description minus the NULL character """
self.taskwarrior.task_add("foo\x00bar")
tasks = self.taskwarrior.load_tasks()
assert len(tasks['pending']) == 1
assert tasks['pending'][0]['description'] == 'foobar'
def test_add_task_recurs(self):
""" Try adding a task with `recur` to ensure the uuid can be parsed """
self.taskwarrior.task_add("foobar weekly", due="tomorrow", recur="weekly")
tasks = self.taskwarrior.load_tasks()
assert len(tasks['pending']) == 1
assert tasks['pending'][0]['description'] == 'foobar weekly'
assert tasks['pending'][0]['recur'] == 'weekly'
assert tasks['pending'][0]['parent'] is not None
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1607295332.0
taskw-1.3.1/taskw/utils.py 0000664 0001750 0001750 00000016521 00000000000 017064 0 ustar 00acoddington acoddington """ Various utilties """
from __future__ import print_function
import datetime
import re
from operator import itemgetter
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import dateutil.tz
import pytz
import six
from distutils.version import LooseVersion
DATE_FORMAT = '%Y%m%dT%H%M%SZ'
encode_replacements = OrderedDict([
('\\', '\\\\'),
('\"', '&dquot;'),
('"', '&dquot;'),
('[', '&open;'),
(']', '&close;'),
('\n', ' '),
('/', '\\/'),
])
encode_replacements_experimental = OrderedDict([
('\"', '&dquot;'),
('"', '&dquot;'),
('[', '&open;'),
(']', '&close;'),
])
decode_replacements = OrderedDict([
[v, k] for k, v in encode_replacements.items()
if k not in ('\n') # We skip these.
])
logical_replacements = OrderedDict([
('?', '\\?'),
('+', '\\+'),
('(', '\\('),
(')', '\\)'),
('[', '\\['),
(']', '\\]'),
('{', '\\{'),
('}', '\\}'),
])
def encode_task_value(key, value, query=False):
if value is None:
value = ''
elif isinstance(value, datetime.datetime):
if not value.tzinfo:
# Dates not having timezone information should be
# assumed to be in local time
value = value.replace(tzinfo=dateutil.tz.tzlocal())
# All times should be converted to UTC before serializing
value = value.astimezone(pytz.utc).strftime(DATE_FORMAT)
elif isinstance(value, datetime.date):
value = value.strftime(DATE_FORMAT)
elif isinstance(value, six.string_types):
if query:
# In some contexts, parentheses are interpreted for use in
# logical expressions. They must *sometimes* be escaped.
for left, right in six.iteritems(logical_replacements):
# don't replace '?' if this is an exact match
if left == '?' and '.' not in key:
continue
value = value.replace(left, right)
else:
for unsafe, safe in six.iteritems(
encode_replacements_experimental
):
value = value.replace(unsafe, safe)
else:
value = str(value)
return value
def encode_query(value, version, query=True):
args = []
if isinstance(value, dict):
value = six.iteritems(value)
for k, v in value:
if isinstance(v, list):
args.append(
"( %s )" % (" %s " % k).join([
encode_query([item], version, query=False)[0] for item in v
])
)
else:
if k.endswith(".is") and version >= LooseVersion('2.4'):
args.append(
'%s == "%s"' % (
k[:-3],
encode_task_value(k, v, query=query)
)
)
else:
args.append(
'%s:%s' % (
k,
encode_task_value(k, v, query=query)
)
)
return args
def clean_task(task):
""" Clean a task by replacing any dangerous characters """
return task
def encode_task_experimental(task):
""" Convert a dict-like task to its string representation
Used for adding a task via `task add`
"""
# First, clean the task:
task = task.copy()
if 'tags' in task:
task['tags'] = ','.join(task['tags'])
for k in task:
task[k] = encode_task_value(k, task[k])
# Then, format it as a string
return [
"%s:\"%s\"" % (k, v) if v else "%s:" % (k, )
for k, v in sorted(task.items(), key=itemgetter(0))
]
def encode_task(task):
""" Convert a dict-like task to its string representation """
# First, clean the task:
task = task.copy()
if 'tags' in task:
task['tags'] = ','.join(task['tags'])
for k in task:
for unsafe, safe in six.iteritems(encode_replacements):
if isinstance(task[k], six.string_types):
task[k] = task[k].replace(unsafe, safe)
if isinstance(task[k], datetime.datetime):
task[k] = task[k].strftime("%Y%m%dT%M%H%SZ")
# Then, format it as a string
return "[%s]\n" % " ".join([
"%s:\"%s\"" % (k, v)
for k, v in sorted(task.items(), key=itemgetter(0))
])
def decode_task(line):
""" Parse a single record (task) from a task database file.
I don't understand why they don't just use JSON or YAML. But
that's okay.
>>> decode_task('[description:"Make a python API for taskwarrior"]')
{'description': 'Make a python API for taskwarrior'}
"""
task = {}
for key, value in re.findall(r'(\w+):"(.*?)(?