diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 6452e07..c5f776a 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,5 +1,5 @@ { - "name": "CHANGE IT", + "name": "EP", "dockerComposeFile": [ "../docker-compose.yml" ], diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 4047c80..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "workbench.colorCustomizations": { - "activityBar.activeBackground": "#fbed80", - "activityBar.activeBorder": "#06b9a5", - "activityBar.background": "#fbed80", - "activityBar.foreground": "#15202b", - "activityBar.inactiveForeground": "#15202b99", - "activityBarBadge.background": "#06b9a5", - "activityBarBadge.foreground": "#15202b", - "statusBar.background": "#f9e64f", - "statusBar.foreground": "#15202b", - "statusBarItem.hoverBackground": "#f7df1e", - "titleBar.activeBackground": "#f9e64f", - "titleBar.activeForeground": "#15202b", - "titleBar.inactiveBackground": "#f9e64f99", - "titleBar.inactiveForeground": "#15202b99", - "sash.hoverBorder": "#fbed80", - "statusBarItem.remoteBackground": "#f9e64f", - "statusBarItem.remoteForeground": "#15202b", - "commandCenter.border": "#15202b99" - }, - "peacock.remoteColor": "#f9e64f" -} diff --git a/CHANGELOG.md b/CHANGELOG.md index 570089c..3133cef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,83 +14,6 @@ Types of changes - `Fixed` for any bug fixes. - `Security` in case of vulnerabilities. -## [1.3.0] - -- `Added` test-int-debug target. - -## [1.2.0] - -- `Added` go-devcontainer version from v2.0 to v3.1 (golang 1.21). -- `Added` miller version 6.8.0. - -## [1.1.0] - -- `Changed` go-devcontainer version from v1.0 to v2.0 (golang 1.20). - -## [1.0.1] - -- `Fixed` more portable neon info, tested in GitHub CodeSpaces. - -## [1.0.0] - -- `Changed` go-devcontainer version from v0.7 to v1.0 (golang 1.9). - -## [0.8.0] - -- `Changed` go-devcontainer version from v0.6 to v0.7 (golang 1.8). -- `Changed` miller version from v6.0.0 to v6.2.0 - -## [0.7.1] - -- `Fixed` release github action break when dependabot is enabled. - -## [0.7.0] - -- `Changed` Upgrade go-devcontainer from v0.5 to v0.6. -- `Changed` Upgrade mlr from 5.10.2 to 6.0.0. - -## [0.6.1] - -- `Fixed` Disabling `golint` linter because it has been archived by the owner. - -## [0.6.0] - -- `Changed` Upgrade go-devcontainer from v0.4 to v0.5. - -## [0.5.0] - -- `Changed` Upgrade go-devcontainer from v0.3 to v0.4. - -## [0.4.1] - -- `Fixed` Regression on GitHub release action. - -## [0.4.0] - -- `Changed` Upgrade go-devcontainer from v0.2 to v0.3. -- `Changed` Execute GitHub actions on ci flavored container (smaller image). -- `Fixed` Refresh target when the repo has UPPERCASE letters. -- `Fixed` Autoset permissions when starting devcontainer on a git repo that was not cloned by vscode user. -- `Fixed` CONTRIB.md was renamed to CONTRIBUTING.md and initialized with basic instructions. -- `Fixed` Refresh target always recreate go.mod and go.sum. -- `Fixed` Promote target does not create tag. -- `Fixed` Docker-tag target complains about missing DOCKERHUB_PASS. - -## [0.3.0] - -- `Added` Colors in neon help target. -- `Added` License target to scan 3rd party licenses and generate notice file. -- `Added` Default GitHub action for CI checks, run on push or pull request events but only for the main branch. -- `Added` Default GitHub action for Release, run on new tags. -- `Fixed` Cleaner git ignore. -- `Changed` Improved default linters configuration, and cleaner gopls configuration. -- `Changed` Build target `docker-publish` renamed to `docker-push`. - -## [0.2.0] - -- `Fixed` Publish target works properly; -- `Changed` Publish target now depends from the `test-int` target. - ## [0.1.0] -- `Added` First official version of the template. +- `Added` minimal features. diff --git a/Dockerfile b/Dockerfile index 5935b6e..b024981 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ FROM gcr.io/distroless/base ARG BIN -COPY /bin/cli /cli -CMD ["/cli"] +COPY /bin/ep /ep +CMD ["/ep"] diff --git a/Dockerfile.webserver b/Dockerfile.webserver deleted file mode 100644 index bc276b8..0000000 --- a/Dockerfile.webserver +++ /dev/null @@ -1,5 +0,0 @@ -FROM gcr.io/distroless/base -ARG BIN -COPY /bin/webserver /webserver -EXPOSE 8080 -CMD ["/webserver"] diff --git a/LICENSE b/LICENSE index 958d273..f288702 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,674 @@ -MIT License - -Copyright (c) 2021 Adrien Aury - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/NOTICE.md b/NOTICE.md deleted file mode 100644 index b7d758f..0000000 --- a/NOTICE.md +++ /dev/null @@ -1,16 +0,0 @@ -# 3rd-Party Software Licenses - -The following 3rd-party software components may be used by or distributed with this project. Any information relevant to third-party vendors listed below are collected using common, reasonable means. - -## cli - -| module | license | -| --- | --- | -| github.com/rs/zerolog | MIT License | - -## webserver - -| module | license | -| --- | --- | -| github.com/gorilla/mux | BSD 3-Clause "New" or "Revised" License | -| github.com/rs/zerolog | MIT License | diff --git a/README.md b/README.md index 5e03a7e..7d38ba2 100644 --- a/README.md +++ b/README.md @@ -1,685 +1,22 @@ -# Go Template +# Emporte-Pièce -This repository is a Go project template. This is not a real application, the go source code is an empty shell. - -List of folders - -- `cmd` contains source code of all compiled binaries, each sub-folder correspond to a binary. -- `internal` contains source code that cannot be linked in an external project. -- `pkg` contains source code that can be linked in an external project. -- `test` contains integration tests source code (run with venom). -- `githooks` contains git hooks for better automation. +Create project file/directory structure from data + template definition. ## Usage -### Prerequisites - -You need : - -- Visual Studio Code ([download](https://code.visualstudio.com/)) with the [Remote - Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) installed. -- Docker Desktop (Windows, macOS) or Docker CE/EE (Linux) - -Details are available on [the official Visual Studio documentation](https://code.visualstudio.com/docs/remote/containers#_getting-started). - -### Initialize a new repository using Github - -Use the button `Use this template` at the top of this page. It will automatically initialize your new repository with this template. - -### Initialize a new repository without using Github - -```console -$ cd -/your/project/root$ wget -nv -O- https://github.com/adrienaury/go-template/archive/refs/heads/main.tar.gz | tar --strip-components=1 -xz -/your/project/root$ git init -b main -/your/project/root$ git add . -/your/project/root$ git commit -m "chore: init repository from go template" -``` - -### Modify an existing repository - -Warning: do this in a branch where to isolate the changes - -```console -$ cd -/your/project/root$ wget -nv -O- https://github.com/adrienaury/go-template/archive/refs/heads/main.tar.gz | tar --strip-components=1 -xz -``` - -### Things you might or should delete (or replace) - -- might: the `.vscode` folder contains a VSCode color theme, you might want to remove this folder, or customize the colors -- might: the `githooks/commit-msg` file contains a commit message check to enforce [semantic commit message](https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716) -- might: the `Makefile` if you want to only use the neon build tool, but I think it's nice to give a well known handle to the build workflow -- might: the `.github` folder if you don't want to use GitHub actions -- should: the `Dockerfile` and the `Dockerfile.webserver` if your project does not produce Docker images (DO NOT DELETE the `docker-compose.yml` file, you can move it under `.devcontainer` and adapt paths) -- should: the `LICENSE` file as your project is not copyrighted by me ! Replace it by your own license -- should: everything under `test/suites`, replace it with your own tests suites or remove the `test` folder completely if you don't do integration tests -- should: every `.go` file will have to be deleted, as well as folders under `cmd`, `pkg` and `internal` -- should: this `README.md` file, of course ;) - -### Run your workspace - -When opening the folder with [Visual Studio Code](https://code.visualstudio.com/), the [Remote - Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) will detect the devcontainer configuration and ask you to reopen the project in a container. - -Accept and enjoy ! - -## Features - -- Structured Go code following folder names convention -- VSCode devcontainer pre-parameterized -- Auto code formatting, using EditorConfig extension -- Changelog, Contrib : all initialized with default templates -- Git commit message semantic validation -- Docker compatible (docker client and docker-compose are available inside the devcontainer) -- Pre-configured GitHub actions : CI on pull requests, Release on tag -- Build targets (run with `make` or `neon`) : - - [`help`](#help-target) : default target, print help message - - [`info`](#info-target) : print information on the build pipeline - - [`promote`](#promote-target) : promote the project to a new tag using semantic versioning - - [`refresh`](#refresh-target) : refresh go modules dependencies - - [`compile`](#compile-target) : compile sources - - [`lint`](#lint-target) : check the code for suspicious constructs - - [`test`](#test-target) : run the unit tests - - [`release`](#release-target) : compile binaries, with production flags - - [`test-int`](#test-int-target) : run integration tests with venom - - [`publish`](#publish-target) : publish binaries on Github with goreleaser - - [`docker`](#docker-target) : build docker images - - [`docker-tag`](#docker-tag-target) : tag docker images using semantic versioning - - [`docker-push`](#docker-push-target) : publish docker images on Dockerhub - - [`license`](#license-target) : scan binaries for 3rd party licenses and generate a notice file - -### Build targets - -Run a build target by using the neon command. - -```console -neon target -``` - -This text bloc show how target are related to each other. E.g. running the target `lint` will also run `info` and `refresh`. - -```text -→ help -→ promote -→ info ┰ docker → docker-tag → docker-push - ┖ refresh ┰ compile → license - ┖ lint → test → release → test-int → publish -``` - -Multiple targets can be run in the same command, e.g. `neon release docker-tag`. - -Neon targets are also mapped to a Makefile, so running `make compile` will produce the same result as running `neon compile`. - -#### Help target - -```console -$ neon help ------------------------------------------------ help -- -Available targets - -help Print this message -info Print build informations -promote Promote the project with a new tag based on git log history -refresh Refresh go modules (add missing and remove unused modules) [info] -compile Compile binary files locally [info->refresh] -lint Examine source code and report suspicious constructs [info->refresh] -test Run all tests with coverage [info->refresh->lint] -release Compile binary files for production [info->refresh->lint->test] -test-int Run all integration tests [info->refresh->lint->test->release] -publish Publish tagged binary to Github [info->refresh->lint->test->release->test-int] -docker Build docker images [info] -docker-tag Tag docker images [info->docker] -docker-push Publish docker images to Dockerhub [info->docker->docker-tag] -license Scan licenses from binaries and generate notice file [info->refresh->compile] - -Example: neon -props '{latest: true}' promote publish - -Target dependencies - -→ help -→ promote -→ info ┰ docker → docker-tag → docker-push - ┖ refresh ┰ compile → license - ┖ lint → test → release → test-int → publish -OK -``` - -#### Info target - -Print build informations, like the author or the current tag. - -```console -$ neon info ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = 00424c8c67bca5b11ed99efa0d45902f1143cbd7 -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no -OK -``` - -#### Promote target - -Promote the project with a new tag based on git log history, or based on the parameter passed with `-props` flag. - -Without parameter, the tag name will be determined by the git commit history since the last tag (or will be equal to `v0.1.0` if there is no existing tag). This is base on the [`svu`](https://github.com/caarlos0/svu) tool. - -```console -$ neon promote ---------------------------------------------- promote -- -Promoted to v0.2.0 -OK -``` - -It's possible to use the `-props` flag to override the name of the tag. - -```console -$ neon -props '{tag: "v0.2.1-alpha"}' promote ---------------------------------------------- promote -- -Promoted to v0.2.1-alpha -OK -``` - -#### Refresh target - -Refresh go modules (add missing and remove unused modules). - -This target will keep your `go.mod` and `go.sum` files clean. - -```console -$ neon refresh ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = 00424c8c67bca5b11ed99efa0d45902f1143cbd7 -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy -OK -``` - -#### Compile target - -Compile binary files locally. - -By default, the `cmd` folder is scanned and each subfolder will create a binary with the name of the subfolder. +Example ```console -$ neon compile ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = b0b418aa05db7f386275249ea641f14b295cf3ab -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy ---------------------------------------------- compile -- -Building cmd/cli -Building cmd/webserver -OK +$ ep template < context.yml +8:41AM INF start color=auto debug=false log-json=false verbosity=info +8:41AM INF generating MyProject from=template/{{projectName}} +8:41AM INF generating MyProject/mask from=template/{{projectName}}/mask +8:41AM INF generating MyProject/mask/masking_TABLE1.yml from=template/{{projectName}}/mask/masking_{{$[-2].tables.[].name}}.yml +8:41AM INF generating MyProject/mask/masking_TABLE2.yml from=template/{{projectName}}/mask/masking_{{$[-2].tables.[].name}}.yml +8:41AM INF generating MyProject/pseudo_AX.sh from=template/{{projectName}}/pseudo_{{$[-2].projectName}}.sh +8:41AM INF end return=0 ``` -It's possible to use the `-props` flag to specify a list of folders to compile. Be aware that if one of these folders does not have a `main` package, the result file will not be executable. - -```console -$ neon -props '{buildpaths: ["internal/helloservice"]}' compile ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = b0b418aa05db7f386275249ea641f14b295cf3ab -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy ---------------------------------------------- compile -- -Building internal/helloservice -OK -``` - -#### Lint target - -Examine source code and report suspicious constructs. Under the hood, the [`golangci-lint`](https://github.com/golangci/golangci-lint) tool is used. - -```console -$ neon lint ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = b0b418aa05db7f386275249ea641f14b295cf3ab -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy ------------------------------------------------- lint -- -Running command: golangci-lint run --fast --enable-all --disable scopelint --disable forbidigo -OK -``` - -By default, all fast linters are enabled (`--fast` and `--enable-all` flags) but you can change this with the following build properties : - -- `linters` : an array of linters to enable, if left empty then all fast linters are enabled. -- `lintersno` : an array of linters to disable, by default `scopelint` (deprecated) and `forbidigo` are disabled. - -To change the default values, edit the `build.yml` file and look for the properties names `linters` or `lintersno`. - -These build properties can also be set by the `neon -props` flag. - -```console -$ neon -props '{linters: ["deadcode"]}' lint ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = b0b418aa05db7f386275249ea641f14b295cf3ab -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy ------------------------------------------------- lint -- -Running command: golangci-lint run --enable deadcode --disable scopelint --disable forbidigo -OK -``` - -#### Test target - -Run all tests with coverage. - -```console -$ neon test ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = 6ac8d1ab1facb9969a84b330d08e0f3efac55819 -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy ------------------------------------------------- lint -- -Running command: golangci-lint run --fast --enable-all --disable scopelint --disable forbidigo ------------------------------------------------- test -- -? github.com/adrienaury/go-template/cmd/cli [no test files] -? github.com/adrienaury/go-template/cmd/webserver [no test files] -? github.com/adrienaury/go-template/internal/helloservice [no test files] -? github.com/adrienaury/go-template/pkg/nameservice [no test files] -OK -``` - -#### Release target - -Compile binary files for production. - -The only difference with the [`compile`](#compile) target is with the `ldflags` passed to the Go linker (it will produce a smaller binary) and the dependency to other targets ([`lint`](#lint) and [`test`](#test)). - -```console -$ neon release ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = b0b418aa05db7f386275249ea641f14b295cf3ab -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy ------------------------------------------------- lint -- -Running command: golangci-lint run --fast --enable-all --disable scopelint --disable forbidigo ------------------------------------------------- test -- -? github.com/adrienaury/go-template/cmd/cli [no test files] -? github.com/adrienaury/go-template/cmd/webserver [no test files] -? github.com/adrienaury/go-template/internal/helloservice [no test files] -? github.com/adrienaury/go-template/pkg/nameservice [no test files] ---------------------------------------------- release -- -Calling target 'compile' ---------------------------------------------- compile -- -Building cmd/cli -Building cmd/webserver -OK -``` - -The build properties are the same as the [`compile`](#compile) target. - -#### Test-int target - -Run all integration tests. Under the hood the tool [`venom`](https://github.com/ovh/venom) is used. - -By default it will run every test suites under the folder `test/suites`. - -```console -neon test-int ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = 9791b0c79b55f2f34517d7e6b64d4900c8c7f2ce -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy ------------------------------------------------- lint -- -Running command: golangci-lint run --fast --enable-all --disable scopelint --disable forbidigo ------------------------------------------------- test -- -? github.com/adrienaury/go-template/cmd/cli [no test files] -? github.com/adrienaury/go-template/cmd/webserver [no test files] -? github.com/adrienaury/go-template/internal/helloservice [no test files] -? github.com/adrienaury/go-template/pkg/nameservice [no test files] ---------------------------------------------- release -- -Calling target 'compile' ---------------------------------------------- compile -- -Building cmd/cli -Building cmd/webserver --------------------------------------------- test-int -- - • run cli (test/suites/01-run-cli.yml) - • no-arguments SUCCESS - • run webserver (test/suites/02-run-webserver.yml) - • no-arguments SUCCESS -OK -``` - -#### Publish target - -Publish tagged binary to Github (as a Release). Under the hood, the [`goreleaser`](https://github.com/goreleaser/goreleaser) tool is used. - -Edit the file `./goreleaser.template.yml` to configure the [`goreleaser`](https://github.com/goreleaser/goreleaser) build. - -A prerequisite to this target is that a file named `.github.yml` at the home directory (`~/.github.yml`) contains a `GITHUB_TOKEN` property. - -```console -neon publish ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = 00a4bdbf147a4394aa1e7f0483802f94658e9ce3 -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- refresh -- -go: creating new go.mod: module github.com/adrienaury/go-template -go: to add module requirements and sums: - go mod tidy ------------------------------------------------- lint -- -Running command: golangci-lint run --fast --enable-all --disable scopelint --disable forbidigo ------------------------------------------------- test -- -? github.com/adrienaury/go-template/cmd/cli [no test files] -? github.com/adrienaury/go-template/cmd/webserver [no test files] -? github.com/adrienaury/go-template/internal/helloservice [no test files] -? github.com/adrienaury/go-template/pkg/nameservice [no test files] ---------------------------------------------- release -- -Calling target 'compile' ---------------------------------------------- compile -- -Building cmd/cli -Building cmd/webserver --------------------------------------------- test-int -- - • run cli (test/suites/01-run-cli.yml) - • no-arguments SUCCESS - • run webserver (test/suites/02-run-webserver.yml) - • no-arguments SUCCESS ---------------------------------------------- publish -- - - • releasing... - • loading config file file=bin/.goreleaser.yml - • loading environment variables - • getting and validating git state - • releasing v0.1.0, commit 00a4bdbf147a4394aa1e7f0483802f94658e9ce3 - • pipe skipped error=disabled during snapshot mode - • parsing tag - • running before hooks - • running go mod download - • setting defaults - • snapshotting - • github/gitlab/gitea releases - • project name - • loading go mod information - • building binaries - • creating source archive - • archives - • linux packages - • snapcraft packages - • calculating checksums - • signing artifacts - • docker images - • artifactory - • blobs - • homebrew tap formula - • scoop manifests - • milestones - • snapshotting - • checking ./dist - • --rm-dist is set, cleaning it up - • loading go mod information - • writing effective config file - • writing config=bin/dist/config.yaml - • generating changelog - • pipe skipped error=not available for snapshots - • building binaries - • building binary=/workspaces/go-template/bin/dist/cmd/cli_windows_386/cli.exe - • building binary=/workspaces/go-template/bin/dist/cmd/cli_darwin_arm64/cli - • building binary=/workspaces/go-template/bin/dist/cmd/cli_linux_arm64/cli - • building binary=/workspaces/go-template/bin/dist/cmd/cli_linux_386/cli - • building binary=/workspaces/go-template/bin/dist/cmd/cli_windows_amd64/cli.exe - • building binary=/workspaces/go-template/bin/dist/cmd/cli_darwin_amd64/cli - • building binary=/workspaces/go-template/bin/dist/cmd/cli_linux_amd64/cli - • building binary=/workspaces/go-template/bin/dist/cmd/webserver_windows_386/webserver.exe - • building binary=/workspaces/go-template/bin/dist/cmd/webserver_linux_amd64/webserver - • building binary=/workspaces/go-template/bin/dist/cmd/webserver_linux_386/webserver - • building binary=/workspaces/go-template/bin/dist/cmd/webserver_windows_amd64/webserver.exe - • building binary=/workspaces/go-template/bin/dist/cmd/webserver_darwin_amd64/webserver - • building binary=/workspaces/go-template/bin/dist/cmd/webserver_darwin_arm64/webserver - • building binary=/workspaces/go-template/bin/dist/cmd/webserver_linux_arm64/webserver - • archives - • creating archive=bin/dist/go-template_v0.1.0-SNAPSHOT-00a4bdb_windows_386.tar.gz - • creating archive=bin/dist/go-template_v0.1.0-SNAPSHOT-00a4bdb_linux_386.tar.gz - • creating archive=bin/dist/go-template_v0.1.0-SNAPSHOT-00a4bdb_darwin_arm64.tar.gz - • creating archive=bin/dist/go-template_v0.1.0-SNAPSHOT-00a4bdb_windows_amd64.tar.gz - • creating archive=bin/dist/go-template_v0.1.0-SNAPSHOT-00a4bdb_linux_amd64.tar.gz - • creating archive=bin/dist/go-template_v0.1.0-SNAPSHOT-00a4bdb_linux_arm64.tar.gz - • creating archive=bin/dist/go-template_v0.1.0-SNAPSHOT-00a4bdb_darwin_amd64.tar.gz - • creating source archive - • linux packages - • snapcraft packages - • calculating checksums - • checksumming file=go-template_v0.1.0-SNAPSHOT-00a4bdb_windows_amd64.tar.gz - • checksumming file=go-template_v0.1.0-SNAPSHOT-00a4bdb_darwin_arm64.tar.gz - • checksumming file=go-template_v0.1.0-SNAPSHOT-00a4bdb_linux_amd64.tar.gz - • checksumming file=go-template_v0.1.0-SNAPSHOT-00a4bdb_darwin_amd64.tar.gz - • checksumming file=go-template_v0.1.0-SNAPSHOT-00a4bdb_linux_arm64.tar.gz - • checksumming file=go-template_v0.1.0-SNAPSHOT-00a4bdb_windows_386.tar.gz - • checksumming file=go-template_v0.1.0-SNAPSHOT-00a4bdb_linux_386.tar.gz - • signing artifacts - • docker images - • publishing - • blobs - • http upload - • custom publisher - • artifactory - • docker images - • pipe skipped error=publishing is disabled - • docker manifests - • pipe skipped error=publishing is disabled - • snapcraft packages - • pipe skipped error=publishing is disabled - • github/gitlab/gitea releases - • pipe skipped error=publishing is disabled - • homebrew tap formula - • scoop manifests - • pipe skipped error=publishing is disabled - • milestones - • pipe skipped error=publishing is disabled - • release succeeded after 1.39s -OK -``` - -The build properties are the same as the [`compile`](#compile) target. Additionaly the `snapshot` property can be set to `true` to run the target without uploading anything to GitHub. - -#### Docker target - -Build docker images locally. - -Dockerfiles and build contexts are configured by the `dockerfiles` map. It'a map with Dockerfiles paths as keys and context paths as values. The default value is `{"Dockerfile": ".", "Dockerfile.webserver", "."}` which will build both Dockerfiles present at the root of this template with a build context equal to the current directory (root directory). - -The images are named according to a few rules : - -- if the source Dockerfile has an extension (e.g. `Dockerfile.webserver`) then the image built will be named `/-` (e.g. : `Dockerfile.webserver` will produce an image named `/-webserver`) -- if the source Dockerfile hasn't an extension (e.g. `Dockerfile`) then the image built will be named `/` - -A prerequisite to this target is that a file named `.dockerhub.yml` at the home directory (`~/.dockerhub.yml`) contains a `DOCKERHUB_USER` property. - -```console -neon docker ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = 9791b0c79b55f2f34517d7e6b64d4900c8c7f2ce -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- docker -- -adrienaury/go-template refactor sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 Less than a second ago 20.6MB -adrienaury/go-template-webserver refactor sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 1 second ago 20.6MB -OK -``` - -To configure the docker target, edit the `build.yml` file and look for the property named `dockerfiles`. - -The `dockerfiles` map can also be passed by the `neon -props` flag. - -```console -$ neon -props '{dockerfiles: {"Dockerfile": "."}}' docker ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = refactor -COMMIT = 9791b0c79b55f2f34517d7e6b64d4900c8c7f2ce -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = no ---------------------------------------------- docker -- -adrienaury/go-template refactor sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 7 minutes ago 20.6MB -OK -``` - -#### Docker-tag target - -Tag docker images. This target will run only if the tag being built is a release tag (vX.Y.Z). - -It will tag all docker images with [semantic docker tags](https://medium.com/@mccode/using-semantic-versioning-for-docker-image-tags-dfde8be06699). - -The build properties are the same as the [`docker`](#docker) target (a `dockerfiles` map). - -```console -$ neon docker-tag ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = v0.2.0 -COMMIT = 00a4bdbf147a4394aa1e7f0483802f94658e9ce3 -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = yes -VERSION = 0.2.0 ---------------------------------------------- docker -- -adrienaury/go-template refactor sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template v0.2.0 sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template-webserver refactor sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver v0.2.0 sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB ------------------------------------------ docker-tag -- -adrienaury/go-template refactor sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template v0 sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template v0.2 sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template v0.2.0 sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template-webserver refactor sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver v0 sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver v0.2 sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver v0.2.0 sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -OK -``` - -Use `-props '{latest: true}'` to include the latest tag. - -```console -$ neon -props '{latest: true}' docker-tag ------------------------------------------------ info -- -MODULE = github.com/adrienaury/go-template -PROJECT = go-template -TAG = v0.2.0 -COMMIT = 00a4bdbf147a4394aa1e7f0483802f94658e9ce3 -DATE = 2021-05-02 -BY = adrienaury@gmail.com -RELEASE = yes -VERSION = 0.2.0 ---------------------------------------------- docker -- -adrienaury/go-template refactor sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template v0.2.0 sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template-webserver refactor sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver v0.2.0 sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB ------------------------------------------ docker-tag -- -adrienaury/go-template latest sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template refactor sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template v0 sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template v0.2 sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template v0.2.0 sha256:d05a1e1e5119aab03f3e3e33fa56d7db66ae5634beb53827b0e69fa168e3c595 20 minutes ago 20.6MB -adrienaury/go-template-webserver latest sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver refactor sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver v0 sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver v0.2 sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -adrienaury/go-template-webserver v0.2.0 sha256:14b333b3679a64b3255e7c88e7211fa4b7502e2664e7b482373b392d5615414c 20 minutes ago 20.6MB -OK -``` - -#### Docker-push target - -Publish tagged docker images to Dockerhub. - -A prerequisite to this target is that a file named `.dockerhub.yml` at the home directory (`~/.dockerhub.yml`) contains a `DOCKERHUB_USER` property and a `DOCKERHUB_PASS` property. - -The build properties are the same as the [`docker`](#docker) target and the [`docker-tag`](#docker-tag) target combined (a `dockerfiles` map and the `latest` boolean). - -#### License target - -Scan binaries for 3rd party licenses and generate a notice file, see the [example notice](NOTICE.md) generated by this target. Under the hood, the [golicense](https://github.com/mitchellh/golicense) tool is used. - -This target work best if a file named `.github.yml` is present at the home directory (`~/.github.yml`) and contains a valid `GITHUB_TOKEN` property. - -By default, this target write in `./NOTICE.md`. Use `-props '{noticefile: "a/different/filename.md"}'` to change the location and name of the notice file. - -License scanning can report an error if an unallowed license is detected. Configure the build property `license`, or use the `neon -props` flag to exclude/include license by [SPDX identifier](https://spdx.org/licenses/), or to map unknown license (see [this link](https://github.com/mitchellh/golicense#configuration-file) for more information). - -Example : `neon -props '{license: {deny: ["BSD-1-Clause"]}}' license` - ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. diff --git a/cmd/cli/main.go b/cmd/cli/main.go deleted file mode 100644 index 8f3225d..0000000 --- a/cmd/cli/main.go +++ /dev/null @@ -1,52 +0,0 @@ -// MIT License -// -// Copyright (c) 2021 Adrien Aury -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package main - -import ( - "fmt" - "os" - - "github.com/adrienaury/go-template/internal/helloservice" - "github.com/adrienaury/go-template/pkg/nameservice" - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -// Provisioned by ldflags. -var ( - name string //nolint: gochecknoglobals - version string //nolint: gochecknoglobals - commit string //nolint: gochecknoglobals - buildDate string //nolint: gochecknoglobals - builtBy string //nolint: gochecknoglobals -) - -func main() { - //nolint: exhaustruct - log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) - - log.Info().Msgf("%v %v (commit=%v date=%v by=%v)", name, version, commit, buildDate, builtBy) - - fmt.Printf("%s", helloservice.Hello(nameservice.GetName())) - fmt.Println() -} diff --git a/cmd/ep/main.go b/cmd/ep/main.go new file mode 100644 index 0000000..7f061ef --- /dev/null +++ b/cmd/ep/main.go @@ -0,0 +1,163 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package main + +import ( + "fmt" + "os" + "runtime" + "strings" + + "github.com/cgi-fr/emporte-piece/internal/infra" + "github.com/cgi-fr/emporte-piece/pkg/filetree" + "github.com/mattn/go-isatty" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "github.com/spf13/cobra" +) + +//nolint:gochecknoglobals +var ( + name string // Provisioned by ldflags. + version string // Provisioned by ldflags. + commit string // Provisioned by ldflags. + buildDate string // Provisioned by ldflags. + builtBy string // Provisioned by ldflags. + + verbosity string + jsonlog bool + debug bool + colormode string + + outputDir string + format string +) + +func main() { + cobra.OnInitialize(initLog) + + rootCmd := &cobra.Command{ //nolint:exhaustruct + Use: fmt.Sprintf("%v path/to/template/dir < context.yaml", name), + Short: "Emporte-pièce", + Long: `Emporte-pièce will help you bootstrap your project.`, + Version: fmt.Sprintf(`%v (commit=%v date=%v by=%v)`, version, commit, buildDate, builtBy), + PersistentPreRun: func(cmd *cobra.Command, args []string) { + log.Info(). + Str("verbosity", verbosity). + Bool("log-json", jsonlog). + Bool("debug", debug). + Str("color", colormode). + Msg("start") + }, + Args: cobra.ExactArgs(1), + Run: func(cmd *cobra.Command, args []string) { + if err := run(cmd, args[0], outputDir, format); err != nil { + log.Fatal().Err(err).Msg("end") + } + }, + PersistentPostRun: func(cmd *cobra.Command, args []string) { + log.Info().Int("return", 0).Msg("end") + }, + } + + rootCmd.PersistentFlags().StringVarP(&verbosity, "verbosity", "v", "info", + "set level of log verbosity : none (0), error (1), warn (2), info (3), debug (4), trace (5)") + rootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "add debug information to logs (very slow)") + rootCmd.PersistentFlags().BoolVar(&jsonlog, "log-json", false, "output logs in JSON format") + rootCmd.PersistentFlags().StringVar(&colormode, "color", "auto", "use colors in log outputs : yes, no or auto") + + rootCmd.PersistentFlags().StringVarP(&outputDir, "output", "o", ".", "output directory") + rootCmd.PersistentFlags(). + StringVarP(&format, "format", "f", "yaml", "format of context data : yaml, json or jsonl (default=yaml)") + + if err := rootCmd.Execute(); err != nil { + log.Err(err).Msg("error when executing command") + os.Exit(1) + } +} + +func run(_ *cobra.Command, templateDir, outputDir, format string) error { + var contextReader infra.ContextReader + + switch strings.ToLower(format) { + case "yaml", "yml": + contextReader = infra.NewContextReaderYAML(os.Stdin) + case "json": + contextReader = infra.NewContextReaderJSON(os.Stdin) + case "jsonl": + contextReader = infra.NewContextReaderJSONL(os.Stdin) + } + + for contextReader.HasNext() { + context, err := contextReader.Next() + if err != nil { + return fmt.Errorf("%w", err) + } + + driver := filetree.NewDriver(infra.FileSystem{}) + + err = driver.Develop(templateDir, outputDir, context) + if err != nil { + return fmt.Errorf("%w", err) + } + } + + return nil +} + +func initLog() { + color := false + + switch strings.ToLower(colormode) { + case "auto": + if isatty.IsTerminal(os.Stdout.Fd()) && runtime.GOOS != "windows" { + color = true + } + case "yes", "true", "1", "on", "enable": + color = true + } + + if jsonlog { + log.Logger = zerolog.New(os.Stderr) + } else { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, NoColor: !color}) //nolint:exhaustruct + } + + if debug { + log.Logger = log.Logger.With().Caller().Logger() + } + + setVerbosity() +} + +func setVerbosity() { + switch verbosity { + case "trace", "5": + zerolog.SetGlobalLevel(zerolog.TraceLevel) + case "debug", "4": + zerolog.SetGlobalLevel(zerolog.DebugLevel) + case "info", "3": + zerolog.SetGlobalLevel(zerolog.InfoLevel) + case "warn", "2": + zerolog.SetGlobalLevel(zerolog.WarnLevel) + case "error", "1": + zerolog.SetGlobalLevel(zerolog.ErrorLevel) + default: + zerolog.SetGlobalLevel(zerolog.Disabled) + } +} diff --git a/cmd/webserver/main.go b/cmd/webserver/main.go deleted file mode 100644 index 52e31aa..0000000 --- a/cmd/webserver/main.go +++ /dev/null @@ -1,62 +0,0 @@ -// MIT License -// -// Copyright (c) 2021 Adrien Aury -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package main - -import ( - "fmt" - "net/http" - "os" - - "github.com/adrienaury/go-template/internal/helloservice" - "github.com/adrienaury/go-template/pkg/nameservice" - "github.com/gorilla/mux" - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" -) - -// Provisioned by ldflags. -var ( - name string //nolint: gochecknoglobals - version string //nolint: gochecknoglobals - commit string //nolint: gochecknoglobals - buildDate string //nolint: gochecknoglobals - builtBy string //nolint: gochecknoglobals -) - -func main() { - //nolint: exhaustruct - log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) - log.Info().Msgf("%v %v (commit=%v date=%v by=%v)", name, version, commit, buildDate, builtBy) - log.Info().Msg("This is the web server.") - - fmt.Printf("%s", helloservice.Hello(nameservice.GetName())) - fmt.Println() - - r := mux.NewRouter() - r.HandleFunc("/version", VersionHandler) -} - -func VersionHandler(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - fmt.Printf("%v %v (commit=%v date=%v by=%v)\n", name, version, commit, buildDate, builtBy) -} diff --git a/githooks/commit-msg b/githooks/commit-msg old mode 100755 new mode 100644 diff --git a/go.mod b/go.mod index 7eb1045..054883f 100644 --- a/go.mod +++ b/go.mod @@ -1,14 +1,34 @@ -module github.com/adrienaury/go-template +module github.com/cgi-fr/emporte-piece go 1.21 require ( - github.com/gorilla/mux v1.8.0 + github.com/Masterminds/sprig/v3 v3.2.3 + github.com/alediaferia/prefixmap v1.0.1 + github.com/mattn/go-isatty v0.0.14 github.com/rs/zerolog v1.28.0 + github.com/spf13/cobra v1.7.0 + github.com/stretchr/testify v1.8.4 + golang.org/x/text v0.13.0 + gopkg.in/yaml.v3 v3.0.1 ) require ( + github.com/Masterminds/goutils v1.1.1 // indirect + github.com/Masterminds/semver/v3 v3.2.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/google/uuid v1.1.1 // indirect + github.com/huandu/xstrings v1.3.3 // indirect + github.com/imdario/mergo v0.3.11 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/mattn/go-colorable v0.1.12 // indirect - github.com/mattn/go-isatty v0.0.14 // indirect - golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect + github.com/mitchellh/copystructure v1.0.0 // indirect + github.com/mitchellh/reflectwalk v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/shopspring/decimal v1.2.0 // indirect + github.com/spf13/cast v1.3.1 // indirect + github.com/spf13/pflag v1.0.5 // indirect + golang.org/x/crypto v0.3.0 // indirect + golang.org/x/sys v0.5.0 // indirect + gopkg.in/alediaferia/stackgo.v1 v1.1.1 // indirect ) diff --git a/go.sum b/go.sum index cccaefd..a9c328b 100644 --- a/go.sum +++ b/go.sum @@ -1,16 +1,94 @@ +github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g= +github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= +github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA= +github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= +github.com/alediaferia/prefixmap v1.0.1 h1:MnlMtO77dZkDgTSaQeiGW1W2NOFTSKcUh4rl57EqcIc= +github.com/alediaferia/prefixmap v1.0.1/go.mod h1:OoVudMbSvqhz1WD0+QMmd8vhye19e3k51n69J1dr3+0= github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= -github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/huandu/xstrings v1.3.3 h1:/Gcsuc1x8JVbJ9/rlye4xZnVAbEkGauT8lbebqcQws4= +github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA= +github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= +github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY= github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= +github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A= +golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/alediaferia/stackgo.v1 v1.1.1 h1:htUbPM2OVv8njXgNngn7sXYNQXMgAfRfCYtugsIpGXo= +gopkg.in/alediaferia/stackgo.v1 v1.1.1/go.mod h1:zCaxPo2py6RpzzpTw6cgT365QmkJ+4ySaVX5ZCOYLIQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/helloservice/service.go b/internal/helloservice/service.go deleted file mode 100644 index e38f6c4..0000000 --- a/internal/helloservice/service.go +++ /dev/null @@ -1,27 +0,0 @@ -// MIT License -// -// Copyright (c) 2021 Adrien Aury -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package helloservice - -func Hello(name string) string { - return "Hello " + name + "!" -} diff --git a/internal/infra/contextReader.go b/internal/infra/contextReader.go new file mode 100644 index 0000000..fe3ae06 --- /dev/null +++ b/internal/infra/contextReader.go @@ -0,0 +1,27 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package infra + +import "errors" + +type ContextReader interface { + HasNext() bool + Next() (any, error) +} + +var ErrContextReaderEmpty = errors.New("context reader is empty") diff --git a/internal/infra/contextReaderJSON.go b/internal/infra/contextReaderJSON.go new file mode 100644 index 0000000..d08e04e --- /dev/null +++ b/internal/infra/contextReaderJSON.go @@ -0,0 +1,66 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package infra + +import ( + "encoding/json" + "fmt" + "io" + "os" +) + +type ContextReaderJSON struct { + read bool + input io.Reader +} + +func NewContextReaderJSON(input io.Reader) *ContextReaderJSON { + return &ContextReaderJSON{read: false, input: input} +} + +func NewContextReaderJSONFromFile(filepath string) (*ContextReaderJSON, error) { + input, err := os.Open(filepath) + if err != nil { + return nil, fmt.Errorf("error opening file: %w", err) + } + + return NewContextReaderJSON(input), nil +} + +func (cr *ContextReaderJSON) HasNext() bool { + return !cr.read +} + +func (cr *ContextReaderJSON) Next() (any, error) { + if cr.read { + return nil, ErrContextReaderEmpty + } + + bytes, err := io.ReadAll(cr.input) + if err != nil { + return nil, fmt.Errorf("error reading JSON input: %w", err) + } + + context := make(map[string]any) + + if err := json.Unmarshal(bytes, &context); err != nil { + return nil, fmt.Errorf("error parsing JSON input: %w", err) + } + + return context, nil +} diff --git a/internal/infra/contextReaderJSONL.go b/internal/infra/contextReaderJSONL.go new file mode 100644 index 0000000..6f1d40b --- /dev/null +++ b/internal/infra/contextReaderJSONL.go @@ -0,0 +1,75 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package infra + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "os" +) + +type ContextReaderJSONL struct { + input *bufio.Scanner + err error + value []byte +} + +func NewContextReaderJSONL(input io.Reader) *ContextReaderJSONL { + return &ContextReaderJSONL{ + input: bufio.NewScanner(input), + err: nil, + value: nil, + } +} + +func NewContextReaderJSONLFromFile(filepath string) (*ContextReaderJSON, error) { + input, err := os.Open(filepath) + if err != nil { + return nil, fmt.Errorf("error opening file: %w", err) + } + + return NewContextReaderJSON(input), nil +} + +func (cr *ContextReaderJSONL) HasNext() bool { + if !cr.input.Scan() { + cr.err = cr.input.Err() + + return false + } + + cr.value = cr.input.Bytes() + + return cr.err == nil && cr.value != nil +} + +func (cr *ContextReaderJSONL) Next() (any, error) { + if cr.err != nil { + return nil, cr.err + } + + context := make(map[string]any) + + if err := json.Unmarshal(cr.value, &context); err != nil { + return nil, fmt.Errorf("error parsing JSON input: %w", err) + } + + return context, nil +} diff --git a/internal/infra/contextReaderYAML.go b/internal/infra/contextReaderYAML.go new file mode 100644 index 0000000..4ec23ee --- /dev/null +++ b/internal/infra/contextReaderYAML.go @@ -0,0 +1,69 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package infra + +import ( + "fmt" + "io" + "os" + + "gopkg.in/yaml.v3" +) + +type ContextReaderYAML struct { + read bool + input io.Reader +} + +func NewContextReaderYAML(input io.Reader) *ContextReaderYAML { + return &ContextReaderYAML{read: false, input: input} +} + +func NewContextReaderYAMLFromFile(filepath string) (*ContextReaderYAML, error) { + input, err := os.Open(filepath) + if err != nil { + return nil, fmt.Errorf("error opening file: %w", err) + } + + return NewContextReaderYAML(input), nil +} + +func (cr *ContextReaderYAML) HasNext() bool { + return !cr.read +} + +func (cr *ContextReaderYAML) Next() (any, error) { + if cr.read { + return nil, ErrContextReaderEmpty + } + + cr.read = true + + bytes, err := io.ReadAll(cr.input) + if err != nil { + return nil, fmt.Errorf("error reading JSON input: %w", err) + } + + context := make(map[string]any) + + if err := yaml.Unmarshal(bytes, &context); err != nil { + return nil, fmt.Errorf("error parsing JSON input: %w", err) + } + + return context, nil +} diff --git a/internal/infra/fileSystem.go b/internal/infra/fileSystem.go new file mode 100644 index 0000000..27a2ce5 --- /dev/null +++ b/internal/infra/fileSystem.go @@ -0,0 +1,41 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package infra + +import ( + "io/fs" + "os" +) + +type FileSystem struct{} + +func (fsys FileSystem) ReadDir(name string) ([]fs.DirEntry, error) { + return os.ReadDir(name) //nolint:wrapcheck +} + +func (fsys FileSystem) WriteFile(name string, data []byte, perm fs.FileMode) error { + return os.WriteFile(name, data, perm) //nolint:wrapcheck +} + +func (fsys FileSystem) Mkdir(name string, perm fs.FileMode) error { + return os.MkdirAll(name, perm) //nolint:wrapcheck +} + +func (fsys FileSystem) Open(name string) (fs.File, error) { + return os.Open(name) //nolint:wrapcheck +} diff --git a/pkg/filetree/defaults.go b/pkg/filetree/defaults.go new file mode 100644 index 0000000..e37c3d8 --- /dev/null +++ b/pkg/filetree/defaults.go @@ -0,0 +1,119 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package filetree + +import ( + "io/fs" + "os" + "path" + "strings" + + "github.com/alediaferia/prefixmap" + "github.com/rs/zerolog/log" +) + +type InMemoryFileSystem struct { + disk *prefixmap.PrefixMap +} + +func NewInMemoryFileSystem() *InMemoryFileSystem { + return &InMemoryFileSystem{ + disk: prefixmap.New(), + } +} + +func (fsys *InMemoryFileSystem) ReadDir(name string) ([]fs.DirEntry, error) { + result := []fs.DirEntry{} + + if !strings.HasSuffix(name, string(os.PathSeparator)) { + name += string(os.PathSeparator) + } + + for _, item := range fsys.disk.GetByPrefix(name) { + file := item.(*File) //nolint:forcetypeassert + if strings.Count(strings.TrimPrefix(file.path, name), string(os.PathSeparator)) == 0 { + result = append(result, file) + } + } + + log.Trace().Str("param", name).Interface("result", result).Msg("InMemoryFileSystem - ReadDir") + + return result, nil +} + +func (fsys *InMemoryFileSystem) WriteFile(name string, data []byte, perm fs.FileMode) error { + var file *File + + files := fsys.disk.Get(name) + if len(files) == 0 { + file = NewFile(name, false, perm) + + for dir, _ := path.Split(name); len(dir) > 0; dir, _ = path.Split(dir) { + dir = path.Clean(dir) + if err := fsys.Mkdir(dir, fs.ModePerm); err != nil { + return err + } + } + } else { + file = files[0].(*File) //nolint:forcetypeassert + } + + if _, err := file.Write(data); err != nil { + return err + } + + fsys.disk.Replace(name, file) + + return nil +} + +func (fsys *InMemoryFileSystem) Mkdir(name string, perm fs.FileMode) error { + var file *File + + name = strings.TrimSuffix(name, string(os.PathSeparator)) + + files := fsys.disk.Get(name) + if len(files) == 0 { + file = NewFile(name, true, perm) + } else { + file = files[0].(*File) //nolint:forcetypeassert + } + + if !file.isDir { + return fs.ErrExist + } + + log.Trace().Str("param", name).Msg("InMemoryFileSystem - MkDir") + + fsys.disk.Replace(name, file) + + return nil +} + +func (fsys *InMemoryFileSystem) Open(name string) (fs.File, error) { + var file *File + + files := fsys.disk.Get(name) + if len(files) == 0 { + return nil, os.ErrNotExist + } + + file = files[0].(*File) //nolint:forcetypeassert + + return file, nil +} diff --git a/pkg/filetree/driven.go b/pkg/filetree/driven.go new file mode 100644 index 0000000..dc9996d --- /dev/null +++ b/pkg/filetree/driven.go @@ -0,0 +1,27 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package filetree + +import "io/fs" + +type FileSystem interface { + ReadDir(name string) ([]fs.DirEntry, error) + WriteFile(name string, data []byte, perm fs.FileMode) error + Mkdir(name string, perm fs.FileMode) error + Open(name string) (fs.File, error) +} diff --git a/pkg/filetree/driver.go b/pkg/filetree/driver.go new file mode 100644 index 0000000..dfec4b2 --- /dev/null +++ b/pkg/filetree/driver.go @@ -0,0 +1,101 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package filetree + +import ( + "fmt" + "io" + "os" + "path" + + "github.com/cgi-fr/emporte-piece/pkg/jsonpath" + "github.com/cgi-fr/emporte-piece/pkg/template" + "github.com/rs/zerolog/log" +) + +type Driver struct { + fs FileSystem +} + +func NewDriver(fsys FileSystem) Driver { + return Driver{ + fs: fsys, + } +} + +func (d Driver) Develop(templatePath string, targetPath string, contexts ...any) error { + files, _ := d.fs.ReadDir(templatePath) + for _, file := range files { + rs, err := jsonpath.Develop(file.Name(), contexts...) + if err != nil { + return fmt.Errorf("%w", err) + } + + for _, devpath := range rs { + subTemplatePath := path.Join(templatePath, file.Name()) + subTargetPath := path.Join(targetPath, devpath.Selected) + + log.Info().Str("from", subTemplatePath).Msg("generating " + subTargetPath) + + if file.IsDir() { + if err := d.developDir(subTargetPath, subTemplatePath, devpath); err != nil { + return err + } + } else { + if err := d.developFile(subTargetPath, subTemplatePath, devpath); err != nil { + return err + } + } + } + } + + return nil +} + +func (d Driver) developFile(subTargetPath string, subTemplatePath string, devpath jsonpath.ResultString) error { + tmplFile, err := d.fs.Open(subTemplatePath) + if err != nil { + return fmt.Errorf("%w", err) + } + + tmplContent, err := io.ReadAll(tmplFile) + if err != nil { + return fmt.Errorf("%w", err) + } + + content, err := template.Generate(string(tmplContent), devpath.Stack) + if err != nil { + return fmt.Errorf("%w", err) + } + + if err := d.fs.WriteFile(subTargetPath, content, os.ModePerm); err != nil { + return fmt.Errorf("%w", err) + } + + return nil +} + +func (d Driver) developDir(subTargetPath string, subTemplatePath string, devpath jsonpath.ResultString) error { + if err := d.fs.Mkdir(subTargetPath, os.ModePerm); err != nil && !os.IsExist(err) { + return fmt.Errorf("%w", err) + } else if err := d.Develop(subTemplatePath, subTargetPath, devpath.Stack...); err != nil { + return fmt.Errorf("%w", err) + } + + return nil +} diff --git a/pkg/filetree/driver_test.go b/pkg/filetree/driver_test.go new file mode 100644 index 0000000..8a9e759 --- /dev/null +++ b/pkg/filetree/driver_test.go @@ -0,0 +1,167 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package filetree_test + +import ( + "io" + "os" + "testing" + + "github.com/cgi-fr/emporte-piece/pkg/filetree" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "github.com/stretchr/testify/assert" + "gopkg.in/yaml.v3" +) + +func TestMain(m *testing.M) { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, NoColor: true}) //nolint:exhaustruct + + zerolog.SetGlobalLevel(zerolog.InfoLevel) + + code := m.Run() + + os.Exit(code) +} + +func TestDevelopContext(t *testing.T) { + t.Parallel() + + fsys := filetree.NewInMemoryFileSystem() + + content := `hello {{$person := Stack -2}}{{$person.name}}` + + assert.NoError(t, fsys.Mkdir("template", os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{persons.[].name}}.txt", []byte(content), os.ModePerm)) + assert.NoError(t, fsys.Mkdir("result", os.ModePerm)) + + context := map[string]any{ + "persons": []map[string]any{ + { + "name": "John", + }, + }, + } + + driver := filetree.NewDriver(fsys) + + assert.NoError(t, driver.Develop("template", "result", context)) + + f, err := fsys.Open("result/John.txt") + assert.NoError(t, err) + + b, err := io.ReadAll(f) + assert.NoError(t, err) + + assert.Equal(t, "hello John", string(b)) +} + +//nolint:lll,funlen +func TestStack(t *testing.T) { + t.Parallel() + + context := map[string]any{} + + yamlb, _ := os.ReadFile("testdata/context_1.yaml") + _ = yaml.Unmarshal(yamlb, context) + + content0 := `{{Stack 0}}` + content1 := `{{Stack 1}}` + content2 := `{{Stack 2}}` + content3 := `{{Stack 3}}` + content4 := `{{Stack 4}}` + content5 := `{{Stack 5}}` + content6 := `{{Stack 6}}` + content7 := `{{Stack 7}}` + contentM1 := `{{Stack -1}}` + contentM2 := `{{Stack -2}}` + contentM3 := `{{Stack -3}}` + + fsys := filetree.NewInMemoryFileSystem() + + assert.NoError(t, fsys.Mkdir("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}", os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stack0.txt", []byte(content0), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stack1.txt", []byte(content1), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stack2.txt", []byte(content2), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stack3.txt", []byte(content3), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stack4.txt", []byte(content4), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stack5.txt", []byte(content5), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stack6.txt", []byte(content6), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stack7.txt", []byte(content7), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stackM1.txt", []byte(contentM1), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stackM2.txt", []byte(contentM2), os.ModePerm)) + assert.NoError(t, fsys.WriteFile("template/{{departements.[].nom}}/{{$[-2].villes.[].nom}}/{{$[-2].restaurants.[].nom}}/stackM3.txt", []byte(contentM3), os.ModePerm)) + + driver := filetree.NewDriver(fsys) + assert.NoError(t, driver.Develop("template/", "result/", context)) + + // full context on stack 0 + file0, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stack0.txt") + file0b, _ := io.ReadAll(file0) + assert.Equal(t, "map[departements:[map[nom:Ain numero:1 villes:[map[nom:Bourg-en-Bresse population:41681 restaurants:[map[nom:Auberge Bressane] map[nom:Mets et Vins] map[nom:Place Bernard]]] map[nom:Oyonnax population:22271 restaurants:[map[nom:La Renaissance] map[nom:Les saveurs d'Italie] map[nom:Le Chalet Gourmand]]]]] map[nom:Aisne numero:2 villes:[map[nom:Saint-Quentin population:53100 restaurants:[map[nom:Al Taglio Pizza] map[nom:Chez Jean] map[nom:Au Made In France]]] map[nom:Soissons population:43580 restaurants:[map[nom:Le Bouche à Oreilles] map[nom:Léon] map[nom:La Cathédrale]]]]]]]", string(file0b)) + + // departements list on stack 1 + file1, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stack1.txt") + file1b, _ := io.ReadAll(file1) + assert.Equal(t, "[map[nom:Ain numero:1 villes:[map[nom:Bourg-en-Bresse population:41681 restaurants:[map[nom:Auberge Bressane] map[nom:Mets et Vins] map[nom:Place Bernard]]] map[nom:Oyonnax population:22271 restaurants:[map[nom:La Renaissance] map[nom:Les saveurs d'Italie] map[nom:Le Chalet Gourmand]]]]] map[nom:Aisne numero:2 villes:[map[nom:Saint-Quentin population:53100 restaurants:[map[nom:Al Taglio Pizza] map[nom:Chez Jean] map[nom:Au Made In France]]] map[nom:Soissons population:43580 restaurants:[map[nom:Le Bouche à Oreilles] map[nom:Léon] map[nom:La Cathédrale]]]]]]", string(file1b)) + + // first departement on stack 2 + file2, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stack2.txt") + file2b, _ := io.ReadAll(file2) + assert.Equal(t, "map[nom:Ain numero:1 villes:[map[nom:Bourg-en-Bresse population:41681 restaurants:[map[nom:Auberge Bressane] map[nom:Mets et Vins] map[nom:Place Bernard]]] map[nom:Oyonnax population:22271 restaurants:[map[nom:La Renaissance] map[nom:Les saveurs d'Italie] map[nom:Le Chalet Gourmand]]]]]", string(file2b)) + + // cities of first departement on stack 3 + file3, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stack3.txt") + file3b, _ := io.ReadAll(file3) + assert.Equal(t, "[map[nom:Bourg-en-Bresse population:41681 restaurants:[map[nom:Auberge Bressane] map[nom:Mets et Vins] map[nom:Place Bernard]]] map[nom:Oyonnax population:22271 restaurants:[map[nom:La Renaissance] map[nom:Les saveurs d'Italie] map[nom:Le Chalet Gourmand]]]]", string(file3b)) + + // first city of first departement on stack 4 + file4, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stack4.txt") + file4b, _ := io.ReadAll(file4) + assert.Equal(t, "map[nom:Bourg-en-Bresse population:41681 restaurants:[map[nom:Auberge Bressane] map[nom:Mets et Vins] map[nom:Place Bernard]]]", string(file4b)) + + // restaurants of first city of first departement on stack 5 + file5, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stack5.txt") + file5b, _ := io.ReadAll(file5) + assert.Equal(t, "[map[nom:Auberge Bressane] map[nom:Mets et Vins] map[nom:Place Bernard]]", string(file5b)) + + // first restaurant of first city of first departement on stack 6 + file6, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stack6.txt") + file6b, _ := io.ReadAll(file6) + assert.Equal(t, "map[nom:Auberge Bressane]", string(file6b)) + + // name of first restaurant of first city of first departement on stack 7 + file7, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stack7.txt") + file7b, _ := io.ReadAll(file7) + assert.Equal(t, "Auberge Bressane", string(file7b)) + + // name of first restaurant of first city of first departement on stack -1 + fileM1, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stackM1.txt") + fileM1b, _ := io.ReadAll(fileM1) + assert.Equal(t, "Auberge Bressane", string(fileM1b)) + + // first restaurant of first city of first departement on stack -2 + fileM2, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stackM2.txt") + fileM2b, _ := io.ReadAll(fileM2) + assert.Equal(t, "map[nom:Auberge Bressane]", string(fileM2b)) + + // restaurants of first city of first departement on stack -3 + fileM3, _ := fsys.Open("result/Ain/Bourg-en-Bresse/Auberge Bressane/stackM3.txt") + fileM3b, _ := io.ReadAll(fileM3) + assert.Equal(t, "[map[nom:Auberge Bressane] map[nom:Mets et Vins] map[nom:Place Bernard]]", string(fileM3b)) +} diff --git a/pkg/filetree/model.go b/pkg/filetree/model.go new file mode 100644 index 0000000..aea58b1 --- /dev/null +++ b/pkg/filetree/model.go @@ -0,0 +1,72 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package filetree + +import ( + "bytes" + "io/fs" + "path" +) + +type File struct { + path string + isDir bool + mode fs.FileMode + content *bytes.Buffer +} + +func NewFile(path string, isDir bool, mode fs.FileMode) *File { + return &File{ + path: path, + isDir: isDir, + mode: mode, + content: new(bytes.Buffer), + } +} + +func (f *File) Name() string { + return path.Base(f.path) +} + +func (f *File) IsDir() bool { + return f.isDir +} + +func (f *File) Type() fs.FileMode { + return f.mode +} + +func (f *File) Info() (fs.FileInfo, error) { + return nil, nil +} + +func (f *File) Read(p []byte) (int, error) { + return f.content.Read(p) //nolint:wrapcheck +} + +func (f *File) Write(p []byte) (int, error) { + return f.content.Write(p) //nolint:wrapcheck +} + +func (f *File) Stat() (fs.FileInfo, error) { + return nil, nil +} + +func (f *File) Close() error { + return nil +} diff --git a/pkg/filetree/testdata/context_1.yaml b/pkg/filetree/testdata/context_1.yaml new file mode 100644 index 0000000..c40bd7b --- /dev/null +++ b/pkg/filetree/testdata/context_1.yaml @@ -0,0 +1,31 @@ +departements: + - numero: 1 + nom: "Ain" + villes: + - nom: "Bourg-en-Bresse" + population: 41681 + restaurants: + - nom: "Auberge Bressane" + - nom: "Mets et Vins" + - nom: "Place Bernard" + - nom: "Oyonnax" + population: 22271 + restaurants: + - nom: "La Renaissance" + - nom: "Les saveurs d'Italie" + - nom: "Le Chalet Gourmand" + - numero: 2 + nom: "Aisne" + villes: + - nom: "Saint-Quentin" + population: 53100 + restaurants: + - nom: "Al Taglio Pizza" + - nom: "Chez Jean" + - nom: "Au Made In France" + - nom: "Soissons" + population: 43580 + restaurants: + - nom: "Le Bouche à Oreilles" + - nom: "Léon" + - nom: "La Cathédrale" diff --git a/pkg/jsonpath/driver.go b/pkg/jsonpath/driver.go new file mode 100644 index 0000000..e9b05a0 --- /dev/null +++ b/pkg/jsonpath/driver.go @@ -0,0 +1,229 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package jsonpath + +import ( + "fmt" + "regexp" + "strconv" + "strings" +) + +var patternStack = regexp.MustCompile(`^\$\[(-?\d+)\]$`) + +func Get(path string, contexts ...any) ([]Result, error) { + context := contexts[0] + paths := strings.Split(path, ".") + + if paths[0][0] == '$' { + context, contexts = refreshContext(paths, contexts) + paths = paths[1:] + } + + return get(context, paths, contexts) +} + +func refreshContext(paths []string, contexts []any) (any, []any) { + if patternStack.MatchString(paths[0]) { + stackindexstr := patternStack.FindStringSubmatch(paths[0])[1] + stackindex, _ := strconv.Atoi(stackindexstr) + + if stackindex < 0 { + return contexts[len(contexts)+stackindex], contexts[:len(contexts)+stackindex+1] + } + + return contexts[stackindex], contexts[:stackindex] + } + + return contexts[len(contexts)-1], contexts[:len(contexts)-1] +} + +func get(context any, paths []string, stack []any) ([]Result, error) { + path := paths[0] + + if len(paths) == 1 { + if obj, ok := context.(map[string]any); ok { + return []Result{{Selected: obj[path], Stack: append(stack, obj[path])}}, nil + } + + return nil, nil + } + + if path == "[]" || path == "*" { + if array, ok := context.([]map[string]any); ok { + return getArrayMap(array, paths, stack) + } + + if array, ok := context.([]any); ok { + return getArrayAny(array, paths, stack) + } + } + + if obj, ok := context.(map[string]any); ok { + return get(obj[path], paths[1:], append(stack, obj[path])) + } + + return nil, nil +} + +func getArrayMap(array []map[string]any, paths []string, stack []any) ([]Result, error) { + allResults := []Result{} + + for _, item := range array { + newstack := make([]any, len(stack)+1) + copy(newstack, stack) + newstack[len(stack)] = item + + results, err := get(item, paths[1:], newstack) + if err != nil { + return nil, err + } + + allResults = append(allResults, results...) + } + + return allResults, nil +} + +func getArrayAny(array []any, paths []string, stack []any) ([]Result, error) { + allResults := []Result{} + + for _, item := range array { + newstack := make([]any, len(stack)+1) + copy(newstack, stack) + newstack[len(stack)] = item + + results, err := get(item, paths[1:], newstack) + if err != nil { + return nil, err + } + + allResults = append(allResults, results...) + } + + return allResults, nil +} + +func Develop(template string, contexts ...any) ([]ResultString, error) { + resultstrings := []ResultString{} + path, pathBegin, pathEnd := extractPath(template) + + if len(path) == 0 { + return []ResultString{ + { + Selected: template, + Stack: contexts, + }, + }, nil + } + + results, err := Get(path, contexts...) + if err != nil { + return resultstrings, err + } + + for _, result := range results { + selectedString := strings.Builder{} + selectedString.WriteString(template[0:pathBegin]) + selectedString.WriteString(toString(result.Selected)) + selectedString.WriteString(template[pathEnd:]) + resultstring := ResultString{ + Selected: selectedString.String(), + Stack: result.Stack, + } + resultstrings = append(resultstrings, resultstring) + } + + return resultstrings, nil +} + +//nolint:gomnd +func extractPath(template string) (string, int, int) { + var step, pathBegin, pathEnd int + + path := strings.Builder{} + + for index, char := range template { + switch step { + case 0: + if char == '{' { + step = 1 + pathBegin = index + } + case 1: + if char == '{' { + step = 2 + } else { + step = 0 + } + case 2: + if char == '}' { + step = 3 + } else { + path.WriteRune(char) + } + case 3: + if char == '}' { + pathEnd = index + 1 + + return path.String(), pathBegin, pathEnd + } + + path.WriteRune('}') + path.WriteRune(char) + + step = 2 + } + } + + return "", 0, 0 +} + +//nolint:gocyclop,cyclop +func toString(v any) string { + switch vTyped := v.(type) { + case string: + return vTyped + case fmt.Stringer: + return vTyped.String() + case int: + return strconv.Itoa(vTyped) + case int64: + return strconv.FormatInt(vTyped, 10) + case int32: + return strconv.FormatInt(int64(vTyped), 10) + case int16: + return strconv.FormatInt(int64(vTyped), 10) + case int8: + return strconv.FormatInt(int64(vTyped), 10) + case uint: + return strconv.FormatUint(uint64(vTyped), 10) + case uint64: + return strconv.FormatUint(vTyped, 10) + case uint32: + return strconv.FormatUint(uint64(vTyped), 10) + case uint16: + return strconv.FormatUint(uint64(vTyped), 10) + case uint8: + return strconv.FormatUint(uint64(vTyped), 10) + case bool: + return strconv.FormatBool(vTyped) + default: + return fmt.Sprintf("%v", vTyped) + } +} diff --git a/pkg/jsonpath/driver_test.go b/pkg/jsonpath/driver_test.go new file mode 100644 index 0000000..71dab87 --- /dev/null +++ b/pkg/jsonpath/driver_test.go @@ -0,0 +1,90 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package jsonpath_test + +import ( + "fmt" + "testing" + + "github.com/cgi-fr/emporte-piece/pkg/jsonpath" + "github.com/stretchr/testify/assert" +) + +func TestDevelopLen(t *testing.T) { + t.Parallel() + + //nolint:lll + testdatas := []struct { + template string + context any + expectedLen int + }{ + {"hello {{name}} !", map[string]any{"name": "world"}, 1}, + {"hello {{persons.[].name}} !", map[string]any{"persons": []map[string]any{{"name": "world"}, {"name": "space"}}}, 1}, + {"hello {{$.persons.[].name}} !", map[string]any{"persons": []map[string]any{{"name": "world"}, {"name": "space"}}}, 1}, + {"hello {{$[-1].persons.[].name}} !", map[string]any{"persons": []map[string]any{{"name": "world"}, {"name": "space"}}}, 1}, + } + + for _, td := range testdatas { + t.Run(fmt.Sprintf("%v", td.template), func(t *testing.T) { + t.Parallel() + + res, err := jsonpath.Develop("hello {{name}} !", map[string]any{"name": "world"}) + + assert.NoError(t, err) + assert.Len(t, res, 1) + }) + } +} + +//nolint:golint,revive,stylecheck +func TestDevelopContext(t *testing.T) { + t.Parallel() + + column_1_name := "column_1" + column_2_name := "column_2" + column_3_name := "column_3" + column_4_name := "column_4" + + column_1 := map[string]any{"name": column_1_name} + column_2 := map[string]any{"name": column_2_name} + column_3 := map[string]any{"name": column_3_name} + column_4 := map[string]any{"name": column_4_name} + + table_1_columns := []map[string]any{column_1, column_2} + table_2_columns := []map[string]any{column_3, column_4} + + table_1_name := "table_1" + table_2_name := "table_2" + + table_1 := map[string]any{"name": table_1_name, "columns": table_1_columns} + table_2 := map[string]any{"name": table_2_name, "columns": table_2_columns} + + tables := []map[string]any{table_1, table_2} + + root := map[string]any{"tables": tables} + + stack := []any{root, tables, table_2, table_2_name} + + res, err := jsonpath.Develop("{{$[-2].columns.[].name}}.txt", stack...) + + assert.NoError(t, err) + assert.Len(t, res, 2) + assert.Equal(t, "column_3.txt", res[0].Selected) + assert.Equal(t, "column_4.txt", res[1].Selected) +} diff --git a/pkg/jsonpath/model.go b/pkg/jsonpath/model.go new file mode 100644 index 0000000..ab2403f --- /dev/null +++ b/pkg/jsonpath/model.go @@ -0,0 +1,28 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package jsonpath + +type Result struct { + Selected any + Stack []any +} + +type ResultString struct { + Selected string + Stack []any +} diff --git a/pkg/nameservice/service.go b/pkg/nameservice/service.go deleted file mode 100644 index 28f073c..0000000 --- a/pkg/nameservice/service.go +++ /dev/null @@ -1,27 +0,0 @@ -// MIT License -// -// Copyright (c) 2021 Adrien Aury -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -package nameservice - -func GetName() string { - return "World" -} diff --git a/pkg/template/driver.go b/pkg/template/driver.go new file mode 100644 index 0000000..f680936 --- /dev/null +++ b/pkg/template/driver.go @@ -0,0 +1,76 @@ +// Copyright (C) 2023 CGI France +// +// This file is part of emporte-piece. +// +// Emporte-piece 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. +// +// Emporte-piece 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 emporte-piece. If not, see . + +package template + +import ( + "bytes" + "fmt" + "strings" + "text/template" + "unicode" + + "github.com/Masterminds/sprig/v3" + "golang.org/x/text/runes" + "golang.org/x/text/transform" + "golang.org/x/text/unicode/norm" +) + +func Generate(tmplstr string, stack []any) ([]byte, error) { + funcmap := generateFuncMap() + + funcmap["Stack"] = generateStackFunc(stack) + + tmpl, err := template.New("template").Funcs(sprig.TxtFuncMap()).Funcs(funcmap).Parse(tmplstr) + if err != nil { + return nil, fmt.Errorf("%w", err) + } + + result := &bytes.Buffer{} + err = tmpl.Execute(result, stack[0]) + + return result.Bytes(), err +} + +func generateFuncMap() template.FuncMap { + funcMap := template.FuncMap{} + + funcMap["ToUpper"] = strings.ToUpper + funcMap["ToLower"] = strings.ToLower + funcMap["NoAccent"] = rmAcc + + return funcMap +} + +func generateStackFunc(stack []any) func(index int) any { + return func(index int) any { + if index < 0 { + return stack[len(stack)+index] + } + + return stack[index] + } +} + +// rmAcc removes accents from string +// Function derived from: http://blog.golang.org/normalization +func rmAcc(s string) string { + t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) + result, _, _ := transform.String(t, s) + + return result +} diff --git a/test/suites/01-run-cli.yml b/test/suites/01-run-cli.yml index 0279bd6..fc820b7 100644 --- a/test/suites/01-run-cli.yml +++ b/test/suites/01-run-cli.yml @@ -1,10 +1,15 @@ # Venom Test Suite definition # Check Venom documentation for more information : https://github.com/ovh/venom -name: run cli +name: run emporte piece testcases: - name: no arguments steps: - - script: cli + - script: ep + assertions: + - result.code ShouldEqual 1 + + - name: simple template + steps: + - script: ep --output 01-simple-template/result 01-simple-template/template < 01-simple-template/context.yml assertions: - - result.systemout ShouldContainSubstring Hello World! - result.code ShouldEqual 0 diff --git a/test/suites/01-simple-template/context.yml b/test/suites/01-simple-template/context.yml new file mode 100644 index 0000000..6321234 --- /dev/null +++ b/test/suites/01-simple-template/context.yml @@ -0,0 +1,9 @@ +tables: + - name: "table_1" + columns: + - name: "column_1" + - name: "column_2" + - name: "table_2" + columns: + - name: "column_3" + - name: "column_4" diff --git a/test/suites/01-simple-template/result/table_1/column_1.txt b/test/suites/01-simple-template/result/table_1/column_1.txt new file mode 100644 index 0000000..5155977 --- /dev/null +++ b/test/suites/01-simple-template/result/table_1/column_1.txt @@ -0,0 +1,2 @@ +Nom de la colonne : column_1 +Nom de la table : table_1 diff --git a/test/suites/01-simple-template/result/table_1/column_2.txt b/test/suites/01-simple-template/result/table_1/column_2.txt new file mode 100644 index 0000000..932ed86 --- /dev/null +++ b/test/suites/01-simple-template/result/table_1/column_2.txt @@ -0,0 +1,2 @@ +Nom de la colonne : column_2 +Nom de la table : table_1 diff --git a/test/suites/01-simple-template/result/table_2/column_3.txt b/test/suites/01-simple-template/result/table_2/column_3.txt new file mode 100644 index 0000000..47c90e0 --- /dev/null +++ b/test/suites/01-simple-template/result/table_2/column_3.txt @@ -0,0 +1,2 @@ +Nom de la colonne : column_3 +Nom de la table : table_2 diff --git a/test/suites/01-simple-template/result/table_2/column_4.txt b/test/suites/01-simple-template/result/table_2/column_4.txt new file mode 100644 index 0000000..9d423cb --- /dev/null +++ b/test/suites/01-simple-template/result/table_2/column_4.txt @@ -0,0 +1,2 @@ +Nom de la colonne : column_4 +Nom de la table : table_2 diff --git a/test/suites/01-simple-template/template/{{tables.[].name}}/{{$[-2].columns.[].name}}.txt b/test/suites/01-simple-template/template/{{tables.[].name}}/{{$[-2].columns.[].name}}.txt new file mode 100644 index 0000000..02fe639 --- /dev/null +++ b/test/suites/01-simple-template/template/{{tables.[].name}}/{{$[-2].columns.[].name}}.txt @@ -0,0 +1,4 @@ +{{$column := Stack -2 -}} +{{$table := Stack -4 -}} +Nom de la colonne : {{$column.name}} +Nom de la table : {{$table.name}} diff --git a/test/suites/02-run-webserver.yml b/test/suites/02-run-webserver.yml deleted file mode 100644 index f3f144a..0000000 --- a/test/suites/02-run-webserver.yml +++ /dev/null @@ -1,10 +0,0 @@ -# Venom Test Suite definition -# Check Venom documentation for more information : https://github.com/ovh/venom -name: run webserver -testcases: - - name: no arguments - steps: - - script: webserver - assertions: - - result.systemout ShouldContainSubstring Hello World! - - result.code ShouldEqual 0