diff options
author | Clemens Fries <github-clockrotz@xenoworld.de> | 2016-11-01 17:11:58 +0100 |
---|---|---|
committer | Clemens Fries <github-clockrotz@xenoworld.de> | 2016-11-01 17:11:58 +0100 |
commit | 533681e0f83ec4f69b3b8e9f1982ed9f089285b4 (patch) | |
tree | 4792c3b3e6b353798f8564ff90d6572081755e1f |
Initial commit
-rw-r--r-- | .gitignore | 4 | ||||
-rw-r--r-- | Godeps/Godeps.json | 34 | ||||
-rw-r--r-- | Godeps/Readme | 5 | ||||
-rw-r--r-- | LICENSE | 674 | ||||
-rw-r--r-- | README.asciidoc | 469 | ||||
-rw-r--r-- | clockrotz.go | 197 | ||||
-rw-r--r-- | clockrotz_test.go | 34 | ||||
-rw-r--r-- | cmd/check.go | 131 | ||||
-rw-r--r-- | cmd/create.go | 212 | ||||
-rw-r--r-- | cmd/create_test.go | 41 | ||||
-rw-r--r-- | cmd/debug.go | 73 | ||||
-rw-r--r-- | cmd/next.go | 91 | ||||
-rw-r--r-- | cmd/run.go | 316 | ||||
-rw-r--r-- | cmd/run_test.go | 39 | ||||
-rw-r--r-- | common/configuration.go | 142 | ||||
-rw-r--r-- | common/configuration_test.go | 105 | ||||
-rw-r--r-- | common/consts.go | 49 | ||||
-rw-r--r-- | common/message.go | 231 | ||||
-rw-r--r-- | common/message_test.go | 82 | ||||
-rw-r--r-- | common/util.go | 63 | ||||
-rw-r--r-- | common/util_test.go | 79 | ||||
-rw-r--r-- | testdata/config.ini | 5 | ||||
-rw-r--r-- | testdata/todo/2061.msg | 8 | ||||
-rw-r--r-- | testdata/todo/2134.msg | 11 |
24 files changed, 3095 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b3702a0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +clockrotz +clockrotz.iml +README.html +.idea diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json new file mode 100644 index 0000000..437070f --- /dev/null +++ b/Godeps/Godeps.json @@ -0,0 +1,34 @@ +{ + "ImportPath": "github.com/githubert/clockrotz", + "GoVersion": "go1.5.4", + "Deps": [ + { + "ImportPath": "github.com/davecgh/go-spew/spew", + "Rev": "5215b55f46b2b919f50a1df0eaa5886afe4e3b3d" + }, + { + "ImportPath": "github.com/docopt/docopt.go", + "Comment": "0.6.2", + "Rev": "784ddc588536785e7299f7272f39101f7faccc3f" + }, + { + "ImportPath": "github.com/go-ini/ini", + "Comment": "v1.11.0", + "Rev": "12f418cc7edc5a618a51407b7ac1f1f512139df3" + }, + { + "ImportPath": "github.com/jordan-wright/email", + "Comment": "v2.2-9-gfd70310", + "Rev": "fd703108daeb23d77c124d12978e9b6c4f28f034" + }, + { + "ImportPath": "github.com/pmezard/go-difflib/difflib", + "Rev": "792786c7400a136282c1664665ae0a8db921c6c2" + }, + { + "ImportPath": "github.com/stretchr/testify/assert", + "Comment": "v1.1.3-16-g6cb3b85", + "Rev": "6cb3b85ef5a0efef77caef88363ec4d4b5c0976d" + } + ] +} diff --git a/Godeps/Readme b/Godeps/Readme new file mode 100644 index 0000000..4cdaa53 --- /dev/null +++ b/Godeps/Readme @@ -0,0 +1,5 @@ +This directory tree is generated automatically by godep. + +Please do not edit. + +See https://github.com/tools/godep for more information. @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 <http://www.gnu.org/licenses/>. + +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: + + <program> Copyright (C) <year> <name of author> + 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 +<http://www.gnu.org/licenses/>. + + 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 +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/README.asciidoc b/README.asciidoc new file mode 100644 index 0000000..8c344fa --- /dev/null +++ b/README.asciidoc @@ -0,0 +1,469 @@ += Clockrotz +Clemens Fries <github-clockrotz@xenoworld.de> +:source-highlighter: pygments +:toc: left +:clockrotz-ini: clockrotz.ini +:clockrotz-base: clockrotz +:version: 0.0.1 + +Clockrotz v{version} — a simple email notification helper. + +IMPORTANT: This program is in development and might have some rough edges. The +documentation on `master` should still accurately reflect the current state of +the program. + +== What is `clockrotz`? + +`clockrotz` is a “note to my future self” email notification tool. You write a +simple text file, with some metadata, and it will, upon invocation, send a +message when the time has come. + +.Example message +---- +to: me@example.com +subject: Watch Halley's Comet +date: 2061-07-28 + +Greetings! + +Go outside at night, if the curfew of the – highly welcomed — alien overlords +permits, and watch Halley's Comet. +---- + +=== Motivation + +I needed a fairly simple tool to send some one-off reminders to myself, and +possibly to others. Plus, I wanted the messages to live in my home directory, +so I would not forget them if I move to another server. You could realize +most of this with `atd`, but it is a bit clumsy if want to quickly write a +message, plus I'd totally forget to copy `/var/spool/at`. + +`clockrotz` is not meant to be a daemon. It should be executed regularly by a +cron job or other method. For the `date` parameter it also supports having a +specific time, which acts as a “not before” constraint. If you run your cron +job often enough (for example: every five minutes) the message will, of course, +be sent very close to the given time. + + +== Quick Start + +=== Building + +In order to check out and build the project in its own directory in `/tmp`, +write the following: + +[source,shell] +---- +cd $(mktemp -d) +export GOPATH=$PWD +git clone http://github.com/githubert/clockrotz src/github.com/githubert/clockrotz +cd src/github.com/githubert/clockrotz +godep get +go build +---- + +=== Running + +Create `.config/{clockrotz-ini}`: +[source,ini] +---- +[default] +server = smtp.example.com +user = me +password = aengeequ6xeiseoY +from = me@example.com +---- + +Create a new message: +---- +clockrotz create --to me@example.com +---- + +Add a cron job: +---- +0 6 * * * /path/to/clockrotz run +---- + +List messages due in the next days: +---- +clockrotz next +---- + +Run manually: +---- +clockrotz run +---- + +== Quick Start Walkthrough + +Create a file `.config/{clockrotz-ini}` and provide a server, credentials and a +from address: + +[source,ini] +---- +[default] +server = smtp.example.com +user = me +password = aengeequ6xeiseoY +from = me@example.com +---- + +NOTE: `port` defaults to `587`. If it doesn't work, try setting `port` to +`25`. + +Now ready some message to yourself: + +---- +clockrotz create --to me@example.com +---- + +This will open a new file using the editor set in the `VISUAL` environment +variable, or if no editor is set, it will default to `vi`. + +Fill in `date` in the format `YYYY-mm-dd` (for example `date: 2016-01-01`) and +add a meaningful `subject`. Add a blank line between the configuration in the +header and your message's body. + +Save and exit the editor. `clockrotz` will ask you what to do. Press `ENTER` to +save the message to the `{clockrotz-base}/todo` folder. + +If you set `date` to today's date you can test if everything works. First check +if everything is okay by running `clockrotz check`, if it reports no errors, +you can see with `clockrotz next` if the message is scheduled for being sent +out in the next seven days. + +Finally, if you type `clockrotz run`, it will deliver all messages that were +due. + +As `clockrotz` is not a daemon, you should run it daily by adding it as a cron +job. + +Type `crontab -e` and add a entry to run the command every day at 6 in the +morning: + +---- +0 6 * * * /path/to/clockrotz run +---- + +== Folder structure + +The default working directory is `clockrotz`, located in the user's home +directory. There are several folders created beneath it, when the program +is invoked. + +---- +clockrotz/ + todo/ + done/ + errors/ + drafts/ +---- + +`todo/` is the message queue. All `.msg` files in that folder are considered +when running `clockrotz run`. + +`done/` contains all messages that were successfully delivered. For every +message there is also a corresponding `.log` file. + +`errors/` contains all messages that could not be delivered. For every message +there is also a corresponding `.log` file. + +`drafts/` contains messages that can be used with `clockrotz create --draft +FILENAME`. Additionally, messages in this folder will also be checked with +`clockrotz check`. + +== Global Settings File `.config/{clockrotz-ini}` + +Global settings can be put into the optional file `.config/{clockrotz-ini}`. + +All _global_ settings can also be overridden on the command line. + +`.config/{clockrotz-ini}` is a simple ini-style settings file with a `default` +section, plus optional sections for every command, in order to overrule the +settings in the `default` section. + +.Example file +[source,ini] +---- +[default] +workdir = ~/clockrotz +server = smtp.example.com +port = 587 +from = me@example.com + +[run] +bcc = me@example.com +---- + +=== Settings + +NOTE: Empty values are valid and mean that a setting has been un-set. + +==== Global and Command Line + +workdir:: The working directory, defaults to `~/clockrotz`. +server:: Address of the SMTP server. Defaults to `localhost`. +port:: Port of the SMTP server. Defaults to the SMTP submission port `587`. +not-before:: Do not sent messages before the specified time. (`00:00` until `not-before`) +not-after:: Do not sent messages after the specified time. (`not-after` until `23:59`) + +TODO: not-after / not-before warrant some better explanation + +Priority of these is as follows `command line > global`. + +==== Global, Command Line and as Configuration + +These parameters are valid everywhere and may also be included in the +configuration part of a message. + +NOTE: `date` is not allowed anywhere except in the message configuration. + +from:: `from` as in <<Configuration>> +to:: `to` as in <<Configuration>> +cc:: `cc` as in <<Configuration>> +bcc:: `bcc` as in <<Configuration>> +subject:: `subject` as in <<Configuration>> +reply-to:: `reply-to` as in <<Configuration>> + +Priority of these is as follows `configuration > command line > global`. + +== Message format + +Messages consist of two parts *separated by a single empty line*. The first part +is the configuration and the second part is the actual message. + +.Example message +---- +to: cryogenics-department@example.com +from: me-bot@example.com +cc: me@example.com +subject: Unfreeze Clemens +date: 2134-01-01 + +Dear Cryogenics Department, + +please unfreeze Clemens, as he wanted to watch this year's close pass of +Halley's Comet. This one is going to have an apparent magnitude of -2.0 — it's +gonna be fun, so feel free to join him! +---- + + +[[Configuration]] +=== Configuration + +The following parameters are permitted, everything else is going to be ignored. + +==== Required parameters + +NOTE: Except for `date`, other required parameters may be specified outside the +message configuration, either on the command line or in the ini-file. + +date:: The "not before" date. This may either be a simple date in the format +`YYYY-mm-dd`, which will be interpreted as `YYYY-mm-dd 00:00`, or a date with a +time in the form of `YYYY-mm-dd HH:MM`. + +to:: A single address to where the message will be sent. It may either be a +simple email address such as `foo@example.net` or an address including a +name such as `Foo bar <foo@example.net>`. + +subject:: A short subject. + +from:: Same format as `to`. + +==== Optional parameters + +cc:: Same format as `to`, but multiple comma-separated entries are allowed, +works like `Cc` in email. + +bcc:: Same format as `to`, but multiple comma-separated entries are allowed, +works like `Bcc` in email. + +reply-to:: Same format as `to`, works like `Reply-To` in email. + +=== Message Body + +Simple, plain text. It is assumed to be in UTF-8, though. + +== Writing a New Message + +Either edit a file, directly in `{clockrotz-base}/todo`, or use the command line tool +to initialize an empty message and start your favourite editor. The file name +must end in `.msg`, otherwise it will be ignored. + +.Using the command line tool +---- +$ clockrotz create --to "foo@example.com" +---- + +== Command Line Options + +Use `--help` after any command to get the full help message shown. + +---- +include::clockrotz.go[tag=main] +---- + +=== `next` command + +---- +include::cmd/next.go[tag=next] +---- + +This will show which messages are going to be sent within the next 7 days. Use +the `--days` parameter to change how many days in advance are processed. If you +use the `--all` parameter, all pending messages will be listed. +The format is simply `date subject (filename)`. + +---- +$ clockrotz next --all +Showing all messages. + +2061-07-28 00:00 Watch Halley's Comet (halley.msg) +2134-01-01 00:00 Unfreeze Clemens (unfreeze.msg) +---- + + +=== `run` command + +---- +include::cmd/run.go[tag=run] +---- + +This will send out all pending messages. There will be no output, unless there +were errors. Any message that could not be sent will be moved to the `errors` +folder, and a corresponding `.log`-file will be created with all available +information; additionally, the program will start to complain at every +invocation that there were messages with errors. Messages that were delivered +successfully are moved to the `done` folder and a corresponding `.log`-file is +created there, too. + + +=== `create` command + +---- +include::cmd/create.go[tag=create] +---- + +The `create` command will assist you in creating a new message. It will open a +new file for you, filled in with any parameters you provided on the command +line. If you provide a file name through the `--draft` parameter, it will +create a new file based on the given file name in the `drafts` folder. + +---- +clockrotz create --to foo@example.com --subject "Something" +---- + +It will use the editor configured in `$VISUAL` or `$EDITOR` or `vi`, if the +former are empty. + +`date` will be set to tomorrow's date. + +---- +1 to: foo@example.com +2 subject: Something +3 date: 2016-01-01 +4 +5 Add message to the world of tomorrow here. +~ +~ +~ +~ + INSERT >> [No Name][+] <<< +-- INSERT -- +---- + +After editing it will ask you if you want to add the message to the `todo` +folder. + +---- +Save message? ([(y)es], (d)raft, (n)o): +---- + +Answering `n` or `no` will discard the message, answering `d` or `draft` will +add it to the `drafts` folder. If you type `y`, `yes`, or simply hit `ENTER` it +will be added to the `todo` folder. + + +=== `check` command + +---- +include::cmd/check.go[tag=check] +---- + +The `check` command will check all messages in the `todo` and `drafts` folder +and report any messages that can't be processed. Optionally a file name can be +provided to check only the given file. It will exit with a code of `0` if no +errors were found, otherwise with a code of `1`. + +NOTE: `--silent` will not suppress output of errors, such as problems loading a +file. + +---- +$ clockrotz check + +in drafts: + foo.msg: + missing the 'to' parameter + missing the 'subject' parameter + +in todo: + bar.msg: + 'date' parameter is invalid +---- + +=== `debug` command + +---- +include::cmd/debug.go[tag=debug] +---- + +The `debug` command will print out the effective configuration for a message, +plus the email message. This shows all settings as they are seen at that +point. Note that this also shows settings — such as `workdir` and `config` — +that cannot be overridden by the message. Please note that for the email +message there are several places, such as the `Message-Id`, that vary from +invocation to invocation as they are randomly generated. + +---- +$ clockrotz debug clockrotz/todo/2061.msg +Configuration +------------- +config: /home/me/.config/config.ini +date: 2061-07-28 +days: 7 +from: me@example.com +not-after: 23:59 +not-before: 00:00 +port: 578 +server: smtp.example.com +subject: Watch Halley's Comet +to: me@example.com +workdir: /home/me/clockrotz + +Email message +------------- +Content-Type: multipart/mixed; + boundary=8bb4fce665d20481a3b832ef74a12123edadb7b1bc4d5b505c93e9fbd9e2 +To: <me@example.com> +Subject: Watch Halley's Comet +Message-Id: <1464969109987565122.18908.793296386389602001@smtp.example.com> +From: me@example.com +Date: Fri, 03 Jun 2016 17:51:49 +0200 +Mime-Version: 1.0 + +--8bb4fce665d20481a3b832ef74a12123edadb7b1bc4d5b505c93e9fbd9e2 +Content-Type: multipart/alternative; + boundary=70b52bfb5fa8b90ebe2b3b9373f62436d412ae3e59bbfa20685dbc1bd6bc + +--70b52bfb5fa8b90ebe2b3b9373f62436d412ae3e59bbfa20685dbc1bd6bc +Content-Type: text/plain; charset=UTF-8 +Content-Transfer-Encoding: quoted-printable + +Greetings! + +Go outside at night, if the curfew of the – highly welcomed — alien overlords +permits, and watch Halley's Comet. +--70b52bfb5fa8b90ebe2b3b9373f62436d412ae3e59bbfa20685dbc1bd6bc-- + +--8bb4fce665d20481a3b832ef74a12123edadb7b1bc4d5b505c93e9fbd9e2-- +---- diff --git a/clockrotz.go b/clockrotz.go new file mode 100644 index 0000000..a88353a --- /dev/null +++ b/clockrotz.go @@ -0,0 +1,197 @@ +/* clockrotz.go: main program + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ + +package main + +import ( + "fmt" + "github.com/docopt/docopt.go" + "os" + "os/user" + "path/filepath" + "github.com/githubert/clockrotz/cmd" + . "github.com/githubert/clockrotz/common" +) + + +var usageMain = +// tag::main[] +` +Usage: + clockrotz [options] <command> [<args>...] + +Options: + --workdir=WORKDIR Working directory, defaults to $HOME/clockrotz + --config=CONFIG Use the given INI file instead of .config/clockrotz.ini + --help Show this help. + +The following commands are available: + next Show messages due in the next days. + check Check if a message is complete. + debug Print the effective configuration for a message, and the resulting + email message. + create Open a new message in an editor. + run Send out pending messages. +` // end::main[] + +var defaultConf = Configuration{ + Data: map[string]string{ + CONF_DAYS: "7", + CONF_SMTP_PORT: "587", + CONF_SMTP_SERVER: "localhost", + CONF_NOT_BEFORE: "00:00", + CONF_NOT_AFTER: "23:59", + }, +} + + +// Retrieve the user's home directory. +func userHome() string { + u, err := user.Current() + + // I don't think we can go on without finding the user's home directory + if err != nil { + panic(err) + } + + return u.HomeDir +} + +// Retrieve the user's config home, which is either defined through the environment variable +// `XDG_CONFIG_HOME` or is assumed to be a folder called `.config` in the user's home +// directory (as retrieved by `userHome()`). +func configHome() string { + value, present := os.LookupEnv("XDG_CONFIG_HOME") + + configHome := value + + if !present || value == "" || !filepath.IsAbs(value) { + configHome = filepath.Join(userHome(), ".config") + } + + return configHome +} + +// Expand `~/`, if the working directory begins with it. +func expandTilde(conf *Configuration) { + workdir := conf.Get(CONF_WORKDIR) + + if len(workdir) > 1 && workdir[0:2] == "~/" { + conf.Set(CONF_WORKDIR, filepath.Join(userHome(), workdir[2:])) + } else if len(workdir) == 1 && workdir == "~" { + conf.Set(CONF_WORKDIR, userHome()) + } +} + +// This will create all necessary folders in the working directory. +func createFolders(workdir string) error { + for _, dir := range []string{DIR_TODO, DIR_DONE, DIR_ERRORS, DIR_DRAFTS} { + err := os.MkdirAll(filepath.Join(workdir, dir), 0777) + + if err != nil { + return err + } + } + + return nil +} + +// Complain about files in DIR_ERRORS. +func alertIfErrors(workdir string) { + errorsDir := filepath.Join(workdir, DIR_ERRORS) + + count := 0 + + filepath.Walk(errorsDir, func(_ string, info os.FileInfo, _ error) error { + if info.Mode().IsRegular() { + count++ + } + + return nil + }) + + if count > 0 { + fmt.Println("There were failed messages.") + fmt.Printf("Please inspect the contents of the %s/ directory.\n", DIR_ERRORS) + } +} + +func main() { + userHome := userHome() + + // This is the configuration that will be cobbled together from the + // default configuration ('defaultConf'), the INI and the command line + // arguments. + sessionConf := NewConfiguration() + + sessionConf.MergeWith(&defaultConf) + + args, _ := docopt.Parse(usageMain, nil, true, "", true) + + // Determine configuration file name, defaults to `clockrotz.ini` in + // the user's config home (usually `.config`). + if args["--config"] != nil { + sessionConf.Set(CONF_CONFIG_FILENAME, args["--config"].(string)) + } else { + sessionConf.Set(CONF_CONFIG_FILENAME, filepath.Join(configHome(), "clockrotz.ini")) + } + + // Determine the desired command (run, next, ...) + command := args["<command>"].(string) + + // Load INI configuration. This will merge the '[default]' section with + // the optional section named after the desired command ('cmd'). + sessionConf.MergeWithIni(command) + + // Determine working directory, defaults to the folder `clockrotz` in + // the user's home directory. '--workdir' on the command line takes + // precedence over the 'workdir' in the INI. + if args["--workdir"] != nil { + sessionConf.Set(CONF_WORKDIR, args["--workdir"].(string)) + } else { + // If no working directory is set in the INI... + if sessionConf.Get(CONF_WORKDIR) == "" { + sessionConf.Set(CONF_WORKDIR, filepath.Join(userHome, "clockrotz")) + } + } + + // Expand the `~/` in workdir. + expandTilde(sessionConf) + + // Make sure that all necessary folders exist. + createFolders(sessionConf.Get(CONF_WORKDIR)) + + // See if there are files in DIR_ERRORS and alert the user. + alertIfErrors(sessionConf.Get(CONF_WORKDIR)) + + commandArgs := []string{command} + commandArgs = append(commandArgs, args["<args>"].([]string)...) + + switch command { + case "next": + cmd.Next(commandArgs, sessionConf) + case "create": + cmd.Create(commandArgs, sessionConf) + case "check": + cmd.Check(commandArgs, sessionConf) + case "run": + cmd.Run(commandArgs, sessionConf) + case "debug": + cmd.Debug(commandArgs, sessionConf) + } +}
\ No newline at end of file diff --git a/clockrotz_test.go b/clockrotz_test.go new file mode 100644 index 0000000..325438c --- /dev/null +++ b/clockrotz_test.go @@ -0,0 +1,34 @@ +package main + +import ( + "github.com/stretchr/testify/assert" + "testing" + . "github.com/githubert/clockrotz/common" +) + +func TestExpandTilde(t *testing.T) { + c := NewConfiguration() + + c.Set(CONF_WORKDIR, "/foo") + expandTilde(c) + assert.Equal(t, "/foo", c.Get(CONF_WORKDIR)) + + c.Set(CONF_WORKDIR, "~/foo") + expandTilde(c) + assert.Equal(t, userHome() + "/foo", c.Get(CONF_WORKDIR)) + + // Shortest possible + c.Set(CONF_WORKDIR, "~/") + expandTilde(c) + assert.Equal(t, userHome(), c.Get(CONF_WORKDIR)) + + // Single character workdir with only a tilde + c.Set(CONF_WORKDIR, "~") + expandTilde(c) + assert.Equal(t, userHome(), c.Get(CONF_WORKDIR)) + + // Ignored tilde + c.Set(CONF_WORKDIR, "~test") + expandTilde(c) + assert.Equal(t, "~test", c.Get(CONF_WORKDIR)) +}
\ No newline at end of file diff --git a/cmd/check.go b/cmd/check.go new file mode 100644 index 0000000..2b7316e --- /dev/null +++ b/cmd/check.go @@ -0,0 +1,131 @@ +/* check.go: check a given message for problems + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package cmd + +import ( + "fmt" + "github.com/docopt/docopt.go" + . "github.com/githubert/clockrotz/common" + "os" + "path/filepath" + "sort" +) + +var usageCheck = +// tag::check[] +` +Usage: + clockrotz check [--silent] [FILE] + +Options: + --silent Suppress output, useful for silent checks. + FILE Check only the given file. + +If no FILE is provided, check will inspect all messages in the todo/ and the +drafts/ folder. The command exit with a code of 0, if there were no problems. +` // end::check[] + +func Check(argv []string, conf *Configuration) { + args, _ := docopt.Parse(usageCheck, argv, true, "", false) + + silent := args["--silent"].(bool) + + ok := true + + if args["FILE"] != nil { + message, err := NewMessageFromFile(args["FILE"].(string)) + + if err != nil { + fmt.Printf("Error while reading message: %s\n", err.Error()) + os.Exit(1) + } + + message.Conf.MergeWith(conf) + ok = checkMessage(message, silent) + } else { + draftOk := checkFolder(DIR_DRAFTS, conf, silent) + + if !silent { + // A bit of space between the drafts/ and todo/ listing + fmt.Println() + } + + todoOk := checkFolder(DIR_TODO, conf, silent) + + ok = draftOk && todoOk + } + + if ok { + os.Exit(0) + } else { + os.Exit(1) + } +} + +// Inspect all messages in a folder. +func checkFolder(folder string, conf *Configuration, silent bool) bool { + messages := NewMessagesFromDirectory(filepath.Join(conf.Get(CONF_WORKDIR), folder)) + sort.Sort(Messages(messages)) + + if !silent { + fmt.Printf("in %s:\n", folder) + } + + ok := true + count := 0 + + for _, message := range messages { + count++ + message.Conf.MergeWith(conf) + + if !checkMessage(message, silent) { + ok = false + } + } + + if ok && !silent { + fmt.Printf(" All (%d) messages are valid.\n", count) + } + + return ok +} + +// Check the given message. If `silent` is false, all problems will be printed +// to stdout. +func checkMessage(message Message, silent bool) bool { + ok := true + errs := message.Verify() + + if errs != nil { + ok = false + } + + if silent { + return ok + } + + if !ok { + fmt.Printf(" %s:\n", message.Name) + + for _, err := range errs { + fmt.Printf(" %s\n", err.Error()) + } + } + + return ok +} diff --git a/cmd/create.go b/cmd/create.go new file mode 100644 index 0000000..3d02bc7 --- /dev/null +++ b/cmd/create.go @@ -0,0 +1,212 @@ +/* create.go: help creating a new message + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package cmd + +import ( + "bufio" + "fmt" + "github.com/docopt/docopt.go" + . "github.com/githubert/clockrotz/common" + "io/ioutil" + "os" + "os/exec" + "path/filepath" + "strings" + "time" +) + +var usageCreate = +// tag::create[] +` +Usage: + clockrotz create [--draft=FILE] [options] + +Options: + --help Show this help. + --to=ADDR Destination address. + --from=ADDR Sender address. + --subject=ADDR Short subject. + --cc=ADDR Set "Cc". + --bcc=ADDR Set "Bcc". + --reply-to=ADDR Set "Reply-To". + --draft=FILE Use FILE from the drafts/ folder as template. +` // end::create[] + +func Create(argv []string, conf *Configuration) { + args, _ := docopt.Parse(usageCreate, argv, true, "", false) + + tmpFile, err := ioutil.TempFile("", "clockrotz") + + if err != nil { + fmt.Printf("Error while creating temporary file: %s\n", err.Error()) + os.Exit(1) + } + + // We close the file right away, because we need only its soulless + // shell, mwhaha. + tmpFile.Close() + + draftsDir := filepath.Join(conf.Get(CONF_WORKDIR), DIR_DRAFTS) + todoDir := filepath.Join(conf.Get(CONF_WORKDIR), DIR_TODO) + + defer os.Remove(tmpFile.Name()) + + message := NewMessage() + + if args["--draft"] != nil { + draft := filepath.Join(draftsDir, args["--draft"].(string)) + m, err := NewMessageFromFile(draft) + + if err != nil { + fmt.Printf("Error while reading draft: %s\n", err.Error()) + os.Exit(1) + } + + message = &m + } + + message.Conf.MergeWithDocOptArgs(CMD_USAGE, &args) + + // MergeWithDocOptArgs will also copy --draft and --help over, but we do not want + // that. + delete(message.Conf.Data, "draft") + delete(message.Conf.Data, "help") + + if message.Get("date") == "" { + // Add tomorrow's date. + message.Conf.Set("date", time.Now().AddDate(0, 0, 1).Format(DATE_FORMAT)) + } + + if message.Get("subject") == "" { + message.Conf.Set("subject", "Type subject here") + } + + if len(message.Body) == 0 { + message.Body = append(message.Body, "Add message to the world of tomorrow here.") + } + + message.WriteToFile(tmpFile.Name()) + + editor := editor() + + fmt.Printf("Opening %s using %s.\n", tmpFile.Name(), editor) + + cmd := exec.Command(editor, tmpFile.Name()) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Run() + + if cmd.ProcessState.Success() { + fmt.Printf("\nSave message? ([(y)es], (d)raft, (n)o): ") + reader := bufio.NewReader(os.Stdin) + response, err := reader.ReadString('\n') + + if err != nil { + fmt.Printf("Error when reading response: %s\n", err.Error()) + os.Exit(1) + } + + var dst string + + saved := false + + response = strings.TrimSpace(response) + + switch response { + case "y", "yes", "": + dst = filepath.Join(todoDir, filepath.Base(tmpFile.Name())+".msg") + dst, err = copyFile(tmpFile.Name(), dst, false) + saved = true + case "d", "draft": + dst = filepath.Join(draftsDir, filepath.Base(tmpFile.Name())+".msg") + dst, err = copyFile(tmpFile.Name(), dst, false) + saved = true + } + + if err != nil { + fmt.Printf("Error when saving %s: %s\n", dst, err) + } else if saved { + fmt.Printf("Saved as: %s\n", dst) + } else { + fmt.Println("Discarding message.") + } + } +} + +// Copy file from `src` to `dst`. If `overwrite` is false, then an alternative +// file name will be used and returned as string. +// TODO: Portability issues (cp) / https://github.com/golang/go/issues/8868 +func copyFile(src, dst string, overwrite bool) (string, error) { + if !overwrite { + var err error + + dst, err = nextFreeFilename(dst) + + if err != nil { + return "", err + } + } + + err := exec.Command("cp", "-f", src, dst).Run() + + return dst, err +} + +func nextFreeFilename(dst string) (string, error) { + _, e := os.Stat(dst) + + // If the file does not exist, we can use the name + if os.IsNotExist(e) { + return dst, nil + } + + alt := "" + + for i := 0; i < 255; i++ { + name := fmt.Sprintf("%s.%d", dst, i) + _, e := os.Stat(name) + + if os.IsNotExist(e) { + alt = name + break + } + } + + if alt == "" { + return "", fmt.Errorf("No suitable file name could be found.") + } + + return alt, nil +} + +func editor() string { + editor := os.Getenv("VISUAL") + + if editor != "" { + return editor + } + + editor = os.Getenv("EDITOR") + + if editor != "" { + return editor + } + + return "vi" +} diff --git a/cmd/create_test.go b/cmd/create_test.go new file mode 100644 index 0000000..388ce36 --- /dev/null +++ b/cmd/create_test.go @@ -0,0 +1,41 @@ +/* create_test.go: unit tests for 'create' command + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package cmd + +import ( + "fmt" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "io/ioutil" + "os" + "path/filepath" + "testing" +) + +func TestEditor(t *testing.T) { + os.Setenv("VISUAL", "") + os.Setenv("EDITOR", "") + + assert.Equal(t, "vi", editor()) + + os.Setenv("EDITOR", "editor") + assert.Equal(t, "editor", editor()) + + os.Setenv("VISUAL", "visual") + assert.Equal(t, "visual", editor()) +}
\ No newline at end of file diff --git a/cmd/debug.go b/cmd/debug.go new file mode 100644 index 0000000..03f529b --- /dev/null +++ b/cmd/debug.go @@ -0,0 +1,73 @@ +/* debug.go: show debug information for a provided message + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package cmd + +import ( + "fmt" + "github.com/docopt/docopt.go" + . "github.com/githubert/clockrotz/common" + "os" +) + +var usageDebug = +// tag::debug[] +` +Usage: + clockrotz debug FILENAME + +Options: + --help Show this help. + FILENAME File name of the message to inspect. +` // end::debug[] + +func Debug(argv []string, conf *Configuration) { + args, _ := docopt.Parse(usageDebug, argv, true, "", false) + + message, err := NewMessageFromFile(args["FILENAME"].(string)) + + if err != nil { + fmt.Printf("Error while reading file: %s\n", err.Error()) + os.Exit(1) + } + + fmt.Println("Configuration\n-------------") + + message.Conf.MergeWith(conf) + + for _, line := range message.Conf.DumpConfig() { + fmt.Println(line) + } + + // TODO: Verify Message? + e, err := prepareEmail(&message) + + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } + + m, err := e.Bytes() + + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } + + fmt.Println("\nEmail message\n-------------") + fmt.Println(string(m)) +} diff --git a/cmd/next.go b/cmd/next.go new file mode 100644 index 0000000..f62aad2 --- /dev/null +++ b/cmd/next.go @@ -0,0 +1,91 @@ +/* next.go: show upcoming messages + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package cmd + +import ( + "fmt" + "github.com/docopt/docopt.go" + . "github.com/githubert/clockrotz/common" + "path/filepath" + "sort" + "strconv" + "time" +) + +var usageNext = +// tag::next[] +` +Usage: + clockrotz next [--days=DAYS | --all] + +Options: + --help Show this help. + --days=DAYS List messages for the next DAYS days. (default: 7) + --all List all pending messages. +` // end::next[] + +func Next(argv []string, conf *Configuration) { + args, _ := docopt.Parse(usageNext, argv, true, "", false) + + if args["--days"] != nil { + conf.Set("days", args["--days"].(string)) + } + + days, err := strconv.ParseInt(conf.Get(CONF_DAYS), 10, 0) + + if err != nil { + fmt.Println("Error while parsing value of --days") + return + } + + all := args["--all"].(bool) + + future := buildTime(time.Now().AddDate(0, 0, int(days)), 23, 59, false) + + messages := NewMessagesFromDirectory(filepath.Join(conf.Get(CONF_WORKDIR), DIR_TODO)) + sort.Sort(messages) + + if all { + fmt.Printf("Showing all messages.\n\n") + } else { + fmt.Printf("Showing messages before %s.\n\n", future.Format(DATETIME_FORMAT)) + } + + count := 0 + + for _, message := range messages { + message.Conf.MergeWith(conf) + + if errs := message.Verify(); errs != nil { + fmt.Printf("Error in message \"%s\". Please run 'clockrotz check'.\n", message.Name) + continue + } + + // Errors are caught already by Verify() + messageDate, _ := ParseTime(message.Get(CONF_DATE)) + + if all || messageDate.Before(future) { + count++ + fmt.Printf("%s %s (%s)\n", messageDate.Format(DATETIME_FORMAT), message.Get(CONF_SUBJECT), message.Name) + } + } + + if count == 0 { + fmt.Println("No messages.") + } +} diff --git a/cmd/run.go b/cmd/run.go new file mode 100644 index 0000000..4ba7b16 --- /dev/null +++ b/cmd/run.go @@ -0,0 +1,316 @@ +/* run.go: send pending messages + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package cmd + +import ( + "crypto/tls" + "fmt" + "github.com/docopt/docopt.go" + . "github.com/githubert/clockrotz/common" + "github.com/jordan-wright/email" + "net/mail" + "net/textproto" + "os" + "path/filepath" + "strings" + "time" +) + +var usageRun = +// tag::run[] +` +Usage: + clockrotz run [options] + +Options: + --help Show this help. + --to=ADDR Destination address. + --from=ADDR Sender address. + --subject=ADDR Short subject. + --cc=ADDR Set "Cc". + --bcc=ADDR Set "Bcc". + --reply-to=ADDR Set "Reply-To". + --not-before=TIME Not before TIME. (default: 00:00) + --not-after=TIME Not after TIME. (default: 23:59) + --server=HOST SMTP hostname. (default: localhost) + --port=PORT SMTP port. (default: 587) + --verbose Report on successfully sent messages. + --dry-run Do not send the message. + --insecure Accept any TLS certificate. +` // end::run[] + +func Run(argv []string, conf *Configuration) { + args, _ := docopt.Parse(usageRun, argv, true, "", false) + conf.MergeWithDocOptArgs(CMD_RUN, &args) + + verbose := args["--verbose"].(bool) + dryRun := args["--dry-run"].(bool) + insecure := args["--insecure"].(bool) + + now := time.Now() + + notBeforeTime, err := time.Parse(TIME_FORMAT, conf.Get(CONF_NOT_BEFORE)) + + if err != nil { + fmt.Printf("Failed parsing not-before time: %s\n", err.Error()) + return + } + + notAfterTime, err := time.Parse(TIME_FORMAT, conf.Get(CONF_NOT_AFTER)) + + if err != nil { + fmt.Printf("Failed parsing not-after time: %s\n", err.Error()) + return + } + + notBefore := buildTime(now, notBeforeTime.Hour(), notBeforeTime.Minute(), true) + notAfter := buildTime(now, notAfterTime.Hour(), notAfterTime.Minute(), false) + + // Return if we are in some quiet period. + if now.After(notAfter) || now.Before(notBefore) { + return + } + + messages := NewMessagesFromDirectory(filepath.Join(conf.Get(CONF_WORKDIR), DIR_TODO)) + + verificationError := false + + for _, message := range messages { + message.Conf.MergeWith(conf) + err := processMessage(message, now, dryRun, insecure, verbose) + + if err != nil { + verificationError = true + continue + } + } + + if verificationError { + // FIXME: This suggests that other messages were not sent, but they were.... + fmt.Println("There were errors when verifying one or more messages.") + fmt.Println("Please run 'clockrotz check'") + os.Exit(1) + } +} + +func processMessage(message Message, now time.Time, dryRun, insecure, verbose bool) error { + if errs := message.Verify(); errs != nil { + return fmt.Errorf("Message %s failed verification.", message.Name) + } + + date, err := ParseTime(message.Get("date")) + + if err != nil { + return err + } + + if !now.After(date) { + return nil + } + + sendErr := sendMessage(message, dryRun, insecure) + + if sendErr != nil { + if !dryRun { + err := moveMessage(message, DIR_ERRORS) + + if err != nil { + fmt.Printf("Error when moving message %s: %s\n", message.Name, err.Error()) + } + + logMessage(message, DIR_ERRORS, sendErr.Error()) + } + + fmt.Printf("Error when sending message %s: %s\n", message.Name, sendErr.Error()) + } else { + if !dryRun { + err := moveMessage(message, DIR_DONE) + + if err != nil { + fmt.Printf("Error when moving message %s: %s\n", message.Name, err.Error()) + } + + logMessage(message, DIR_DONE, "Successfully delivered.") + } + + if verbose { + fmt.Printf("Message %s delivered.\n", message.Name) + } + } + + return nil // TODO: what about errors that are not verification errors? +} + +func logMessage(message Message, dir string, logMessage string) { + dstDir := filepath.Join(message.Get(CONF_WORKDIR), dir) + filename := filepath.Join(dstDir, message.Name[:len(message.Name)-len(".msg")]+".log") + + f, err := os.Create(filename) + + if err != nil { + fmt.Printf("Error when creating log file: %s\n", err.Error()) + return + } + + defer f.Close() + + f.WriteString("Log message:\n") + f.WriteString(fmt.Sprintf(" %s\n", logMessage)) + f.WriteString("\n") + + f.WriteString("\nConfiguration:\n") + for _, s := range message.Conf.DumpConfig() { + f.WriteString(fmt.Sprintf(" %s\n", s)) + } + + f.WriteString("\nBody:\n") + for _, s := range message.Body { + f.WriteString(fmt.Sprintf(" %s\n", s)) + } +} + +// Turn the given plain address list string into an array. +func getAddresses(addressList string) ([]string, error) { + addresses, err := mail.ParseAddressList(addressList) + + if err != nil { + return nil, err + } + + result := []string{} + + for _, address := range addresses { + result = append(result, address.String()) + } + + return result, nil +} + +// Prepare a ready-to-send Email message. +func prepareEmail(message *Message) (*email.Email, error) { + e := email.NewEmail() + e.From = message.Get(CONF_FROM) + e.Subject = message.Get(CONF_SUBJECT) + + // Build list of To addresses. + to, err := getAddresses(message.Get(CONF_TO)) + + if err != nil { + return nil, err + } + + e.To = to + + // Set optional Reply-To header. + if r := message.Get(CONF_REPLY_TO); r != "" { + replyTo, err := getAddresses(r) + + if err != nil { + return nil, err + } + + e.Headers = textproto.MIMEHeader{"Reply-To": replyTo} + } + + // Build list of Cc addresses. + if r := message.Get(CONF_CC); r != "" { + cc, err := getAddresses(r) + + if err != nil { + return nil, err + } + + e.Cc = cc + } + + // Build list of Bcc addresses. + if r := message.Get(CONF_BCC); r != "" { + bcc, err := getAddresses(r) + + if err != nil { + return nil, err + } + + e.Bcc = bcc + } + + e.Text = []byte(strings.Join(message.Body, "\n")) + + return e, nil +} + +// Send the given message, unless `dryRun` is true. Use `insecure` to work +// around things like self-signed certificates. +func sendMessage(message Message, dryRun bool, insecure bool) error { + e, err := prepareEmail(&message) + + if err != nil { + return err + } + + smtpServer := message.Get(CONF_SMTP_SERVER) + ":" + message.Get(CONF_SMTP_PORT) + + if dryRun { + fmt.Printf("Skip sending message %s through %s.\n", message.Name, smtpServer) + return nil + } + + if insecure { + return e.SendWithTLS(smtpServer, nil, &tls.Config{InsecureSkipVerify: true}) + } else { + return e.Send(smtpServer, nil) + } +} + +// Move the given message to a folder relative to the working directory. +func moveMessage(message Message, relative string) error { + todo := filepath.Join(message.Get(CONF_WORKDIR), DIR_TODO) + to := filepath.Join(message.Get(CONF_WORKDIR), relative) + + // FIXME: BUG: This will overwrite existing messages. Look at create.go:nextFreeFilename() + // for ideas on how to resolve this. We could try to use a similar approach. + // `foo.msg` to `foo.1.msg` and `foo.1.log`. + + return os.Rename(filepath.Join(todo, message.Name), filepath.Join(to, message.Name)) +} + +// Build a time.Time from some given base time. If floor is true, seconds will +// be set to 0, if false, 59. +// TODO: Maybe there is a better way?… +func buildTime(base time.Time, hour int, minute int, floor bool) time.Time { + seconds := 0 + + if !floor { + // We ignore the possibility of leap seconds here, this is + // just done so that we can get 23:59:59 instead of 23:59:00. + // 23:59:00 would make us miss a whole minute. It would be + // nice if there were a way to indicate to time.Date() to + // build a date with start of the day / end of the day... + seconds = 59 + } + + return time.Date( + base.Year(), + base.Month(), + base.Day(), + hour, + minute, + seconds, + 0, + base.Location()) +} diff --git a/cmd/run_test.go b/cmd/run_test.go new file mode 100644 index 0000000..2c405e9 --- /dev/null +++ b/cmd/run_test.go @@ -0,0 +1,39 @@ +/* run_test.go: unit tests for 'run' command + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package cmd + +import ( + "github.com/stretchr/testify/assert" + "testing" + "time" +) + +func TestBuildTime(t *testing.T) { + h := 8 + m := 30 + + t1 := buildTime(time.Now(), h, m, true) + + assert.Equal(t, t1.Hour(), 8) + assert.Equal(t, t1.Minute(), 30) + assert.Equal(t, t1.Second(), 0) + + t2 := buildTime(time.Now(), h, m, false) + + assert.Equal(t, t2.Second(), 59) +} diff --git a/common/configuration.go b/common/configuration.go new file mode 100644 index 0000000..2948116 --- /dev/null +++ b/common/configuration.go @@ -0,0 +1,142 @@ +/* configuration.go: module for managing message properties + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package common + +import ( + "fmt" + "github.com/go-ini/ini" + "sort" + "strconv" + "strings" +) + +type Configuration struct { + Data map[string]string +} + +func NewConfiguration() *Configuration { + return &Configuration{ + Data: map[string]string{}, + } +} + +func (c *Configuration) Get(key string) string { + return c.Data[key] +} + +func (c *Configuration) Set(key string, value string) { + c.Data[key] = value +} + +// Load configuration from an array of strings in the form `key: value`. +func (c *Configuration) Load(text []string) { + c.Data = map[string]string{} + + for _, line := range text { + r := strings.SplitN(line, ":", 2) + + key := strings.TrimSpace(r[0]) + + if len(r) == 2 { + c.Data[key] = strings.TrimSpace(r[1]) + } else { + if key != "" { + c.Data[key] = "" + } + } + } +} + +// Merge the `src` configuration into this configuration. +func (c *Configuration) MergeWith(src *Configuration) { + for k, v := range (*src).Data { + (*c).Data[k] = v + } +} + +// Merge arguments from a INI section into the given map. +func mergeIniSection(section *ini.Section, dst *map[string]string) { + for _, k := range section.KeyStrings() { + (*dst)[k] = section.Key(k).String() + } +} + +// Merges the "default" and the "cmd" section from CONF_CONFIG_FILENAME. +func (c *Configuration) MergeWithIni(cmd string) { + cfg, err := ini.Load(c.Get(CONF_CONFIG_FILENAME)) + + if err == nil { + section, err := cfg.GetSection("default") + + if err == nil { + mergeIniSection(section, &c.Data) + } + + section, err = cfg.GetSection(cmd) + + if err == nil { + mergeIniSection(section, &c.Data) + } + } +} + +// Merge arguments from the DocOpt parser into a configuration map. All +// arguments that are not `nil` and start with "--" will be merged. +// Booleans will be converted to strings. +func (c *Configuration) MergeWithDocOptArgs(cmd string, args *map[string]interface{}) { + for k, v := range *args { + + // The args list contains the name of the command, but we are not + // interested in it. + if k == cmd { + continue + } + + // Merge all args that start with -- and where the value is not nil + if v != nil && (len(k) > 2 && k[0:2] == "--") { + switch v.(type) { + case string: + c.Data[k[2:]] = v.(string) + case bool: + c.Data[k[2:]] = strconv.FormatBool(v.(bool)) + } + + } + } +} + +// Dump the configuration as strings in the form `key: value`. +func (c *Configuration) DumpConfig() []string { + keys := make([]string, len(c.Data)) + + i := 0 + for k, _ := range c.Data { + keys[i] = k + i++ + } + + sort.Strings(keys) + + result := make([]string, len(keys)) + + for i, k := range keys { + result[i] = fmt.Sprintf("%s: %s", k, c.Get(k)) + } + + return result +} diff --git a/common/configuration_test.go b/common/configuration_test.go new file mode 100644 index 0000000..dbf2697 --- /dev/null +++ b/common/configuration_test.go @@ -0,0 +1,105 @@ +/* configuration_test.go: unit tests for the configuration module + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package common + +import ( + "github.com/go-ini/ini" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestConfiguration_MergeWith(t *testing.T) { + src := Configuration{ + Data: map[string]string{ + "port": "1", + "server": "example.com", + }, + } + + dst := Configuration{ + Data: map[string]string{ + "server": "example.net", + "workdir": "/home/foo", + }, + } + + expected := map[string]string{ + "port": "1", + "server": "example.com", + "workdir": "/home/foo", + } + + dst.MergeWith(&src) + + assert.Equal(t, expected, dst.Data) +} + +func TestConfiguration_MergeWithIni(t *testing.T) { + dst := map[string]string{ + "port": "1", + "server": "example.com", + } + + iniContents := []byte(` + [foo] + port = 1234 + workdir = /home/foo + `) + + expected := map[string]string{ + "port": "1234", + "server": "example.com", + "workdir": "/home/foo", + } + + cfg, _ := ini.Load(iniContents) + + section := cfg.Section("foo") + + mergeIniSection(section, &dst) + + assert.Equal(t, expected, dst) +} + +func TestConfiguration_Load(t *testing.T) { + text := []string{ + "to: me@example.com", + "from: ", + "subject", + "", + } + + expected := map[string]string{ + "to": "me@example.com", + "from": "", + "subject": "", + } + + conf := Configuration{} + conf.Load(text) + + assert.Equal(t, expected, conf.Data) +} + +func TestConfiguration_Get(t *testing.T) { + conf := NewConfiguration() + + conf.Set("foo", "bar") + + assert.Equal(t, "bar", conf.Get("foo")) +} diff --git a/common/consts.go b/common/consts.go new file mode 100644 index 0000000..822f413 --- /dev/null +++ b/common/consts.go @@ -0,0 +1,49 @@ +/* consts.go: global constants + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package common + +// Project wide constants. +const ( + TIME_FORMAT = "15:04" + DATE_FORMAT = "2006-01-02" + DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT + + DIR_TODO = "todo" + DIR_DRAFTS = "drafts" + DIR_ERRORS = "errors" + DIR_DONE = "done" + + CMD_USAGE = "usage" + CMD_RUN = "run" + + CONF_WORKDIR = "workdir" + CONF_DATE = "date" + CONF_DAYS = "days" + CONF_SUBJECT = "subject" + CONF_TO = "to" + CONF_FROM = "from" + CONF_REPLY_TO = "reply-to" + CONF_CC = "cc" + CONF_BCC = "bcc" + CONF_CONFIG_FILENAME = "config" + CONF_SMTP_SERVER = "server" + CONF_SMTP_PORT = "port" + CONF_SMTP_INSECURE = "insecure" + CONF_NOT_BEFORE = "not-before" + CONF_NOT_AFTER = "not-after" +) diff --git a/common/message.go b/common/message.go new file mode 100644 index 0000000..fbea53d --- /dev/null +++ b/common/message.go @@ -0,0 +1,231 @@ +/* message.go: module for managing message information + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package common + +import ( + "bufio" + "fmt" + "net/mail" + "os" + "path/filepath" +) + +type Message struct { + Conf Configuration + Body []string + Name string +} + +// Supporting sort.Interface. +type Messages []Message + +// Load all messages in the given directory. +func NewMessagesFromDirectory(dir string) Messages { + messages := []Message{} + + err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + // Only interested in regular files + if !info.Mode().IsRegular() { + return nil + } + + // Parse only .msg files + if filepath.Ext(info.Name()) != ".msg" { + return nil + } + + message, err := NewMessageFromFile(path) + + if err != nil { + return err + } + + messages = append(messages, message) + + return nil + }) + + // TODO: Maybe return error? + if err != nil { + fmt.Printf("Error while reading messages from %s:\n\t%s\n", dir, err.Error()) + } + + return messages +} + +func (m Messages) Len() int { return len(m) } +func (m Messages) Swap(i, j int) { m[i], m[j] = m[j], m[i] } +func (m Messages) Less(i, j int) bool { + // TODO: We are being very confident here w.r.t. errors + t1, _ := ParseTime(m[i].Get(CONF_DATE)) + t2, _ := ParseTime(m[j].Get(CONF_DATE)) + + return t1.Before(t2) +} + +// Create a new, empty Message. +func NewMessage() *Message { + return &Message{ + Conf: *NewConfiguration(), + Body: []string{}, + Name: "", + } +} + +// Construct new Message from the given file. +func NewMessageFromFile(path string) (Message, error) { + f, err := os.Open(path) + + if err != nil { + return Message{}, err + } + + defer f.Close() + + scanner := bufio.NewScanner(f) + + lines := []string{} + + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + msgConf, msgBody := SplitMessage(lines) + + configuration := Configuration{} + configuration.Load(msgConf) + + return Message{ + Body: msgBody, + Conf: configuration, + Name: filepath.Base(path), + }, nil +} + +// Write a message to a file, such that it could be loaded again. +func (m *Message) WriteToFile(file string) error { + f, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY, 0666) + + if err != nil { + return err + } + + defer f.Close() + + for _, s := range m.Conf.DumpConfig() { + f.WriteString(s) + f.WriteString("\n") + } + + f.WriteString("\n") + + for _, s := range m.Body { + f.WriteString(s) + f.WriteString("\n") + } + + return nil +} + +// Return the specified configuration key's value. +func (m *Message) Get(key string) string { + return m.Conf.Data[key] +} + +// Checks if set and if ParseAddressList succeeds +func verifyAddressList(addresses string) error { + if addresses == "" { + // TODO: Why is this part different than the one in verifyAddress()? Maybe not intentional? + return nil + } + + _, err := mail.ParseAddressList(addresses) + + if err != nil { + return err + } + + return nil +} + +// Checks if no nil and if ParseAddress succeeds. +func verifyAddress(paramName string, address string) error { + if address == "" { + return fmt.Errorf("'%s' parameter is missing", paramName) + } + + _, err := mail.ParseAddress(address) + + if err != nil { + return err + } + + return nil +} + +// Verify if a message has all necessary parameters. We need at least to, from, +// subject, and date. This will also verify optional address lists, etc. +func (m *Message) Verify() []error { + errors := []error{} + + if err := verifyAddress("from", m.Get("from")); err != nil { + errors = append(errors, err) + } + + if err := verifyAddress("to", m.Get("to")); err != nil { + errors = append(errors, err) + } + + if m.Get("subject") == "" { + errors = append(errors, fmt.Errorf("'subject' parameter is missing")) + } + + if m.Get("date") == "" { + errors = append(errors, fmt.Errorf("'date' parameter is missing")) + } else { + _, err := ParseTime(m.Get("date")) + + if err != nil { + errors = append(errors, fmt.Errorf("'date' format error: %s", err.Error())) + } + } + + if m.Get("reply-to") != "" { + if err := verifyAddress("nil", m.Get("to")); err != nil { + errors = append(errors, err) + } + } + + if err := verifyAddressList(m.Get("cc")); err != nil { + errors = append(errors, err) + } + + if err := verifyAddressList(m.Get("bcc")); err != nil { + errors = append(errors, err) + } + + if len(errors) == 0 { + return nil + } + + return errors +} diff --git a/common/message_test.go b/common/message_test.go new file mode 100644 index 0000000..74ed09f --- /dev/null +++ b/common/message_test.go @@ -0,0 +1,82 @@ +/* message_test.go: unit tests for the message module + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package common + +import ( + "github.com/stretchr/testify/assert" + "path/filepath" + "sort" + "testing" +) + +func TestReadMessagesAndVerify(t *testing.T) { + workdir := "testdata" + + conf := NewConfiguration() + conf.Set("from", "me@example.com") + + messages := NewMessagesFromDirectory(filepath.Join(workdir, "todo")) + + for _, message := range messages { + // If we don't to this, it will fail because "from" is missing + message.Conf.MergeWith(conf) + + if err := message.Verify(); err != nil { + t.Errorf("Verification of message '%s' failed with %s", message.Name, err) + } + } +} + +func TestMessage_Get(t *testing.T) { + message := Message{Conf: *NewConfiguration()} + + message.Conf.Set("foo", "bar") + + assert.Equal(t, "bar", message.Get("foo")) +} + +func TestMessagesSort(t *testing.T) { + messages := []Message{ + { + Name: "1", + Conf: Configuration{ + Data: map[string]string{ + "date": "2000-01-01", + }}}, + { + Name: "2", + Conf: Configuration{ + Data: map[string]string{ + "date": "2010-01-01", + }}}, + { + Name: "3", + Conf: Configuration{ + Data: map[string]string{ + "date": "2005-01-01", + }}}, + } + + sort.Sort(Messages(messages)) + + for i, k := range []string{"1", "3", "2"} { + if messages[i].Name != k { + t.Errorf("expected: %s, but was %s", k, messages[i].Name) + } + } +} diff --git a/common/util.go b/common/util.go new file mode 100644 index 0000000..a4422c7 --- /dev/null +++ b/common/util.go @@ -0,0 +1,63 @@ +/* util.go: various utility functions + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package common + +import ( + "strings" + "time" +) + +// Split a text in two parts on the first blank line. +func SplitMessage(text []string) ([]string, []string) { + conf := []string{} + body := []string{} + + inBody := false + + for _, line := range text { + if !inBody && strings.TrimSpace(line) == "" { + inBody = true + continue // skip the separating line + } + + if inBody { + body = append(body, line) + } else { + conf = append(conf, line) + } + } + + return conf, body +} + +// Parse a time which may either be just a date or a date with time. +func ParseTime(datetime string) (time.Time, error) { + result, err := time.ParseInLocation(DATE_FORMAT, datetime, time.Now().Location()) + + if err == nil { + return result, nil + } + + result, err = time.ParseInLocation(DATETIME_FORMAT, datetime, time.Now().Location()) + + if err == nil { + return result, nil + } + + return result, err +} diff --git a/common/util_test.go b/common/util_test.go new file mode 100644 index 0000000..201cfe0 --- /dev/null +++ b/common/util_test.go @@ -0,0 +1,79 @@ +/* util_test.go: unit tests for utility functions + * + * Copyright (C) 2016 Clemens Fries <github-clockrotz@xenoworld.de> + * + * 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 <http://www.gnu.org/licenses/>. + */ +package common + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestSplitMessage(t *testing.T) { + message := []string{ + "to: me@example.com", + "subject: foo", + "", + "Dear Me,", + "", + "have a nice day.", + } + + conf, body := SplitMessage(message) + + expectedConf := []string{ + "to: me@example.com", + "subject: foo", + } + + expectedBody := []string{ + "Dear Me,", + "", + "have a nice day.", + } + + assert.Equal(t, expectedConf, conf) + assert.Equal(t, expectedBody, body) +} + +func TestParseTime(t *testing.T) { + d1 := "2061-07-28" + d2 := "2061-07-28 12:23" + invalid1 := "2061/07/28" + invalid2 := "2061-07-28 12:23:00" + + r, err := ParseTime(d1) + assert.Nil(t, err) + + if r.Hour() != 0 || r.Minute() != 0 { + t.Errorf("expected Hour and Minute to be 0, but was %s", r) + } + + r, err = ParseTime(d2) + assert.Nil(t, err) + + if r.Hour() != 12 || r.Minute() != 23 { + t.Errorf("expected Hour and Minute to be 12:23, but was %s", r) + } + + // Expected to fail + _, err = ParseTime(invalid1) + assert.NotNil(t, err) + + // Expected to fail + _, err = ParseTime(invalid2) + assert.NotNil(t, err) +} diff --git a/testdata/config.ini b/testdata/config.ini new file mode 100644 index 0000000..d5195f4 --- /dev/null +++ b/testdata/config.ini @@ -0,0 +1,5 @@ +[default] +from = me@example.com +workdir = testdata +server = mail.example.com +port = 1234 diff --git a/testdata/todo/2061.msg b/testdata/todo/2061.msg new file mode 100644 index 0000000..5378da5 --- /dev/null +++ b/testdata/todo/2061.msg @@ -0,0 +1,8 @@ +to: me@example.com +subject: Watch Halley's Comet +date: 2061-07-28 + +Greetings! + +Go outside at night, if the curfew of the – highly welcomed — alien overlords +permits, and watch Halley's Comet. diff --git a/testdata/todo/2134.msg b/testdata/todo/2134.msg new file mode 100644 index 0000000..3db6f3c --- /dev/null +++ b/testdata/todo/2134.msg @@ -0,0 +1,11 @@ +to: cryogenics-department@example.com +from: me-bot@example.com +cc: me@example.com +subject: Unfreeze Clemens +date: 2134-01-01 + +Dear Cryogenics Department, + +please unfreeze Clemens, as he wanted to watch this year's close pass of +Halley's Comet. This one is going to have an apparent magnitude of -2.0 — it's +gonna be fun, so feel free to join him! |