From 9a4ec8ba7719ad9c35a6ad8206e0b645cd3d818b Mon Sep 17 00:00:00 2001 From: StefanGreve Date: Sun, 1 Dec 2024 15:45:14 +0100 Subject: [PATCH 1/4] Refactor project and restart from scratch --- .editorconfig | 7 +- .gitattributes | 17 +- .gitignore | 2 +- CHANGELOG.md | 4 + LICENSE.md | 696 +----------------------- README.md | 14 +- examples/examples.ps1 | 24 - publish.ps1 | 61 --- src/Todo.psd1 | 68 --- src/Todo.psm1 | 30 - src/TodoTable.Format.ps1xml | 61 --- src/classes/Task.ps1 | 21 - src/classes/classes.psd1 | 5 - src/init/RegisterArgumentCompleters.ps1 | 29 - src/private/Get-SavePath.ps1 | 4 - src/public/Get-Task.ps1 | 66 --- src/public/Get-TodoList.ps1 | 125 ----- src/public/New-Task.ps1 | 97 ---- src/public/New-TodoList.ps1 | 50 -- src/public/Remove-Task.ps1 | 64 --- src/public/Remove-TodoList.ps1 | 51 -- src/public/TodoList.sql | 9 - src/public/Update-Task.ps1 | 120 ---- 23 files changed, 39 insertions(+), 1586 deletions(-) delete mode 100644 examples/examples.ps1 delete mode 100644 publish.ps1 delete mode 100644 src/Todo.psd1 delete mode 100644 src/Todo.psm1 delete mode 100644 src/TodoTable.Format.ps1xml delete mode 100644 src/classes/Task.ps1 delete mode 100644 src/classes/classes.psd1 delete mode 100644 src/init/RegisterArgumentCompleters.ps1 delete mode 100644 src/private/Get-SavePath.ps1 delete mode 100644 src/public/Get-Task.ps1 delete mode 100644 src/public/Get-TodoList.ps1 delete mode 100644 src/public/New-Task.ps1 delete mode 100644 src/public/New-TodoList.ps1 delete mode 100644 src/public/Remove-Task.ps1 delete mode 100644 src/public/Remove-TodoList.ps1 delete mode 100644 src/public/TodoList.sql delete mode 100644 src/public/Update-Task.ps1 diff --git a/.editorconfig b/.editorconfig index 5dfc4a1..a3143be 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,11 +1,12 @@ root = true [*] -end_of_line = crlf +end_of_line = lf +indent_style = space indent_size = 4 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true -[*.{ps1, psm1}] -indent_style = space +[*.yml] +indent_size = 2 diff --git a/.gitattributes b/.gitattributes index 797db8e..6313b56 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,16 +1 @@ -* text=auto - -*.md text -*.gitattributes text - -*.ps1 text eol=crlf -*.psm1 text eol=crlf -*.psd1 text eol=crlf -*.psc1 text eol=crlf -*.ps1xml text eol=crlf -*.clixml text eol=crlf -*.xml text eol=crlf -*.txt text eol=crlf - -*.dll binary -*.exe binary +* text=auto eol=lf diff --git a/.gitignore b/.gitignore index 9ae26c0..8b13789 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -modules/* + diff --git a/CHANGELOG.md b/CHANGELOG.md index b6ceee7..7d02e76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Version 2.0.0 (2024-12-01) + +TODO + ## Version 1.3.2 (2022-03-24) Declare `OutputType` as strings to fix a bug which breaks `Get-Task` and `Get-TodoList`: diff --git a/LICENSE.md b/LICENSE.md index 2fb2e74..285d156 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,675 +1,25 @@ -### 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 +The MIT License (MIT) +===================== + +Copyright © 2022-2024 Advanced Systems + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the “Software”), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following 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 . +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 179080c..f54b017 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,16 @@

- +

Advanced Systems Todo List

+![](https://img.shields.io/badge/PowerShell_Version-7.4-blue) +![GitHub License](https://img.shields.io/github/license/advanced-systems/todo) + +## About + `Todo` is an open-source PowerShell module to manage your TODO list from the terminal. All tasks are locally stored in a SQLite database located in a app data sub-directory. This module can be installed from [PowerShell Gallery](https://www.powershellgallery.com/) with @@ -18,13 +23,6 @@ Install-Module -Name Todo - [`SQList`](https://www.powershellgallery.com/packages/SQLite/2.0) -Review the module manifest: - -```powershell -Invoke-WebRequest -Uri https://raw.githubusercontent.com/Advanced-Systems/todo/master/src/Todo.psd1 -OutFile Todo.psd1 -Import-PowerShellDataFile Todo.psd1 | Write-Output -``` - ## Basic Usage ```powershell diff --git a/examples/examples.ps1 b/examples/examples.ps1 deleted file mode 100644 index a5ad0a7..0000000 --- a/examples/examples.ps1 +++ /dev/null @@ -1,24 +0,0 @@ -# -# Todo Module Examples -# - -# 1) Use the built-in filter parameter to perform simple searches -gtodo -Filter Status -eq 'InProgress' - -# 2) Review the description of the last task in list -gtodo | select -Last 1 -Property Description - -# 3) Dry-run mass removal of all discarded tasks -gtodo | where Status -eq 'Discarded' | Remove-Task -WhatIf - -# 4) Get all high-priority tasks and sort by start date -gtodo | where Priority -eq 'High' | sort StartDate | select Id, Description - -# 5) Search all overdue task records that were never completed and update their status to discarded -gtodo | where { $(Get-Date) -gt $_.DueDate -and $_.Status -ne 'Done' } | utask -Status Discarded -WhatIf - -# 6) Display the description of task #42 -gtask 42 | select Description - -# 7) Display the ID and description of all tasks -gtodo -All | select Id, Description diff --git a/publish.ps1 b/publish.ps1 deleted file mode 100644 index ade82f0..0000000 --- a/publish.ps1 +++ /dev/null @@ -1,61 +0,0 @@ -function Publish-Todo { - <# - .SYNOPSIS - Test and publish this module. - - .DESCRIPTION - Test and publish this module. Specify an API key if you intend to publish this module. It is recommended to run the Cmdlet at least once parameterless to perform some preliminary tests. - This Cmdlet requires the following modules in order to run. Release dependencies are marked with a truthy boolean value. - - Name Version Release - ---- ------- ------- - SQLite 2.0 True - PSScriptAnalyzer 1.20.0 False - #> - [Alias("publish")] - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] - param( - [Parameter()] - [string] $ApiKey - ) - begin { - $Steps = 5 - $Name = "Todo" - $ModulePath = $env:PSModulePath -Split ";" | Select-Object -First 1 - $ProjectRootDirectory = Join-Path -Path $PSScriptRoot -ChildPath "src" - $ManifestPath = Join-Path -Path $ProjectRootDirectory -ChildPath "${Name}.psd1" - $Manifest = Import-PowerShellDataFile -Path $ManifestPath - $Version = $Manifest.ModuleVersion - } - process { - Write-Host "(1/${Steps}) Test module manifest" -ForegroundColor Green - Test-ModuleManifest $ManifestPath - - Write-Host "(2/${Steps}) Import module dependencies" -ForegroundColor Green - Import-Module SQLite, PSScriptAnalyzer - - Write-Host "(3/${Steps}) Run PSScriptAnalyzer" -ForegroundColor Green - Invoke-ScriptAnalyzer -Path $ManifestPath -Recurse -Severity Warning - - Write-Host "(4/${Steps}) Import main module" -ForegroundColor Green - Import-Module $ManifestPath -Force - - Write-Host "(5/${Steps}) Copy items to module directory" -ForegroundColor Green - $Destination = New-Item -ItemType Directory -Path $ModulePath -Name $Name -Force - Remove-Item -Recurse -Force $Destination - Copy-Item $ProjectRootDirectory -Destination $Destination.FullName -Recurse -Force - - if ($PSCmdlet.ShouldProcess($ManifestPath, "Publish ${Name} module version ${Version} to PSGallery")) { - Publish-Module -Name $Name -NuGetApiKey $ApiKey -RequiredVersion $Version -Verbose - } - } - end { - if ($ApiKey) { - $UriBuilder = New-Object System.UriBuilder - $UriBuilder.Scheme = "https" - $UriBuilder.Host = "www.powershellgallery.com" - $UriBuilder.Path = @("packages", $Name, $Version -Join "/") - Start-Process $UriBuilder.ToString() - } - } -} diff --git a/src/Todo.psd1 b/src/Todo.psd1 deleted file mode 100644 index a92a7e0..0000000 --- a/src/Todo.psd1 +++ /dev/null @@ -1,68 +0,0 @@ -# -# Module manifest for module "Todo" -# -# Generated by: Stefan Greve -# -# Generated on: 2/19/2022 -# - -@{ - RootModule = "Todo.psm1" - ModuleVersion = "1.3.2" - CompatiblePSEditions = @("Desktop") - GUID = "1005fb56-c909-4fd8-87db-0d6d57de726c" - Author = "Stefan Greve" - CompanyName = "Advanced Systems" - Copyright = "(c) 2022 Advanced Systems. All rights reserved." - Description = "PowerShell Module to manage your TODO list from the terminal." - PowerShellVersion = "5.1" - RequiredModules = @("SQLite") - FormatsToProcess = @("TodoTable.Format.ps1xml") - - FunctionsToExport = @( - "Get-Task", - "Get-TodoList", - "New-Task", - "New-TodoList", - "Remove-Task" - "Remove-TodoList", - "Update-Task" - ) - - CmdletsToExport = @() - VariablesToExport = @() - AliasesToExport = @( - "gtask", # Get-Task - "gtodo", # Get-TodoList - "ntask", # New-Task - "ntodo", # New-TodoList - "rtask", # Remove-Task - "rtodo", # Remove-TodoList - "utask" # Update-Task - ) - - FileList = @( - "Todo.psd1", - "Todo.psm1", - "TodoTable.Format.ps1xml", - "classes\Task.ps1", - "init\RegisterArgumentCompleters.ps1", - "public\Get-Task.ps1", - "public\Get-TodoList.ps1", - "public\New-Task.ps1", - "public\New-TodoList.ps1", - "public\Remove-Task.ps1", - "public\Remove-TodoList.ps1", - "public\TodoList.sql", - "public\Update-Task.ps1" - ) - - PrivateData = @{ - PSData = @{ - Tags = @("PSEdition_Desktop", "Windows", "Todo", "Productivity") - LicenseUri = "https://www.gnu.org/licenses/gpl-3.0.en.html" - ProjectUri = "https://github.com/Advanced-Systems/todo" - ReleaseNotes = "https://github.com/Advanced-Systems/todo/blob/master/CHANGELOG.md" - } - } -} diff --git a/src/Todo.psm1 b/src/Todo.psm1 deleted file mode 100644 index f5bc531..0000000 --- a/src/Todo.psm1 +++ /dev/null @@ -1,30 +0,0 @@ -if (Test-Path "${PSScriptRoot}\classes\classes.psd1") { - $ClassLoadOrder = Import-PowerShellDataFile -Path "${PSScriptRoot}\classes\classes.psd1" -ErrorAction SilentlyContinue -} - -foreach ($Class in $ClassLoadOrder.Order) { - $Path = '{0}\classes\{1}.ps1' -f $PSScriptRoot, $Class - if (Test-Path $Path) { - . $Path - } -} - -$Public = @( Get-ChildItem -Path "${PSScriptRoot}\public\*.ps1" -ErrorAction SilentlyContinue ) -$Private = @( Get-ChildItem -Path "${PSScriptRoot}\private\*.ps1" -ErrorAction SilentlyContinue ) - -foreach ($Import in @($Public + $Private)) { - try { - Write-Verbose "Importing $($Import.FullName)" - . $Import.FullName - } - catch { - Write-Error -Message "Failed to import function $($Import.FullName): $_" - } -} - -Export-ModuleMember -Function $Public.Basename -Alias * - -Get-ChildItem -Path "$PSScriptRoot/init" | ForEach-Object { - Write-Verbose "Initializing $($_.Name)" - . $_.FullName -} diff --git a/src/TodoTable.Format.ps1xml b/src/TodoTable.Format.ps1xml deleted file mode 100644 index e8e644d..0000000 --- a/src/TodoTable.Format.ps1xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - TodoTable - - Task - - - - - - 4 - right - - - - 12 - left - - - - 12 - left - - - - 12 - left - - - - 40 - left - - - - - - - Id - - - Project - - - Status - - - Priority - - - Description - - - - - - - - diff --git a/src/classes/Task.ps1 b/src/classes/Task.ps1 deleted file mode 100644 index ccdd2eb..0000000 --- a/src/classes/Task.ps1 +++ /dev/null @@ -1,21 +0,0 @@ -class Task { - [ValidateNotNullOrEmpty()][int] $Id - [ValidateNotNullOrEmpty()][string] $Project - [ValidateNotNullOrEmpty()][string] $Description - [ValidateSet("High", "Medium", "Low")][string] $Priority - [ValidateSet("TODO", "Idea", "Planning", "InProgress", "Testing", "InReview", "Done", "Discarded", "Blocked")][string] $Status - [ValidateNotNullOrEmpty()][DateTime] $StartDate - [ValidateNotNullOrEmpty()][DateTime] $DueDate - [TimeSpan] $Age - - Task([string]$Id, [string]$Project, [string]$Description, [string]$Priority, [string]$Status, [DateTime]$StartDate, [DateTime]$DueDate) { - $this.Id = $Id - $this.Project = $Project - $this.Description = $Description - $this.Priority = $Priority - $this.Status = $Status - $this.StartDate = $StartDate - $this.DueDate = $DueDate - $this.Age = $(Get-Date) - $StartDate - } -} diff --git a/src/classes/classes.psd1 b/src/classes/classes.psd1 deleted file mode 100644 index 6e68f92..0000000 --- a/src/classes/classes.psd1 +++ /dev/null @@ -1,5 +0,0 @@ -@{ - order = @( - ,'Task' - ) -} diff --git a/src/init/RegisterArgumentCompleters.ps1 b/src/init/RegisterArgumentCompleters.ps1 deleted file mode 100644 index 3e8a0e6..0000000 --- a/src/init/RegisterArgumentCompleters.ps1 +++ /dev/null @@ -1,29 +0,0 @@ -using namespace System.Management.Automation - -$CommandNames = @( - "Get-Task" - "Get-TodoList" - "New-Task" - "New-TodoList" - "Remove-Task" - "Remove-TodoList" - "Update-Task" -) - -$RegisterUserParameter = { - param($Command, $Parameter, $WordToComplete, $CommandAst, $FakeBoundParameters) - $SavePath = Join-Path -Path $([Environment]::GetFolderPath("ApplicationData")) -ChildPath "Todo" - $Users = Get-ChildItem -Path $SavePath -Filter "*.db" - $Users | ForEach-Object { [CompletionResult]::new($_.BaseName) } -} - -$CommandNames | ForEach-Object { Register-ArgumentCompleter -CommandName $_ -ParameterName User -ScriptBlock $RegisterUserParameter } - -$RegisterProjectParameter = { - param($Command, $Parameter, $WordToComplete, $CommandAst, $FakeBoundParameters) - $Projects = Get-TodoList | Select-Object -Property Project -Unique - $Projects | ForEach-Object { [CompletionResult]::new($_.Project) } -} - -@("New-Task", "Update-Task") | ForEach-Object { Register-ArgumentCompleter -CommandName $_ -ParameterName Project -ScriptBlock $RegisterProjectParameter } - diff --git a/src/private/Get-SavePath.ps1 b/src/private/Get-SavePath.ps1 deleted file mode 100644 index e476b1e..0000000 --- a/src/private/Get-SavePath.ps1 +++ /dev/null @@ -1,4 +0,0 @@ -function Get-SavePath { - $SavePath = Join-Path -Path $([Environment]::GetFolderPath("ApplicationData")) -ChildPath "Todo" - Write-Output $SavePath -} diff --git a/src/public/Get-Task.ps1 b/src/public/Get-Task.ps1 deleted file mode 100644 index c32efb7..0000000 --- a/src/public/Get-Task.ps1 +++ /dev/null @@ -1,66 +0,0 @@ -function Get-Task { - <# - .SYNOPSIS - Get a task by ID. - - .DESCRIPTION - Get a task by ID. See also Get-TodoList. - - .PARAMETER Id - Defines the ID of a task that is to be searched. - - .PARAMETER User - Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. - - .INPUTS - You can pipe IDs as integers to Get-Task. - - .OUTPUTS - A Task object. - - .EXAMPLE - PS C:\> Get-Task 42 | select Description - Get the description of task #42. - - .EXAMPLE - PS C:\> 1..10 | Get-Task - Get the first ten tasks in your TODO list. If there are currently less than ten tasks in your TODO list, return the entire TODO list instead. - #> - [Alias("gtask")] - [OutputType("Task")] - [CmdletBinding()] - param( - [Parameter(Position = 0, Mandatory, ValueFromPipeline)] - [int[]] $Id, - - [Parameter()] - [string] $User = $env:USERNAME - ) - - begin { - $DatabasePath = Join-Path -Path $(Get-SavePath) -ChildPath "${User}.db" - - if (-not (Test-Path $DatabasePath)) { - Write-Error -Message "This TODO list does not exist. You can create one with the command 'New-TodoList -User ${User}'" -Category ObjectNotFound -ErrorAction Stop - } - - $Connection = New-Object -TypeName System.Data.SQLite.SQLiteConnection - $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" - $Connection.Open() - } - process { - foreach ($i in $Id) { - $Sql = $Connection.CreateCommand() - $Sql.CommandText = "SELECT * FROM TodoList WHERE Id = $i" - $Adapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $Sql - $Data = New-Object System.Data.DataSet - [void]$Adapter.Fill($Data) - $Task = $Data.Tables[0] | ForEach-Object { [Task]::new($_.Id, $_.Project, $_.Description, $_.Priority, $_.Status, $_.StartDate, $_.DueDate) } - Write-Output $Task - } - } - end { - $Connection.Close() - $Sql.Dispose() - } -} diff --git a/src/public/Get-TodoList.ps1 b/src/public/Get-TodoList.ps1 deleted file mode 100644 index e01965f..0000000 --- a/src/public/Get-TodoList.ps1 +++ /dev/null @@ -1,125 +0,0 @@ -function Get-TodoList { - <# - .SYNOPSIS - List all tasks from a TODO list. - - .DESCRIPTION - List all tasks from a TODO list where status is not set to 'Done' or 'Discarded'. Supply a filter to define custom rules or pipe the output to Where-Object. - - .PARAMETER All - List all tasks regardless of their current status. - - .PARAMETER Filter - Use the filter in combination with a comparison operator to apply simple filters on this list. - - .PARAMETER User - Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. - - .INPUTS - None. You cannot pipe objects to Get-TodoList. - - .OUTPUTS - A list of Task objects. - - .EXAMPLE - PS C:\> Get-TodoList - List all tasks from the active user TODO list where status is not set to 'Done'. Use the -All switch to list all tasks regardless of their current status. - - .EXAMPLE - PS C:\> Get-TodoList -All | where Priority -eq 'High' - List all tasks from the activce user TODO list with a high priority. - - .EXAMPLE - PS C:\> Get-TodoList -Filter Priority -eq 'High' - List all tasks from the Work TODO list with a high priority. - #> - [Alias("gtodo")] - [OutputType("Task")] - [CmdletBinding()] - param( - [Parameter(ParameterSetName = "All")] - [switch] $All, - - [Parameter(ParameterSetName = "Filter", Mandatory)] - [ValidateSet("Id", "Project", "Description", "Priority", "Status", "StartDate", "DueDate")] - [string] $Filter, - - [Parameter(ParameterSetName = "Filter")] - [Parameter(ParameterSetName = "Equal", Mandatory)] - [string] $eq, - - [Parameter(ParameterSetName = "Filter")] - [Parameter(ParameterSetName = "NotEqual", Mandatory)] - [string] $ne, - - [Parameter(ParameterSetName = "Filter")] - [Parameter(ParameterSetName = "GreaterThan", Mandatory)] - [string] $gt, - - [Parameter(ParameterSetName = "Filter")] - [Parameter(ParameterSetName = "GreaterEqual", Mandatory)] - [string] $ge, - - [Parameter(ParameterSetName = "Filter")] - [Parameter(ParameterSetName = "LessThan", Mandatory)] - [string] $lt, - - [Parameter(ParameterSetName = "Filter")] - [Parameter(ParameterSetName = "LessEqual", Mandatory)] - [string] $le, - - [Parameter()] - [string] $User = $env:USERNAME - ) - - begin { - $DatabasePath = Join-Path -Path $(Get-SavePath) -ChildPath "${User}.db" - - if (-not (Test-Path $DatabasePath)) { - Write-Error -Message "This TODO list does not exist. You can create one with the command 'New-TodoList -User ${User}'" -Category ObjectNotFound -ErrorAction Stop - } - - $Connection = New-Object -TypeName System.Data.SQLite.SQLiteConnection - $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" - $Connection.Open() - } - process { - $Sql = $Connection.CreateCommand() - - if ($eq) { - $Operator = "=" - $Value = $eq - } - elseif ($ne) { - $Operator = "<>" - $Value = $ne - } - elseif ($gt) { - $Operator = ">" - $Value = $gt - } - elseif ($ge) { - $Operator = ">=" - $Value = $ge - } - elseif ($lt) { - $Operator = "<" - $Value = $lt - } - else { - $Operator = "<=" - $Value = $le - } - - $Sql.CommandText = if ($Filter) { "SELECT * FROM TodoList WHERE ${Filter} ${Operator} '${Value}'" } else { "SELECT * FROM TodoList $(if ($All) { '' } else { "WHERE Status != 'Done' AND Status != 'Discarded'" })" } - $Adapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $Sql - $Data = New-Object System.Data.DataSet - [void]$Adapter.Fill($Data) - $TaskTable = $Data.Tables[0] | ForEach-Object { [Task]::new($_.Id, $_.Project, $_.Description, $_.Priority, $_.Status, $_.StartDate, $_.DueDate) } - Write-Output $TaskTable - } - end { - $Connection.Close() - $Sql.Dispose() - } -} diff --git a/src/public/New-Task.ps1 b/src/public/New-Task.ps1 deleted file mode 100644 index 1796f7d..0000000 --- a/src/public/New-Task.ps1 +++ /dev/null @@ -1,97 +0,0 @@ -function New-Task { - <# - .SYNOPSIS - Adds a new task to a TODO list. - - .DESCRIPTION - Adds a new task to a TODO list. It is possible to manage multiple TODO lists in separate databases at once. - - .PARAMETER Description - Sets the description of this task. - - .PARAMETER DueDate - Sets the due date for this task. - - .PARAMETER Priority - Sets the perceived priority to this task. - - .PARAMETER Project - Associates this task with a project (group). - - .PARAMETER Status - Sets the current status to this task. - - .PARAMETER User - Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. - - .INPUTS - None. You cannot pipe objects to New-Task. - - .OUTPUTS - None. - - .EXAMPLE - PS C:\> New-Task "Update VM" - Add a new item to the current user's TODO list. Description is the only required parameter in this Cmdlet, all other properties will be automatically populated with their respective default values. - - .EXAMPLE - PS C:\> New-Task -Description "Review PR #186" -Project "Backend" -Priority Medium - NOTE: You can always update specific Properties later with the Update-Task Cmdlet. - #> - [Alias("ntask")] - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Position = 0, Mandatory)] - [ValidateNotNullOrEmpty()] - [string] $Description, - - [Parameter()] - [string] $Project = "Default", - - [Parameter()] - [ValidateSet("High", "Medium", "Low")] - [string] $Priority = "Low", - - [Parameter()] - [ValidateSet("TODO", "Idea", "Planning", "InProgress", "Testing", "InReview", "Done", "Discarded", "Blocked")] - [string] $Status = "TODO", - - [Parameter()] - [DateTime] $DueDate, - - [Parameter()] - [string] $User = $env:USERNAME - ) - - begin { - $DatabasePath = Join-Path -Path $(Get-SavePath) -ChildPath "${User}.db" - - if (-not (Test-Path $DatabasePath)) { - Write-Error -Message "This TODO list does not exist. You can create one with the command 'New-TodoList -User ${User}'" -Category ObjectNotFound -ErrorAction Stop - } - - $Connection = New-Object -TypeName System.Data.SQLite.SQLiteConnection - $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" - $Connection.Open() - $Today = Get-Date - } - process { - $Sql = $Connection.CreateCommand() - $Param1 = $Sql.Parameters.AddWithValue("@Id", $null) - $Param2 = $Sql.Parameters.AddWithValue("@Project", $Project) - $Param3 = $Sql.Parameters.AddWithValue("@Description", $Description) - $Param4 = $Sql.Parameters.AddWithValue("@Priority", $Priority) - $Param5 = $Sql.Parameters.AddWithValue("@Status", $Status) - $Param6 = $Sql.Parameters.AddWithValue("@StartDate", $Today) - $Param7 = $Sql.Parameters.AddWithValue("@DueDate", $(if ($DueDate) { $DueDate } else { [DateTime]::new($Today.Year, 12, 31) })) - $Sql.CommandText = "INSERT INTO TodoList (Id,Project,Description,Priority,Status,StartDate,DueDate) VALUES (@Id,@Project,@Description,@Priority,@Status,@StartDate,@DueDate)" - - if ($PSCmdlet.ShouldProcess($Sql.CommandText)) { - $Sql.ExecuteNonQuery() | Out-Null - } - } - end { - $Connection.Close() - $Sql.Dispose() - } -} diff --git a/src/public/New-TodoList.ps1 b/src/public/New-TodoList.ps1 deleted file mode 100644 index eaf4f31..0000000 --- a/src/public/New-TodoList.ps1 +++ /dev/null @@ -1,50 +0,0 @@ -function New-TodoList { - <# - .SYNOPSIS - Creates a new database for a TODO list. - - .DESCRIPTION - Creates a new database for a TODO list. It is possible to manage multiple TODO lists in separate databases at once. - - .PARAMETER User - Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. - - .INPUTS - None. You cannot pipe objects to New-TodoList. - - .OUTPUTS - None. New-TodoList creates a new system resource, i.e. a database file. - - .EXAMPLE - PS C:\> New-TodoList - Create a new TODO list for the active user account. - - .EXAMPLE - PS C:\> New-TodoList -User "Mazawa Shinonome" - Create a new TODO list for a specific user. - #> - [Alias("ntodo")] - [CmdletBinding()] - param( - [Parameter()] - [string] $User = $env:USERNAME - ) - - begin { - $SavePath = Get-SavePath - New-Item -ItemType Directory -Path $SavePath -Force | Out-Null - $DatabasePath = Join-Path -Path $SavePath -ChildPath "${User}.db" - $Connection = New-Object -TypeName System.Data.SQLite.SQLiteConnection - $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" - $Connection.Open() - } - process { - $Sql = $Connection.CreateCommand() - $Sql.CommandText = Get-Content $(Join-Path -Path $PSScriptRoot -ChildPath "TodoList.sql") - $Sql.ExecuteNonQuery() | Out-Null - } - end { - $Connection.Close() - $Sql.Dispose() - } -} diff --git a/src/public/Remove-Task.ps1 b/src/public/Remove-Task.ps1 deleted file mode 100644 index 7031eea..0000000 --- a/src/public/Remove-Task.ps1 +++ /dev/null @@ -1,64 +0,0 @@ -function Remove-Task { - <# - .SYNOPSIS - Remove a task from a TODO list. - - .DESCRIPTION - Remove a task from a TODO list by Id. - - .PARAMETER Id - Defines the ID of a task that is to be removed. - - .PARAMETER User - Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. - - .INPUTS - You can pipe Task objects to Remove-Task. - - .OUTPUTS - None. - - .EXAMPLE - PS C:\> Remove-Task 23 - Remove a task whose Id equals 23. - - .EXAMPLE - PS C:\> Get-TodoList -All | where Status -eq 'Done' | Remove-Task -WhatIf - Remove all tasks from the current user's TODO list that were marked as done. - #> - [Alias("rtask")] - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Position = 0, Mandatory, ValueFromPipelineByPropertyName)] - [int[]] $Id, - - [Parameter()] - [string] $User = $env:USERNAME - ) - - begin { - $DatabasePath = Join-Path -Path $(Get-SavePath) -ChildPath "${User}.db" - - if (-not (Test-Path $DatabasePath)) { - Write-Error -Message "This TODO list does not exist. You can create one with the command 'New-TodoList -User ${User}'" -Category ObjectNotFound -ErrorAction Stop - } - - $Connection = New-Object -TypeName System.Data.SQLite.SQLiteConnection - $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" - $Connection.Open() - } - process { - foreach ($i in $Id) { - $Sql = $Connection.CreateCommand() - $Sql.CommandText = "DELETE FROM TodoList WHERE Id = ${i}" - - if ($PSCmdlet.ShouldProcess($Sql.CommandText)) { - $Sql.ExecuteNonQuery() | Out-Null - } - } - } - end { - $Connection.Close() - $Sql.Dispose() - } -} diff --git a/src/public/Remove-TodoList.ps1 b/src/public/Remove-TodoList.ps1 deleted file mode 100644 index d2bfacf..0000000 --- a/src/public/Remove-TodoList.ps1 +++ /dev/null @@ -1,51 +0,0 @@ -function Remove-TodoList { - <# - .SYNOPSIS - Deletes a TODO list database. - - .DESCRIPTION - Deletes a TODO list database. - - .PARAMETER User - Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. - - .INPUTS - None. You cannot pipe objects to Remove-TodoList. - - .OUTPUTS - None. - - .EXAMPLE - PS C:\> Remove-TodoList - Remove the default TODO list. - - .EXAMPLE - PS C:\> Remove-TodoList -User "Mazawa Shinonome" - Remove the TODO list for a specific user. - - .EXAMPLE - PS C:\> Get-TodoList | where Status -eq 'Discarded' | Remove-Task -WhatIf - Dry-run mass removal of all discarded tasks. - #> - [Alias("rtodo")] - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] - param( - [Parameter()] - [string] $User = $env:USERNAME - ) - - begin { - $DatabasePath = Join-Path -Path $(Get-SavePath) -ChildPath "${User}.db" - } - process { - if (Test-Path $DatabasePath -IsValid) { - if ($PSCmdlet.ShouldProcess($DatabasePath)) { - Remove-Item $DatabasePath - } - } - else { - Write-Error -Category ObjectNotFound -ErrorAction Stop - } - } - end {} -} diff --git a/src/public/TodoList.sql b/src/public/TodoList.sql deleted file mode 100644 index 12b65e4..0000000 --- a/src/public/TodoList.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE IF NOT EXISTS TodoList ( - Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, - Project TEXT NOT NULL, - Description TEXT NOT NULL, - Priority TEXT NOT NULL, - Status TEXT NOT NULL, - StartDate DATETIME NOT NULL, - DueDate DATETIME NOT NULL -); diff --git a/src/public/Update-Task.ps1 b/src/public/Update-Task.ps1 deleted file mode 100644 index a0c591e..0000000 --- a/src/public/Update-Task.ps1 +++ /dev/null @@ -1,120 +0,0 @@ -function Update-Task { - <# - .SYNOPSIS - Update one or more properties of a specific task. - - .DESCRIPTION - Adds a new task to a TODO list by Id. It is possible to manage multiple TODO lists in separate databases at once. - - .PARAMETER Id - Defines the ID of a task that is to be updated. - - .PARAMETER Description - Sets the description of this task. - - .PARAMETER DueDate - Sets the due date for this task. - - .PARAMETER Priority - Sets the perceived priority to this task. - - .PARAMETER Project - Associates this task with a project (group). - - .PARAMETER Status - Sets the current status to this task. - - .PARAMETER User - Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. - - .INPUTS - You can pipe Task objects to Update-Task. - - .OUTPUTS - None. - - .EXAMPLE - PS C:\> Update-Task 1 -Status Done - Mark the first task as done. - - .EXAMPLE - PS C:\> Update-Task -Id 42 -Priority High -Status InProgress - Update the priority of task 42 to high and change its current status to in-progress. - - .EXAMPLE - PS C:\> Get-TodoList | where { $(Get-Date) -gt $_.DueDate -and $_.Status -ne 'Done' } | Update-Task -Status Discarded - Search all overdue task records that were never completed and update their status to discarded - #> - [Alias("utask")] - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Position = 0, Mandatory, ValueFromPipelineByPropertyName)] - [int[]] $Id, - - [Parameter()] - [string] $Project, - - [Parameter()] - [string] $Description, - - [Parameter()] - [ValidateSet("High", "Medium", "Low")] - [string] $Priority, - - [Parameter()] - [ValidateSet("TODO", "Idea", "Planning", "InProgress", "Testing", "InReview", "Done", "Discarded", "Blocked")] - [string] $Status, - - [Parameter()] - [DateTime] $DueDate, - - [Parameter()] - [string] $User = $env:USERNAME - ) - - begin { - $DatabasePath = Join-Path -Path $(Get-SavePath) -ChildPath "${User}.db" - - if (-not (Test-Path $DatabasePath)) { - Write-Error -Message "This TODO list does not exist. You can create one with the command 'New-TodoList -User ${User}'" -Category ObjectNotFound -ErrorAction Stop - } - - $Connection = New-Object -TypeName System.Data.SQLite.SQLiteConnection - $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" - $Connection.Open() - } - process { - foreach ($i in $Id) { - $Sql = $Connection.CreateCommand() - $QueryBuilder = New-Object System.Collections.Generic.List[string] - $QueryBuilder.Add("UPDATE TodoList SET ") - - if ($Project) { - $QueryBuilder.Add("Project = '${Project}'$(if ($Description -or $Priority -or $Status -or $DueDate) {','} else {''})") - } - if ($Description) { - $QueryBuilder.Add("Description = '${Description}'$(if ($Priority -or $Status -or $DueDate) {','} else {''})") - } - if ($Priority) { - $QueryBuilder.Add("Priority = '${Priority}'$(if ($Status -or $DueDate) {','} else {''})") - } - if ($Status) { - $QueryBuilder.Add("Status = '${Status}'$(if ($DueDate) {','} else {''})") - } - if ($DueDate) { - $QueryBuilder.Add("DueDate = '$($DueDate.ToString("yyyy-MM-dd HH:mm:ss.fffffff"))'") - } - - $QueryBuilder.Add(" WHERE Id=${i}") - $Sql.CommandText = $QueryBuilder -Join '' - - if ($PSCmdlet.ShouldProcess($Sql.CommandText)) { - $Sql.ExecuteNonQuery() | Out-Null - } - } - } - end { - $Connection.Close() - $Sql.Dispose() - } -} From 9dadb7f711daf719eba8051b275b6295c7a89e8e Mon Sep 17 00:00:00 2001 From: StefanGreve Date: Sun, 1 Dec 2024 20:47:12 +0100 Subject: [PATCH 2/4] Re-implement core features of this module --- .config/dotnet-tools.json | 13 +++ .husky/pre-commit | 4 + .husky/pre-push | 4 + .husky/task-runner.json | 63 ++++++++++++ README.md | 2 +- nuget.config | 7 ++ scripts/build.ps1 | 107 ++++++++++++++++++++ scripts/publish.ps1 | 41 ++++++++ scripts/test.ps1 | 36 +++++++ src/Classes/Task.ps1 | 37 +++++++ src/Formats/Task.ps1xml | 70 +++++++++++++ src/Private/Get-SavePath.ps1 | 13 +++ src/Private/TodoList.sql | 9 ++ src/Private/Variables.ps1 | 11 ++ src/Public/Get-Task.ps1 | 93 +++++++++++++++++ src/Public/Get-TodoList.ps1 | 157 +++++++++++++++++++++++++++++ src/Public/New-Task.ps1 | 115 +++++++++++++++++++++ src/Public/New-TodoList.ps1 | 65 ++++++++++++ src/Public/Remove-Task.ps1 | 74 ++++++++++++++ src/Public/Remove-TodoList.ps1 | 56 ++++++++++ src/Public/Update-Task.ps1 | 135 +++++++++++++++++++++++++ src/Scripts/ArgumentCompleters.ps1 | 50 +++++++++ src/Todo.psd1 | 139 +++++++++++++++++++++++++ src/Todo.psm1 | 74 ++++++++++++++ tests/module.tests.ps1 | 32 ++++++ 25 files changed, 1406 insertions(+), 1 deletion(-) create mode 100644 .config/dotnet-tools.json create mode 100644 .husky/pre-commit create mode 100644 .husky/pre-push create mode 100644 .husky/task-runner.json create mode 100644 nuget.config create mode 100644 scripts/build.ps1 create mode 100644 scripts/publish.ps1 create mode 100644 scripts/test.ps1 create mode 100644 src/Classes/Task.ps1 create mode 100644 src/Formats/Task.ps1xml create mode 100644 src/Private/Get-SavePath.ps1 create mode 100644 src/Private/TodoList.sql create mode 100644 src/Private/Variables.ps1 create mode 100644 src/Public/Get-Task.ps1 create mode 100644 src/Public/Get-TodoList.ps1 create mode 100644 src/Public/New-Task.ps1 create mode 100644 src/Public/New-TodoList.ps1 create mode 100644 src/Public/Remove-Task.ps1 create mode 100644 src/Public/Remove-TodoList.ps1 create mode 100644 src/Public/Update-Task.ps1 create mode 100644 src/Scripts/ArgumentCompleters.ps1 create mode 100644 src/Todo.psd1 create mode 100644 src/Todo.psm1 create mode 100644 tests/module.tests.ps1 diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..e6df774 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "husky": { + "version": "0.7.1", + "commands": [ + "husky" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 0000000..6937b36 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +dotnet husky run --group pre-commit diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100644 index 0000000..3af48fa --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +dotnet husky run --group pre-push diff --git a/.husky/task-runner.json b/.husky/task-runner.json new file mode 100644 index 0000000..517c873 --- /dev/null +++ b/.husky/task-runner.json @@ -0,0 +1,63 @@ +{ + "$schema": "https://alirezanet.github.io/Husky.Net/schema.json", + "tasks": [ + { + "name": "unstage-manifest", + "group": "pre-commit", + "command": "git", + "args": [ + "reset", + "HEAD", + "--", + "*.psd1" + ] + }, + { + "name": "restore-manifest", + "group": "pre-commit", + "command": "git", + "args": [ + "restore", + "*.psd1" + ] + }, + { + "name": "build-module", + "group": "pre-push", + "command": "pwsh", + "args": [ + "-NoProfile", + "-ExecutionPolicy", + "ByPass", + "-File", + "./scripts/build.ps1", + "-Version", + "0.0.0" + ], + "include": [ + "*.ps1", + "*.psm1", + "*.psd1", + "*.ps1xml" + ] + }, + { + "name": "test-module", + "group": "pre-push", + "command": "pwsh", + "args": [ + "-NoProfile", + "-ExecutionPolicy", + "ByPass", + "-File", + "./scripts/test.ps1" + ], + "include": [ + "*.ps1", + "*.psm1", + "*.psd1", + "*.ps1xml" + ] + } + ] + } diff --git a/README.md b/README.md index f54b017..58e09e9 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Install-Module -Name Todo ## Required Modules -- [`SQList`](https://www.powershellgallery.com/packages/SQLite/2.0) +- [`SQLite`](https://www.powershellgallery.com/packages/SQLite/2.0) ## Basic Usage diff --git a/nuget.config b/nuget.config new file mode 100644 index 0000000..de291b7 --- /dev/null +++ b/nuget.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/scripts/build.ps1 b/scripts/build.ps1 new file mode 100644 index 0000000..6e1eb20 --- /dev/null +++ b/scripts/build.ps1 @@ -0,0 +1,107 @@ +using namespace System.IO + +param( + [string] $ModuleName = "Todo", + + [Parameter(Mandatory)] + [string] $Version +) + +begin { + $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path + $ProjectRoot = $(Get-Item $([Path]::Combine($ScriptPath, ".."))).FullName + Push-Location $([Path]::Combine($ProjectRoot, "src")) + + $Steps = 5 + $ManifestPath = "${ModuleName}.psd1" +} +process { + #region Step 1 - Install Dependencies + + Write-Host "[1/${Steps}] " -ForegroundColor DarkGray -NoNewline + Write-Host "Install Dependencies" + + if (!(Get-Module SQLite -ListAvailable)) { + Install-Module SQLite -Scope CurrentUser -Force + } + + #endregion + + Import-Module SQLite + + #region Step 2 - Update Manifest + + Write-Host "[2/${Steps}] " -ForegroundColor DarkGray -NoNewline + Write-Host "Update Manifest" + + $FunctionsToExport = Get-ChildItem -Path "./Public" -Filter "*.ps1" + | Select-Object -ExpandProperty BaseName + + $FileList = Get-ChildItem -Recurse -Path "." + | Where-Object { ! $_.PSIsContainer } + | Select-Object -ExpandProperty FullName + | Resolve-Path -Relative + + $Formats = Get-ChildItem -Path "./Formats" -Filter "*.ps1xml" + | Select-Object -ExpandProperty FullName + | Resolve-Path -Relative + + $Scripts = Get-ChildItem -Path "./Scripts" -Filter "*.ps1" + | Select-Object -ExpandProperty FullName + | Resolve-Path -Relative + + $ManifestParameter = @{ + Path = $ManifestPath + ModuleVersion = $Version + FunctionsToExport = @($FunctionsToExport) + FileList = @($FileList) + FormatsToProcess = @($Formats) + ScriptsToProcess = @($Scripts) + } + + Update-ModuleManifest @ManifestParameter -ErrorAction Stop + $Module = Import-PowerShellDataFile -Path $ManifestPath + $Module | Write-Output | Format-Table + + #endregion + + #region Step 3 - Test Module Manifest + + Write-Host "[3/${Steps}] " -ForegroundColor DarkGray -NoNewline + Write-Host "Test Module Manifest" + Test-ModuleManifest -Path $ManifestPath -ErrorAction Stop + Write-Host + + #endregion + + #region Step 4 - Import Module + + Write-Host "[4/${Steps}] " -ForegroundColor DarkGray -NoNewline + Write-Host "Import Module" + Write-Host + + Import-Module -Name "./${ManifestPath}" -Force -ErrorAction Stop + + #endregion + + #region Step 5 - Run Analyzer + + Write-Host "[5/${Steps}] " -ForegroundColor DarkGray -NoNewline + Write-Host "Run Analyzer" + Write-Host + + if (!$(Get-Module PSScriptAnalyzer -ListAvailable)) { + Install-Module PSScriptAnalyzer -Scope CurrentUser -Force + } + + Import-Module PSScriptAnalyzer + Invoke-ScriptAnalyzer -Path "./${ManifestPath}" ` + -Severity Warning ` + -Recurse ` + -ReportSummary + + #endregion +} +clean { + Pop-Location +} diff --git a/scripts/publish.ps1 b/scripts/publish.ps1 new file mode 100644 index 0000000..ccde428 --- /dev/null +++ b/scripts/publish.ps1 @@ -0,0 +1,41 @@ +using namespace System.IO + +[CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] +param( + [string] $ModuleName = "Todo", + + [Parameter(Mandatory)] + [string] $ApiKey, + + [Parameter(Mandatory)] + [string] $Version +) + +begin { + $ManifestPath = "${ModuleName}.psd1" + + $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path + $ProjectRoot = $(Get-Item $([Path]::Combine($ScriptPath, ".."))).FullName + Push-Location $ProjectRoot +} +process { + if ($Version -eq "0.0.0") { + Write-Error "Version is not configured correctly." -Category InvalidArgument -ErrorAction Stop + } + + # 1 - Build + & "./scripts/build.ps1" -Version $Version + + # 2 - Test + & "./scripts/test.ps1" -Version $Version + + # 3 - Deploy + if ($PSCmdlet.ShouldProcess($ManifestPath, "Publish `"${ModuleName}`" (Version ${Version}) to PSGallery")) { + Publish-Module -Name "./src/${ManifestPath}" ` + -NuGetApiKey $ApiKey ` + -RequiredVersion $Version + } +} +clean { + Pop-Location +} diff --git a/scripts/test.ps1 b/scripts/test.ps1 new file mode 100644 index 0000000..c14744b --- /dev/null +++ b/scripts/test.ps1 @@ -0,0 +1,36 @@ +using namespace System.IO + +param( + [string] $Version = "0.0.0", + + [switch] $Build +) + +begin { + $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path + $ProjectRoot = $(Get-Item $([Path]::Combine($ScriptPath, ".."))).FullName +} +process { + if (!$(Get-Module SQLite -ListAvailable)) { + Install-Module SQLite -Scope CurrentUser -Force + } + + Import-Module SQLite + + if (!$(Get-Module Pester -ListAvailable)) { + Install-Module Pester -Scope CurrentUser -Force + } + + Import-Module Pester + + $Container = New-PesterContainer ` + -Path $([Path]::Combine($ProjectRoot, "tests", "module.tests.ps1")) ` + -Data @{ + Version = $Version + Build = $Build.IsPresent + } + + Invoke-Pester -Container $Container -Output Detailed +} +clean { +} diff --git a/src/Classes/Task.ps1 b/src/Classes/Task.ps1 new file mode 100644 index 0000000..ce48119 --- /dev/null +++ b/src/Classes/Task.ps1 @@ -0,0 +1,37 @@ +using namespace System + +class Task { + [ValidateNotNullOrEmpty()] + [int] $Id + + [ValidateNotNullOrEmpty()] + [string] $Project + + [ValidateNotNullOrEmpty()] + [string] $Description + + [ValidateSet("High", "Medium", "Low")] + [string] $Priority + + [ValidateSet("TODO", "Idea", "Planning", "InProgress", "Testing", "InReview", "Done", "Discarded", "Blocked")] + [string] $Status + + [ValidateNotNullOrEmpty()] + [DateTime] $StartDate + + [ValidateNotNullOrEmpty()] + [DateTime] $DueDate + + [TimeSpan] $Age + + Task([string]$Id, [string]$Project, [string]$Description, [string]$Priority, [string]$Status, [DateTime]$StartDate, [DateTime]$DueDate) { + $this.Id = $Id + $this.Project = $Project + $this.Description = $Description + $this.Priority = $Priority + $this.Status = $Status + $this.StartDate = $StartDate + $this.DueDate = $DueDate + $this.Age = $([DateTime]::Now) - $StartDate + } +} diff --git a/src/Formats/Task.ps1xml b/src/Formats/Task.ps1xml new file mode 100644 index 0000000..46b62af --- /dev/null +++ b/src/Formats/Task.ps1xml @@ -0,0 +1,70 @@ + + + + + + TodoTable + + Task + + + + + + 4 + right + + + + 12 + left + + + + 12 + left + + + + 12 + left + + + + 40 + left + + + + + + + Id + + + Project + + + Status + + + Priority + + + Description + + + + + + + + diff --git a/src/Private/Get-SavePath.ps1 b/src/Private/Get-SavePath.ps1 new file mode 100644 index 0000000..983e65b --- /dev/null +++ b/src/Private/Get-SavePath.ps1 @@ -0,0 +1,13 @@ +using namespace System +using namespace System.IO + +function Get-SavePath { + [OutputType([Path])] + param() + + process { + $ModuleName = "Todo" + $SavePath = [Path]::Combine([Environment]::GetFolderPath("ApplicationData"), $ModuleName) + Write-Output $SavePath + } +} diff --git a/src/Private/TodoList.sql b/src/Private/TodoList.sql new file mode 100644 index 0000000..12b65e4 --- /dev/null +++ b/src/Private/TodoList.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS TodoList ( + Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + Project TEXT NOT NULL, + Description TEXT NOT NULL, + Priority TEXT NOT NULL, + Status TEXT NOT NULL, + StartDate DATETIME NOT NULL, + DueDate DATETIME NOT NULL +); diff --git a/src/Private/Variables.ps1 b/src/Private/Variables.ps1 new file mode 100644 index 0000000..274aca0 --- /dev/null +++ b/src/Private/Variables.ps1 @@ -0,0 +1,11 @@ +using namespace System.Diagnostics.CodeAnalysis + +[SuppressMessage("PSUseDeclaredVarsMoreThanAssignments", "")] +param() + +#region Error Messages + +$DatabaseDoesNotExistErrorMessage = "This TODO list does not exist." +$DatabaseConnectionErrorMessage = "An unexpected error occurred while trying to establish a connect to the Database" + +#endregion diff --git a/src/Public/Get-Task.ps1 b/src/Public/Get-Task.ps1 new file mode 100644 index 0000000..847c1c8 --- /dev/null +++ b/src/Public/Get-Task.ps1 @@ -0,0 +1,93 @@ +using namespace System +using namespace System.Data +using namespace System.Data.SQLite +using namespace System.IO + +function Get-Task { + <# + .SYNOPSIS + Get a task by ID. + + .DESCRIPTION + Get a task by ID. See also Get-TodoList. + + .PARAMETER Id + Defines the ID of a task that is to be searched. + + .PARAMETER User + Each TODO list is associated to a user account. The default user account + is read from the username environment variable. Specify a value for this + parameter to access an another TODO list from a different user. + + .INPUTS + You can pipe IDs as integers to Get-Task. + + .OUTPUTS + A Task object. + + .EXAMPLE + PS C:\> Get-Task 42 | select Description + Get the description of task #42. + + .EXAMPLE + PS C:\> 1..10 | Get-Task + Get the first ten tasks in your TODO list. If there are currently less + than ten tasks in your TODO list, return the entire TODO list instead. + #> + [Alias("gtask")] + [OutputType("Task")] + [CmdletBinding()] + param( + [Parameter(Position = 0, Mandatory, ValueFromPipeline)] + [int[]] $Id, + + [Parameter()] + [string] $User = [Environment]::UserName + ) + + begin { + $SavePath = Get-SavePath + $DatabasePath = [Path]::Combine($SavePath, "${User}.db") + + if (!(Test-Path $DatabasePath)) { + Write-Error $DatabaseDoesNotExistErrorMessage -Category ObjectNotFound -ErrorAction Stop + } + + $Connection = [SQLiteConnection]::new() + $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" + $Connection.Open() + } + process { + foreach ($i in $Id) { + $Sql = $Connection.CreateCommand() + $Sql.CommandText = "SELECT * FROM TodoList WHERE Id = $i" + + try { + $Adapter = [SQLiteDataAdapter]::new($Sql) + $Data = [DataSet]::new() + [void] $Adapter.Fill($Data) + + $Task = $Data.Tables[0] | ForEach-Object { + [Task]::new( + $_.Id, + $_.Project, + $_.Description, + $_.Priority, + $_.Status, + $_.StartDate, + $_.DueDate + ) + } + + Write-Output $Task + } catch { + Write-Error $DatabaseConnectionErrorMessage -Category ConnectionError -ErrorAction Stop + } finally { + $Sql.Dispose() + } + } + } + clean { + $Connection.Close() + } +} diff --git a/src/Public/Get-TodoList.ps1 b/src/Public/Get-TodoList.ps1 new file mode 100644 index 0000000..8e4fb66 --- /dev/null +++ b/src/Public/Get-TodoList.ps1 @@ -0,0 +1,157 @@ +using namespace System +using namespace System.Data +using namespace System.Data.SQLite +using namespace System.IO + +function Get-TodoList { + <# + .SYNOPSIS + List all tasks from a TODO list. + + .DESCRIPTION + List all tasks from a TODO list where status is not set to 'Done' or 'Discarded'. + Supply a filter to define custom rules or pipe the output to Where-Object. + + .PARAMETER All + List all tasks regardless of their current status. + + .PARAMETER Filter + Use the filter in combination with a comparison operator to apply simple + filters on this list. + + .PARAMETER User + Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. + + .INPUTS + None. You cannot pipe objects to Get-TodoList. + + .OUTPUTS + A list of Task objects. + + .EXAMPLE + PS C:\> Get-TodoList + List all tasks from the active user TODO list where status is not set to + 'Done'. Use the -All switch to list all tasks regardless of their current + status. + + .EXAMPLE + PS C:\> Get-TodoList -All | where Priority -eq 'High' + List all tasks from the activce user TODO list with a high priority. + + .EXAMPLE + PS C:\> Get-TodoList -Filter Priority -eq 'High' + List all tasks from the Work TODO list with a high priority. + #> + [Alias("gtodo")] + [OutputType("Task")] + [CmdletBinding()] + param( + [Parameter(ParameterSetName = "All")] + [switch] $All, + + [Parameter(ParameterSetName = "Filter", Mandatory)] + [ValidateSet("Id", "Project", "Description", "Priority", "Status", "StartDate", "DueDate")] + [string] $Filter, + + [Parameter(ParameterSetName = "Filter")] + [Parameter(ParameterSetName = "Equal", Mandatory)] + [string] $eq, + + [Parameter(ParameterSetName = "Filter")] + [Parameter(ParameterSetName = "NotEqual", Mandatory)] + [string] $ne, + + [Parameter(ParameterSetName = "Filter")] + [Parameter(ParameterSetName = "GreaterThan", Mandatory)] + [string] $gt, + + [Parameter(ParameterSetName = "Filter")] + [Parameter(ParameterSetName = "GreaterEqual", Mandatory)] + [string] $ge, + + [Parameter(ParameterSetName = "Filter")] + [Parameter(ParameterSetName = "LessThan", Mandatory)] + [string] $lt, + + [Parameter(ParameterSetName = "Filter")] + [Parameter(ParameterSetName = "LessEqual", Mandatory)] + [string] $le, + + [Parameter()] + [string] $User = [Environment]::UserName + ) + + begin { + $SavePath = Get-SavePath + $DatabasePath = [Path]::Combine($SavePath, "${User}.db") + + if (!(Test-Path $DatabasePath)) { + Write-Error $DatabaseDoesNotExistErrorMessage -Category ObjectNotFound -ErrorAction Stop + } + + $Connection = [SQLiteConnection]::new() + $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" + $Connection.Open() + } + process { + $Sql = $Connection.CreateCommand() + + if ($eq) { + $Operator = "=" + $Value = $eq + } + elseif ($ne) { + $Operator = "<>" + $Value = $ne + } + elseif ($gt) { + $Operator = ">" + $Value = $gt + } + elseif ($ge) { + $Operator = ">=" + $Value = $ge + } + elseif ($lt) { + $Operator = "<" + $Value = $lt + } + else { + $Operator = "<=" + $Value = $le + } + + $Sql.CommandText = if ($Filter) { + "SELECT * FROM TodoList WHERE ${Filter} ${Operator} `"${Value}`"" + } else { + "SELECT * FROM TodoList $($All.IsPresent ? [string]::Empty : "WHERE Status != 'Done' AND Status != 'Discarded'" )" + } + + try { + $Adapter = [SQLiteDataAdapter]::new($Sql) + $Data = [DataSet]::new() + [void] $Adapter.Fill($Data) + + $TaskTable = $Data.Tables[0] | ForEach-Object { + [Task]::new( + $_.Id, + $_.Project, + $_.Description, + $_.Priority, + $_.Status, + $_.StartDate, + $_.DueDate + ) + } + + Write-Output $TaskTable + } catch { + Write-Error $DatabaseConnectionErrorMessage -Category ConnectionError -ErrorAction Stop + } finally { + $Sql.Dispose() + } + } + clean { + $Connection.Close() + } +} diff --git a/src/Public/New-Task.ps1 b/src/Public/New-Task.ps1 new file mode 100644 index 0000000..91b030c --- /dev/null +++ b/src/Public/New-Task.ps1 @@ -0,0 +1,115 @@ +using namespace System +using namespace System.Data.SQLite +using namespace System.IO + +function New-Task { + <# + .SYNOPSIS + Adds a new task to a TODO list. + + .DESCRIPTION + Adds a new task to a TODO list. It is possible to manage multiple TODO + lists in separate databases at once. + + .PARAMETER Description + Sets the description of this task. + + .PARAMETER DueDate + Sets the due date for this task. + + .PARAMETER Priority + Sets the perceived priority to this task. + + .PARAMETER Project + Associates this task with a project (group). + + .PARAMETER Status + Sets the current status to this task. + + .PARAMETER User + Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. + + .INPUTS + None. You cannot pipe objects to New-Task. + + .OUTPUTS + None. + + .EXAMPLE + PS C:\> New-Task "Update VM" + Add a new item to the current user's TODO list. Description is the only + required parameter in this Cmdlet, all other properties will be automatically + populated with their respective default values. + + .EXAMPLE + PS C:\> New-Task -Description "Review PR #186" -Project "Backend" -Priority Medium + NOTE: You can always update specific Properties later with the Update-Task Cmdlet. + #> + [Alias("ntask")] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Position = 0, Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Description, + + [Parameter()] + [string] $Project = "Default", + + [Parameter()] + [ValidateSet("High", "Medium", "Low")] + [string] $Priority = "Low", + + [Parameter()] + [ValidateSet("TODO", "Idea", "Planning", "InProgress", "Testing", "InReview", "Done", "Discarded", "Blocked")] + [string] $Status = "TODO", + + [Parameter()] + [DateTime] $DueDate, + + [Parameter()] + [string] $User = [Environment]::UserName + ) + + begin { + $SavePath = Get-SavePath + $DatabasePath = [Path]::Combine($SavePath, "${User}.db") + + if (!(Test-Path $DatabasePath)) { + Write-Error $DatabaseDoesNotExistErrorMessage -Category ObjectNotFound -ErrorAction Stop + } + + $Connection = [SQLiteConnection]::new() + $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" + $Connection.Open() + + $Today = [DateTime]::Now + } + process { + $Sql = $Connection.CreateCommand() + + $null = & { + $Sql.Parameters.AddWithValue("@Id", $null) + $Sql.Parameters.AddWithValue("@Project", $Project) + $Sql.Parameters.AddWithValue("@Description", $Description) + $Sql.Parameters.AddWithValue("@Priority", $Priority) + $Sql.Parameters.AddWithValue("@Status", $Status) + $Sql.Parameters.AddWithValue("@StartDate", $Today) + $Sql.Parameters.AddWithValue("@DueDate", $($DueDate ? $DueDate : [DateTime]::new($Today.Year, 12, 31))) + } + + $Sql.CommandText = "INSERT INTO TodoList (Id,Project,Description,Priority,Status,StartDate,DueDate) VALUES (@Id,@Project,@Description,@Priority,@Status,@StartDate,@DueDate)" + + if ($PSCmdlet.ShouldProcess($Sql.CommandText)) { + try { + $Sql.ExecuteNonQuery() | Out-Null + } catch { + Write-Error $DatabaseConnectionErrorMessage -Category ConnectionError -ErrorAction Stop + } finally { + $Sql.Dispose() + } + } + } + clean { + $Connection.Close() + } +} diff --git a/src/Public/New-TodoList.ps1 b/src/Public/New-TodoList.ps1 new file mode 100644 index 0000000..8ce3782 --- /dev/null +++ b/src/Public/New-TodoList.ps1 @@ -0,0 +1,65 @@ +using namespace System +using namespace System.Data.SQLite +using namespace System.IO + +function New-TodoList { + <# + .SYNOPSIS + Creates a new database for a TODO list. + + .DESCRIPTION + Creates a new database for a TODO list. It is possible to manage multiple + TODO lists in separate databases at once. + + .PARAMETER User + Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. + + .INPUTS + None. You cannot pipe objects to New-TodoList. + + .OUTPUTS + None. New-TodoList creates a new system resource, i.e. a database file. + + .EXAMPLE + PS C:\> New-TodoList + Create a new TODO list for the active user account. + + .EXAMPLE + PS C:\> New-TodoList -User "Mazawa Shinonome" + Create a new TODO list for a specific user. + #> + [Alias("ntodo")] + [CmdletBinding()] + param( + [Parameter()] + [string] $User = [Environment]::UserName + ) + + begin { + $SavePath = Get-SavePath + New-Item -ItemType Directory -Path $SavePath -Force | Out-Null + $DatabasePath = [Path]::Combine($SavePath, "${User}.db") + + $PrivateFolder = [Path]::Combine($(Split-Path -Parent $PSScriptRoot), "Private") + + $Connection = [SQLiteConnection]::new() + $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" + $Connection.Open() + } + process { + $Sql = $Connection.CreateCommand() + $Sql.CommandText = Get-Content $([Path]::Combine($PrivateFolder, "TodoList.sql")) + + try { + $Sql.ExecuteNonQuery() | Out-Null + } catch { + Write-Error $DatabaseConnectionErrorMessage -Category ConnectionError -ErrorAction Stop + } + finally { + $Sql.Dispose() + } + } + clean { + $Connection.Close() + } +} diff --git a/src/Public/Remove-Task.ps1 b/src/Public/Remove-Task.ps1 new file mode 100644 index 0000000..ea92339 --- /dev/null +++ b/src/Public/Remove-Task.ps1 @@ -0,0 +1,74 @@ +using namespace System +using namespace System.Data.SQLite +using namespace System.IO + +function Remove-Task { + <# + .SYNOPSIS + Remove a task from a TODO list. + + .DESCRIPTION + Remove a task from a TODO list by Id. + + .PARAMETER Id + Defines the ID of a task that is to be removed. + + .PARAMETER User + Each TODO list is accociated to a user account. The default user account is read from the username environment variable. Specify a value for this parameter to access an another TODO list from a different user. + + .INPUTS + You can pipe Task objects to Remove-Task. + + .OUTPUTS + None. + + .EXAMPLE + PS C:\> Remove-Task 23 + Remove a task whose Id equals 23. + + .EXAMPLE + PS C:\> Get-TodoList -All | where Status -eq 'Done' | Remove-Task -WhatIf + Remove all tasks from the current user's TODO list that were marked as done. + #> + [Alias("rtask")] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Position = 0, Mandatory, ValueFromPipelineByPropertyName)] + [int[]] $Id, + + [Parameter()] + [string] $User = [Environment]::UserName + ) + + begin { + $SavePath = Get-SavePath + $DatabasePath = [Path]::Combine($SavePath, "${User}.db") + + if (!(Test-Path $DatabasePath)) { + Write-Error $DatabaseDoesNotExistErrorMessage -Category ObjectNotFound -ErrorAction Stop + } + + $Connection = [SQLiteConnection]::new() + $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" + $Connection.Open() + } + process { + foreach ($i in $Id) { + $Sql = $Connection.CreateCommand() + $Sql.CommandText = "DELETE FROM TodoList WHERE Id = ${i}" + + if ($PSCmdlet.ShouldProcess($Sql.CommandText)) { + try { + $Sql.ExecuteNonQuery() | Out-Null + } catch { + Write-Error $DatabaseConnectionErrorMessage -Category ConnectionError -ErrorAction Stop + } finally { + $Sql.Dispose() + } + } + } + } + clean { + $Connection.Close() + } +} diff --git a/src/Public/Remove-TodoList.ps1 b/src/Public/Remove-TodoList.ps1 new file mode 100644 index 0000000..187b3a2 --- /dev/null +++ b/src/Public/Remove-TodoList.ps1 @@ -0,0 +1,56 @@ +using namespace System +using namespace System.IO + +function Remove-TodoList { + <# + .SYNOPSIS + Deletes a TODO list database. + + .DESCRIPTION + Deletes a TODO list database. + + .PARAMETER User + Each TODO list is associated to a user account. The default user account + is read from the username environment variable. Specify a value for this + parameter to access an another TODO list from a different user. + + .INPUTS + None. You cannot pipe objects to Remove-TodoList. + + .OUTPUTS + None. + + .EXAMPLE + PS C:\> Remove-TodoList + Remove the default TODO list. + + .EXAMPLE + PS C:\> Remove-TodoList -User "Stefan Greve" + Remove the TODO list for a specific user. + + .EXAMPLE + PS C:\> Get-TodoList | where Status -eq 'Discarded' | Remove-Task -WhatIf + Dry-run mass removal of all discarded tasks. + #> + [Alias("rtodo")] + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] + param( + [Parameter()] + [string] $User = [Environment]::UserName + ) + + begin { + $SavePath = Get-SavePath + $DatabasePath = [Path]::Combine($SavePath, "${User}.db") + + if (!(Test-Path $DatabasePath)) { + Write-Error $DatabaseDoesNotExistErrorMessage -Category ObjectNotFound -ErrorAction Stop + } + } + process { + if ($PSCmdlet.ShouldProcess($DatabasePath)) { + Remove-Item $DatabasePath + } + } + clean {} +} diff --git a/src/Public/Update-Task.ps1 b/src/Public/Update-Task.ps1 new file mode 100644 index 0000000..a4f711e --- /dev/null +++ b/src/Public/Update-Task.ps1 @@ -0,0 +1,135 @@ +using namespace System +using namespace System.Collections.Generic +using namespace System.Data.SQLite +using namespace System.IO + +function Update-Task { + <# + .SYNOPSIS + Update one or more properties of a specific task. + + .DESCRIPTION + Adds a new task to a TODO list by Id. It is possible to manage multiple + TODO lists in separate databases at once. + + .PARAMETER Id + Defines the ID of a task that is to be updated. + + .PARAMETER Description + Sets the description of this task. + + .PARAMETER DueDate + Sets the due date for this task. + + .PARAMETER Priority + Sets the perceived priority to this task. + + .PARAMETER Project + Associates this task with a project (group). + + .PARAMETER Status + Sets the current status to this task. + + .PARAMETER User + Each TODO list is associated to a user account. The default user account + is read from the username environment variable. Specify a value for this + parameter to access an another TODO list from a different user. + + .INPUTS + You can pipe Task objects to Update-Task. + + .OUTPUTS + None. + + .EXAMPLE + PS C:\> Update-Task 1 -Status Done + Mark the first task as done. + + .EXAMPLE + PS C:\> Update-Task -Id 42 -Priority High -Status InProgress + Update the priority of task 42 to high and change its current status to + in-progress. + + .EXAMPLE + PS C:\> Get-TodoList | ? { $(Get-Date) -gt $_.DueDate -and $_.Status -ne 'Done' } | Update-Task -Status Discarded + Search all overdue task records that were never completed and update their status to discarded + #> + [Alias("utask")] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Position = 0, Mandatory, ValueFromPipelineByPropertyName)] + [int[]] $Id, + + [Parameter()] + [string] $Project, + + [Parameter()] + [string] $Description, + + [Parameter()] + [ValidateSet("High", "Medium", "Low")] + [string] $Priority, + + [Parameter()] + [ValidateSet("TODO", "Idea", "Planning", "InProgress", "Testing", "InReview", "Done", "Discarded", "Blocked")] + [string] $Status, + + [Parameter()] + [DateTime] $DueDate, + + [Parameter()] + [string] $User = [Environment]::UserName + ) + + begin { + $SavePath = Get-SavePath + $DatabasePath = [Path]::Combine($SavePath, "${User}.db") + + if (!(Test-Path $DatabasePath)) { + Write-Error $DatabaseDoesNotExistErrorMessage -Category ObjectNotFound -ErrorAction Stop + } + + $Connection = [SQLiteConnection]::new() + $Connection.ConnectionString = "DATA SOURCE=${DatabasePath}" + $Connection.Open() + } + process { + foreach ($i in $Id) { + $Sql = $Connection.CreateCommand() + $QueryBuilder = [List[string]]::new() + $QueryBuilder.Add("UPDATE TodoList SET ") + + if ($Project) { + $QueryBuilder.Add("Project='${Project}'$(($Description -or $Priority -or $Status -or $DueDate) ? "," : [string]::Empty)") + } + if ($Description) { + $QueryBuilder.Add("Description='${Description}'$(($Priority -or $Status -or $DueDate) ? "," : [string]::Empty)") + } + if ($Priority) { + $QueryBuilder.Add("Priority='${Priority}'$(($Status -or $DueDate)? "," : [string]::Empty)") + } + if ($Status) { + $QueryBuilder.Add("Status='${Status}'$(($DueDate) ? "," : [string]::Empty)") + } + if ($DueDate) { + $QueryBuilder.Add("DueDate='$($DueDate.ToString("yyyy-MM-dd HH:mm:ss.fffffff"))'") + } + + $QueryBuilder.Add(" WHERE Id=${i}") + $Sql.CommandText = $QueryBuilder -Join '' + + if ($PSCmdlet.ShouldProcess($Sql.CommandText)) { + try { + $Sql.ExecuteNonQuery() | Out-Null + } catch { + Write-Error $DatabaseConnectionErrorMessage -Category ConnectionError -ErrorAction Stop + } finally { + $Sql.Dispose() + } + } + } + } + clean { + $Connection.Close() + } +} diff --git a/src/Scripts/ArgumentCompleters.ps1 b/src/Scripts/ArgumentCompleters.ps1 new file mode 100644 index 0000000..4e32e7b --- /dev/null +++ b/src/Scripts/ArgumentCompleters.ps1 @@ -0,0 +1,50 @@ +using namespace System +using namespace System.IO + +$ModuleName = "Todo" + +#region User Completer + +$UserCompleterCommands = @( + "Get-Task" + "Get-TodoList" + "New-Task" + "New-TodoList" + "Remove-Task" + "Remove-TodoList" + "Update-Task" +) + +$RegisterUserParameter = { + param($Command, $Parameter, $WordToComplete, $CommandAst, $FakeBoundParameters) + + $SavePath = [Path]::Combine([Environment]::GetFolderPath("ApplicationData"), $ModuleName) + + Get-ChildItem -Path $SavePath -Filter "*.db" | Where-Object { $_ -like "$WordToComplete*" } +} + +$UserCompleterCommands | ForEach-Object { + Register-ArgumentCompleter -CommandName $_ -ParameterName User -ScriptBlock $RegisterUserParameter +} + +#endregion + +#region Project Completer + +$ProjectCompleterCommands = @( + "New-Task" + "Update-Task" +) + +$RegisterProjectParameter = { + param($Command, $Parameter, $WordToComplete, $CommandAst, $FakeBoundParameters) + + $Projects = Get-TodoList | Select-Object -Property Project -Unique + $Projects | Where-Object { $_ -like "$WordToComplete*" } +} + +$ProjectCompleterCommands | ForEach-Object { + Register-ArgumentCompleter -CommandName $_ -ParameterName Project -ScriptBlock $RegisterProjectParameter +} + +#endregion diff --git a/src/Todo.psd1 b/src/Todo.psd1 new file mode 100644 index 0000000..179085f --- /dev/null +++ b/src/Todo.psd1 @@ -0,0 +1,139 @@ +# +# Module manifest for module 'Todo' +# +# Generated by: Stefan Greve +# +# Generated on: 12/1/2024 +# + +@{ + +# Script module or binary module file associated with this manifest. +RootModule = 'Todo.psm1' + +# Version number of this module. +ModuleVersion = '0.0.0' + +# Supported PSEditions +# CompatiblePSEditions = @() + +# ID used to uniquely identify this module +GUID = '1005fb56-c909-4fd8-87db-0d6d57de726c' + +# Author of this module +Author = 'Stefan Greve' + +# Company or vendor of this module +CompanyName = 'Advanced Systems' + +# Copyright statement for this module +Copyright = '(c) 2024 Advanced Systems. All rights reserved.' + +# Description of the functionality provided by this module +Description = 'PowerShell Module to manage your TODO list from the terminal.' + +# Minimum version of the PowerShell engine required by this module +PowerShellVersion = '7.4' + +# Name of the PowerShell host required by this module +# PowerShellHostName = '' + +# Minimum version of the PowerShell host required by this module +# PowerShellHostVersion = '' + +# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# DotNetFrameworkVersion = '' + +# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# ClrVersion = '' + +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' + +# Modules that must be imported into the global environment prior to importing this module +RequiredModules = @('SQLite') + +# Assemblies that must be loaded prior to importing this module +# RequiredAssemblies = @() + +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +ScriptsToProcess = 'Scripts\ArgumentCompleters.ps1' + +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() + +# Format files (.ps1xml) to be loaded when importing this module +FormatsToProcess = 'Formats\Task.ps1xml' + +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +# NestedModules = @() + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = 'Get-Task', 'Get-TodoList', 'New-Task', 'New-TodoList', 'Remove-Task', + 'Remove-TodoList', 'Update-Task' + +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @() + +# Variables to export from this module +# VariablesToExport = @() + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = @() + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +FileList = 'Todo.psd1', 'Todo.psm1', 'Classes\Task.ps1', 'Formats\Task.ps1xml', + 'Private\Get-SavePath.ps1', 'Private\TodoList.sql', + 'Private\Variables.ps1', 'Public\Get-Task.ps1', + 'Public\Get-TodoList.ps1', 'Public\New-Task.ps1', + 'Public\New-TodoList.ps1', 'Public\Remove-Task.ps1', + 'Public\Remove-TodoList.ps1', 'Public\Update-Task.ps1', + 'Scripts\ArgumentCompleters.ps1' + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + Tags = 'PSEdition_Core','Windows','MacOS','Linux' + + # A URL to the license for this module. + LicenseUri = 'https://github.com/Advanced-Systems/todo/blob/master/LICENSE.md' + + # A URL to the main website for this project. + ProjectUri = 'https://github.com/Advanced-Systems/todo' + + # A URL to an icon representing this module. + IconUri = 'https://raw.githubusercontent.com/Advanced-Systems/assets/refs/heads/master/logos/png/adv-logo_85x85.png' + + # ReleaseNotes of this module + ReleaseNotes = 'https://github.com/Advanced-Systems/todo/blob/master/CHANGELOG.md' + + # Prerelease string of this module + # Prerelease = '' + + # Flag to indicate whether the module requires explicit user acceptance for install/update/save + # RequireLicenseAcceptance = $false + + # External dependent modules of this module + # ExternalModuleDependencies = @() + + } # End of PSData hashtable + + } # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} + diff --git a/src/Todo.psm1 b/src/Todo.psm1 new file mode 100644 index 0000000..369b5c0 --- /dev/null +++ b/src/Todo.psm1 @@ -0,0 +1,74 @@ +using namespace System +using namespace System.Management.Automation + +$IsDebugMode = $MyInvocation.MyCommand.Path -like "*src*" + +#region Export Functions and Classes + +$Classes = @(Get-ChildItem -Path "${PSScriptRoot}\Classes\*.ps1" -ErrorAction SilentlyContinue) +$Private = @(Get-ChildItem -Path "${PSScriptRoot}\Private\*.ps1" -ErrorAction SilentlyContinue) +$Public = @(Get-ChildItem -Path "${PSScriptRoot}\Public\*.ps1" -ErrorAction SilentlyContinue) + +foreach ($Import in @($Classes + $Private + $Public)) { + try { + $File = $Import.FullName + . $File + + if (!$IsDebugMode) { continue } + + Write-Host "[ OK ] " -ForegroundColor Green -NoNewline + Write-Host "Importing ${File}" + } + catch { + Write-Host "[ ER ] " -ForegroundColor Red -NoNewline + Write-Host "Failed to import file ${File}: $_" + } +} + +Export-ModuleMember -Function $Public.BaseName -Cmdlet * -Alias * + +#endregion + +#region Exporting Classes with Type Accelerators + +$ExportableTypes =@( + [Task] +) + +$TypeAcceleratorsClass = [PSObject].Assembly.GetType( + "System.Management.Automation.TypeAccelerators" +) + +# Ensure none of the types would clobber an existing type accelerator. +# If a type accelerator with the same name exists, throw an exception. +$ExistingTypeAccelerators = $TypeAcceleratorsClass::Get + +foreach ($Type in $ExportableTypes) { + if ($Type.FullName -in $ExistingTypeAccelerators.Keys) { + $Message = @( + "Unable to register type accelerator `"$($Type.FullName)`"" + "Accelerator already exists." + ) -join " - " + + throw [ErrorRecord]::new( + [InvalidOperationException]::new($Message), + "TypeAcceleratorAlreadyExists", + [ErrorCategory]::InvalidOperation, + $Type.FullName + ) + } +} + +# Add type accelerators for every exportable type. +foreach ($Type in $ExportableTypes) { + $null = $TypeAcceleratorsClass::Add($Type.FullName, $Type) +} + +# Remove type accelerators when the module is removed. +$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = { + foreach ($Type in $ExportableTypes) { + $null = $TypeAcceleratorsClass::Remove($Type.FullName) + } +}.GetNewClosure() + +#endregion diff --git a/tests/module.tests.ps1 b/tests/module.tests.ps1 new file mode 100644 index 0000000..dd51578 --- /dev/null +++ b/tests/module.tests.ps1 @@ -0,0 +1,32 @@ +using namespace System.IO + +param( + [string] $ModuleName = "Todo", + + [string] $Version, + + [switch] $Build +) + +$ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path +$ProjectRoot = $(Get-Item $([Path]::Combine($ScriptPath, ".."))).FullName + +if ($Build.IsPresent) { + & $([Path]::Combine($ProjectRoot, "Scripts", "build.ps1")) -Version $Version +} + +Import-Module -Name $([Path]::Combine($ProjectRoot, "src", "${ModuleName}.psd1")) ` + -ErrorAction Stop ` + -PassThru + +#region Unit Tests + +Describe "Foo" { + Context "Bar" { + It "Should pass" { + $true | Should -Be $true -Because "it is true" + } + } +} + +#endregion From 44fbdd4afd6c7d6224097022d7e0003acbe6ca93 Mon Sep 17 00:00:00 2001 From: StefanGreve Date: Sun, 1 Dec 2024 21:03:57 +0100 Subject: [PATCH 3/4] Configure workflow for testing and publishing this module --- .github/workflows/publish-module.yml | 35 ++++++++++++++++++++++++++++ .github/workflows/unit-tests.yml | 29 +++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 .github/workflows/publish-module.yml create mode 100644 .github/workflows/unit-tests.yml diff --git a/.github/workflows/publish-module.yml b/.github/workflows/publish-module.yml new file mode 100644 index 0000000..cb65861 --- /dev/null +++ b/.github/workflows/publish-module.yml @@ -0,0 +1,35 @@ +name: Publish Module + +on: + workflow_dispatch: + inputs: + version: + description: "Version Number" + required: true + +env: + API_KEY: ${{ secrets.PSGALLERY_API_TOKEN }} + RELEASE_VERSION: ${{ github.event.inputs.version }} + +jobs: + deploy: + name: Deployment + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Build Dependencies + shell: pwsh + run: | + Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted + Install-Module PSScriptAnalyzer + Install-Module SQLite + + - name: Publish Module + shell: pwsh + run: | + pwsh -NoProfile -ExecutionPolicy ByPass -File "./scripts/publish.ps1" ` + -Version ${{ env.RELEASE_VERSION }} ` + -ApiKey ${{ env.API_KEY }} ` + -Confirm:$false diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml new file mode 100644 index 0000000..77157d2 --- /dev/null +++ b/.github/workflows/unit-tests.yml @@ -0,0 +1,29 @@ +name: Unit Test +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ ubuntu-latest, macOS-latest, windows-latest ] + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Build Dependencies + shell: pwsh + run: | + Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted + Install-Module PSScriptAnalyzer + Install-Module SQLite + + - name: Run Unit Tests + shell: pwsh + run: | + pwsh -NoProfile -ExecutionPolicy ByPass -File ./scripts/test.ps1 -Build From 1268663c4078e1280d698d05b5b6be68db3fcb1b Mon Sep 17 00:00:00 2001 From: StefanGreve Date: Sun, 1 Dec 2024 21:17:32 +0100 Subject: [PATCH 4/4] Refactor scripts --- scripts/build.ps1 | 6 +++--- scripts/publish.ps1 | 5 +---- scripts/test.ps1 | 3 +-- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/scripts/build.ps1 b/scripts/build.ps1 index 6e1eb20..3c71b90 100644 --- a/scripts/build.ps1 +++ b/scripts/build.ps1 @@ -8,12 +8,12 @@ param( ) begin { - $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path - $ProjectRoot = $(Get-Item $([Path]::Combine($ScriptPath, ".."))).FullName - Push-Location $([Path]::Combine($ProjectRoot, "src")) + $ProjectRoot = Split-Path -Path $PSScriptRoot -Parent $Steps = 5 $ManifestPath = "${ModuleName}.psd1" + + Push-Location $([Path]::Combine($ProjectRoot, "src")) } process { #region Step 1 - Install Dependencies diff --git a/scripts/publish.ps1 b/scripts/publish.ps1 index ccde428..c93af60 100644 --- a/scripts/publish.ps1 +++ b/scripts/publish.ps1 @@ -1,5 +1,3 @@ -using namespace System.IO - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "High")] param( [string] $ModuleName = "Todo", @@ -13,9 +11,8 @@ param( begin { $ManifestPath = "${ModuleName}.psd1" + $ProjectRoot = Split-Path -Path $PSScriptRoot -Parent - $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path - $ProjectRoot = $(Get-Item $([Path]::Combine($ScriptPath, ".."))).FullName Push-Location $ProjectRoot } process { diff --git a/scripts/test.ps1 b/scripts/test.ps1 index c14744b..710ec46 100644 --- a/scripts/test.ps1 +++ b/scripts/test.ps1 @@ -7,8 +7,7 @@ param( ) begin { - $ScriptPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path - $ProjectRoot = $(Get-Item $([Path]::Combine($ScriptPath, ".."))).FullName + $ProjectRoot = Split-Path -Path $PSScriptRoot -Parent } process { if (!$(Get-Module SQLite -ListAvailable)) {