├── .github ├── FUNDING.yml └── workflows │ └── codeql-analysis.yml ├── .gitignore ├── COPYING ├── README.md ├── cmd └── zas │ └── main.go ├── constants.go ├── data.go ├── generate.go ├── go.mod ├── go.sum ├── init.go └── subcommand.go /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [darccio] 4 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '43 5 * * 3' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'go' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 37 | # Learn more: 38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 39 | 40 | steps: 41 | - name: Checkout repository 42 | uses: actions/checkout@v2 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #### joe made this: https://goel.io/joe 2 | 3 | #####=== Go ===##### 4 | 5 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 6 | *.o 7 | *.a 8 | *.so 9 | 10 | # Folders 11 | _obj 12 | _test 13 | 14 | # Architecture specific extensions/prefixes 15 | *.[568vq] 16 | [568vq].out 17 | 18 | *.cgo1.go 19 | *.cgo2.c 20 | _cgo_defun.c 21 | _cgo_gotypes.go 22 | _cgo_export.* 23 | 24 | _testmain.go 25 | 26 | *.exe 27 | *.test 28 | *.prof 29 | 30 | #####=== Vim ===##### 31 | [._]*.s[a-w][a-z] 32 | [._]s[a-w][a-z] 33 | *.un~ 34 | Session.vim 35 | .netrwhist 36 | *~ 37 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![Zas](http://i.imgur.com/e9abWRX.png) 2 | 3 | Most simple static site generator ever. 4 | 5 | ## Why another one? C'mon, you must be kidding 6 | 7 | I just wanted to set up a simple website, just some pages, using Jekyll, and it didn't feel right. I didn't want a blog. 8 | 9 | I checked other projects, but they were incomplete, cumbersome, or solved the wrong problem (blogs, blogs everywhere). I wanted a zen-like experience: a layout and some Markdown files as pages with unobtrusive structure and configuration. 10 | 11 | Yes, it is another NIH, but... I think Zas is a different kind of beast. I admit that I probably overlooked some projects at the moment. 12 | 13 | ### What is the difference? 14 | 15 | 1. Gophers. Yes, there is [Hugo](http://gohugo.io/) (kudos!) but... Who wants to learn another directory layout? There is also [Hastie](https://github.com/mkaz/hastie) and [lots of other static site generators](https://jamstack.org/generators/). 16 | 2. Pure Markdown. And HTML, if you want. 17 | 3. Just a loop. Zas loops over all .md and .html files in the current directory (and subdirectories), ignoring other files (including dot-files). 18 | 4. Your imagination is your limit. Zas has a simple extension mechanism based on subcommands. Do you need to handle a blog with Zas? Install/create a new extension and do it! 19 | 5. Unobtrusive structure, no `_` files. More in the [Usage section](#usage). 20 | 21 | ## Usage 22 | 23 | Install: 24 | 25 | ```sh 26 | go install github.com/darccio/zas/cmd/zas@latest 27 | ``` 28 | 29 | Go to your site's directory and do: 30 | 31 | ```sh 32 | zas init 33 | ``` 34 | 35 | Zas will create a `.zas` directory with sane defaults. Put your layout in `.zas/layout.html`, and you are good to go. 36 | 37 | ```sh 38 | zas 39 | ``` 40 | 41 | Yes. Enough. Your delightful site is on .zas/deploy. Enjoy. 42 | 43 | What is happening here? Well, Zas calls the `generate` subcommand by default. This subcommand accepts the following flags: 44 | 45 | * `-verbose`: print ALL the things! 46 | * `-full`: generate all the input files. By default, it has an incremental mode that keeps source and deploys directories in sync. 47 | 48 | ## Configuration and extension 49 | 50 | Zas is like water. It can flow, or it can cr... Nah, Zas doesn't crash (please fill an issue if it does). 51 | 52 | Everything is configurable at .zas/config.yml. It is initialized with default values every time you create a repository. Beware, it happens every time you execute init. 53 | 54 | You can override the `site` config section in two ways: 55 | 56 | 1. HTML comment in files (most precedence). 57 | 2. `.zas.yml` file at the directory level. Its scope is its directory and subdirectories (until another `.zas.yml` is found). 58 | 59 | To extend Zas functionality, you can use and create plugins. You can develop them in any language (not only in Golang) thanks to Unix magic. And more gophers. 60 | 61 | ### Plugins 62 | 63 | Any prefixed by `zs` or `mzs` is a potential Zas plugin. All plugins are Zas subcommands. 64 | 65 | For example, we invoke an imaginary plugin called `zshello` as a subcommand: 66 | 67 | ```sh 68 | $ zas hello 69 | Hello! 70 | 71 | $ zas hello World 72 | Hello World! 73 | ``` 74 | 75 | That's all. Zas passes any command-line argument after subcommand name to `zshello`. 76 | 77 | **Beware:** Zas won't pass any configuration information. Plugins are responsible for reading configuration, even from directory and page levels. Helper libraries in different languages are welcome! 78 | 79 | Also, plugins are free to use `.zas` directory for their own needs. I recommend creating this directory's structure to avoid colliding issues: 80 | 81 | ```text 82 | .zas 83 | +-- plugins 84 | | +-- github.com 85 | | +-- imdario 86 | | +-- myplugin 87 | +-- ... 88 | ``` 89 | 90 | Any `zs` plugin can be invoked through a script tag with type `application/zas+myplugin`. Arguments can be passed with data-args attribute, which content will be used as command-line invoke. 91 | 92 | ```html 93 | 94 | ``` 95 | 96 | The tag is deleted after execution. Any output in stdout will replace the tag. 97 | 98 | All plugins will be called in order. Oh, you can even ask for async execution with same-name attribute (hint: async). 99 | 100 | #### What's the deal with "mzs" prefix? (a.k.a. MIME types plugins) 101 | 102 | These are MIME type plugins. Zas uses embed tags to allow easy integration beyond command line. Any MIME type can be configured in `.zas/config.yml` under mimetypes section. 103 | 104 | ```yaml 105 | mimetypes: 106 | text/markdown: markdown 107 | text/yaml+myplugin: myplugin 108 | ``` 109 | 110 | If Zas finds an embed tag with a type attribute set to `text/yaml+myplugin`, it will invoke `mzsmyplugin`. Zas expects to process the plugin's stdout as HTML. It also pipes stderr to the user's shell. Any plugin will be called passing the current file's path as an argument. 111 | 112 | ```html 113 | 114 | ``` 115 | 116 | Maybe you are asking yourself: "Where is mzsmarkdown?". Nowhere! It is a particular case where Zas calls an exported method Markdown. I wanted to allow anyone to override internal Markdown processing if they wish. 117 | 118 | If you develop a new plugin, please contact me, and I will list it here :) Please, keep in mind: make it [idempotent](http://en.wikipedia.org/wiki/Idempotence). 119 | 120 | ## Building sites 121 | 122 | Your site layout will look like this: 123 | 124 | ```sh 125 | $ ls 126 | $ 127 | ``` 128 | 129 | Just kidding. A site would be: 130 | 131 | ```sh 132 | $ ls -laR 133 | total 8 134 | drwxr-xr-x 5 Dario staff 170 30 mar 16:18 . 135 | drwxr-xr-x 6 Dario staff 204 30 mar 13:17 .. 136 | drwxr-xr-x 13 Dario staff 442 27 mar 20:05 .git 137 | drwxr-xr-x 3 Dario staff 102 30 mar 13:18 .zas 138 | -rw-r--r-- 1 Dario staff 941 30 mar 16:19 about.md 139 | -rw-r--r--@ 1 Dario staff 1645 30 mar 15:31 index.md 140 | drwxr-xr-x 4 Dario staff 136 30 mar 16:20 section 141 | 142 | # [...] 143 | 144 | ./.zas: 145 | total 0 146 | drwxr-xr-x 4 Dario staff 136 30 mar 16:22 . 147 | drwxr-xr-x 7 Dario staff 238 30 mar 16:19 .. 148 | -rw-r--r-- 1 Dario staff 29 30 mar 13:18 config.yml 149 | -rw-r--r-- 1 Dario staff 2438 30 mar 16:22 layout.html 150 | 151 | ./section: 152 | total 0 153 | drwxr-xr-x 4 Dario staff 136 30 mar 16:20 . 154 | drwxr-xr-x 7 Dario staff 238 30 mar 16:19 .. 155 | -rw-r--r-- 1 Dario staff 718 30 mar 16:19 index.md 156 | -rw-r--r-- 1 Dario staff 991 30 mar 16:20 more.md 157 | ``` 158 | 159 | All .md files will be converted to HTML and copied in `.zas/deploy` using `.zas/layout.html` as layout and copying any other files and their structure. The former is also true for HTML files. 160 | 161 | Keep in mind that any file will be treated as a Go text template before any further processing. You have access to these fields and methods from anywhere: 162 | 163 | * `{{.Body}}`: the file itself in HTML. 164 | * `{{.Title}}`: autodetected title (first H1 header in file), overridden by `title` property in page's config. 165 | * `{{.Path}}`: file's path (also valid as URL). 166 | * `{{.Site.BaseURL}}`: URL where this site will be deployed, e.g. http://example.com (without final slash). 167 | * `{{.Site.Image}}`: URL to main image. Useful for Open Graph and Twitter meta tags. 168 | * `{{.Page}}`: YAML map from first HTML comment (in Markdown and HTML files). It is optional. 169 | * `{{.Directory}}`: YAML map from above (up to project's directory) or current directory's `.zas.yml` file. It is optional. 170 | * `{{.URL}}`: full URL for this file. 171 | * `{{.Extra /path/}}`: direct access to map holding `.zas/config.yml` as it is. You can access to any value with its full path. E.g. BaseURL is also available as `/site/baseurl`. 172 | * `{{.Resolve id}}`: indirect access to site, directory and page config. It works with simple keys (no paths), checking for them in page, directory and site config (as `/site/`), in this order. 173 | * `{{.Language}}`: file current language, if defined in the first comment (as YAML property `language`). By default, `/site/language` value. 174 | 175 | ### What about layout.html? 176 | 177 | It is plain HTML. No frills. Just add a placeholder `{{.Body}}` in your template. 178 | 179 | First header level 1 from Markdown files will be made available as `{{.Title}}`, unless it is overridden. 180 | 181 | ### But... I want to do pages beyond post-like format 182 | 183 | No problem! Just use our old friend ``. Imagine `` is a valid tag. 184 | 185 | ```html 186 | 187 | 190 |
191 | 192 |
193 |
194 | ``` 195 | 196 | What does it mean? It means you can have .html files with embedded markdown files. Or anything else supported by Zas. 197 | 198 | ## 你会说普通话? 199 | 200 | 對不起。T我不会说普通话。That's all my Chinese! If you are here, I guess you will enjoy I18N support in Zas. 201 | 202 | ### I18N? 203 | 204 | Yeah, internationalization: you can build multilingual sites with Zas! 205 | 206 | You only need to do three simple steps. First, create an i18n.yml file inside your .zas directory, like this: 207 | 208 | ```yaml 209 | Main page: 210 | zh: 首页 211 | ru: Заглавная страница 212 | es: Portada 213 | ca: Portada 214 | Create account: 215 | zh: 创建账户 216 | ru: Создать учётную запись 217 | es: Crear una cuenta 218 | ca: Crea un compte 219 | Log in: 220 | zh: 登录 221 | ru: Войти 222 | es: Acceder 223 | ca: Inicia la sessió 224 | ``` 225 | 226 | Set your site's main language in `.zas/config.yml`: 227 | 228 | ```yaml 229 | site: 230 | language: en 231 | ``` 232 | 233 | Also, set each file's language in first comment or, if you have lots of files, as a `.zas.yml` in a subdirectory where to group them. 234 | 235 | ```sh 236 | .zas/ 237 | index.md 238 | faq.md 239 | +-- zh 240 | +-- .zas.yml 241 | +-- index.md 242 | +-- faq.md 243 | +-- ru 244 | +-- .zas.yml 245 | +-- index.md 246 | +-- faq.md 247 | +-- es 248 | +-- .zas.yml 249 | +-- index.md 250 | +-- faq.md 251 | +-- ca 252 | +-- .zas.yml 253 | +-- index.md 254 | +-- faq.md 255 | ``` 256 | 257 | Your `.zas.yml` will look like this, i.e. for Russian (ru): 258 | 259 | ```yaml 260 | language: ru 261 | ``` 262 | 263 | ## Roadmap 264 | 265 | There is no roadmap. I wrote some possible enhancements [here](https://github.com/darccio/zas/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement). 266 | 267 | Feel free to open an issue if you think Zas should do something specific in its core. 268 | 269 | ## Contact me 270 | 271 | If I can help you, you have an idea or you are using Zas in your projects, don't hesitate to drop me a line (or a pull request): [@darccio](https://twitter.com/darccio) 272 | 273 | ## About 274 | 275 | Written by [Dario Castañé](http://dario.im). 276 | 277 | ## License 278 | 279 | Zas is under [AGPL v3](http://www.gnu.org/licenses/agpl-3.0.html) license. 280 | 281 | ## Other cool projects 282 | 283 | Recently I found this cool generator inspired by zas: [zs](https://github.com/zserge/zs). I'm happy to be a humble reference for somebody :) 284 | -------------------------------------------------------------------------------- /cmd/zas/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dario Castañé. 3 | * This file is part of Zas. 4 | * 5 | * Zas is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * Zas is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with Zas. If not, see . 17 | */ 18 | package main 19 | 20 | import ( 21 | "fmt" 22 | "os" 23 | "os/exec" 24 | "runtime" 25 | "strings" 26 | 27 | "github.com/darccio/zas" 28 | ) 29 | 30 | /* 31 | * Current Zas internal subcommands. 32 | */ 33 | var subcommands = []*zas.Subcommand{ 34 | cmdInit, 35 | cmdGenerate, 36 | } 37 | 38 | var ( 39 | verbose, full *bool 40 | cmdInit = zas.NewSubcommand("init", func() { 41 | i := zas.Init{} 42 | i.Run() 43 | }) 44 | cmdGenerate = zas.NewSubcommand("generate", func() { 45 | g := zas.Generator{ 46 | Verbose: *verbose, 47 | Full: *full, 48 | } 49 | g.Run() 50 | }) 51 | ) 52 | 53 | func init() { 54 | verbose = cmdGenerate.Flag.Bool("verbose", false, "Verbose output") 55 | full = cmdGenerate.Flag.Bool("full", false, "Full generation (non-incremental mode)") 56 | } 57 | 58 | func main() { 59 | runtime.GOMAXPROCS(runtime.NumCPU()) 60 | 61 | args := os.Args[1:] 62 | if len(args) == 0 { 63 | // If no subcommand is provided, we default to "generate". 64 | args = []string{"generate"} 65 | } 66 | 67 | if strings.HasPrefix(args[0], "-") { 68 | // If the first argument is a flag, we default to "generate". 69 | args = append([]string{"generate"}, args...) 70 | } 71 | 72 | command := strings.ToLower(args[0]) 73 | 74 | for _, cmd := range subcommands { 75 | if cmd.Name == command && cmd.Run != nil { 76 | cmd.Flag.Parse(args[1:]) 77 | cmd.Run() 78 | 79 | os.Exit(0) 80 | } 81 | } 82 | 83 | // If not internal subcommand is found, we try to exec an external Zas subcommand (plugin). 84 | cmd := exec.Command(fmt.Sprintf("%s%s", zas.ZAS_PREFIX, args[0]), args[1:]...) 85 | cmd.Stdout = os.Stdout 86 | cmd.Stderr = os.Stderr 87 | 88 | if err := cmd.Run(); err != nil { 89 | fmt.Fprintf(os.Stderr, "# %s %s\n", args[0], strings.Join(args[1:], " ")) 90 | 91 | panic(err) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /constants.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dario Castañé. 3 | * This file is part of Zas. 4 | * 5 | * Zas is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * Zas is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with Zas. If not, see . 17 | */ 18 | package zas 19 | 20 | import ( 21 | "fmt" 22 | "path/filepath" 23 | 24 | "golang.org/x/text/cases" 25 | "golang.org/x/text/language" 26 | ) 27 | 28 | var ( 29 | ZAS = "zas" 30 | ZAS_PREFIX = "zs" 31 | ZAS_NAME = cases.Title(language.English).String(ZAS) 32 | ZAS_DIR = fmt.Sprintf(".%s", ZAS) 33 | ZAS_CONF_FILE = filepath.Join(ZAS_DIR, "config.yml") 34 | ZAS_I18N_FILE = filepath.Join(ZAS_DIR, "i18n.yml") 35 | ZAS_DIR_CONF_FILE = fmt.Sprintf(".%s.yml", ZAS) 36 | ZAS_DEFAULT_DIR_PERM = 0o755 37 | ZAS_DEFAULT_FILE_PERM = 0o644 38 | ZAS_DEFAULT_CONF = ConfigSection{ 39 | ZAS: ConfigSection{ 40 | "layout": filepath.Join(ZAS_DIR, "layout.html"), 41 | "deploy": filepath.Join(ZAS_DIR, "deploy"), 42 | }, 43 | "site": ConfigSection{ 44 | "baseurl": "http://example.com", 45 | "language": "en", 46 | }, 47 | "mimetypes": ConfigSection{ 48 | "text/markdown": "markdown", 49 | "text/plain": "plain", 50 | "text/html": "html", 51 | }, 52 | } 53 | ) 54 | -------------------------------------------------------------------------------- /data.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dario Castañé. 3 | * This file is part of Zas. 4 | * 5 | * Zas is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * Zas is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with Zas. If not, see . 17 | */ 18 | package zas 19 | 20 | import ( 21 | "errors" 22 | "fmt" 23 | thtml "html/template" 24 | "path" 25 | "strings" 26 | 27 | "github.com/melvinmt/gt" 28 | ) 29 | 30 | /* 31 | * Context data store used in templates. 32 | */ 33 | type ZasData struct { 34 | // Template used as body from current file. 35 | Body thtml.HTML 36 | // Current path (usable in URLs). 37 | Path string 38 | // Title from first level header (H1). 39 | FirstTitle string 40 | // Site configuration, as found in ZAS_CONF_FILE. 41 | Site ZasSiteData 42 | // In-page configuration, from first HTML comment (expected as YAML map). 43 | Page map[interface{}]interface{} 44 | // Current directory configuration, from ZAS_DIR_CONF_FILE. 45 | Directory ConfigSection 46 | // Config loaded from ZAS_CONF_FILE. 47 | config ConfigSection 48 | // i18n helper 49 | i18n *gt.Build 50 | } 51 | 52 | /* 53 | * Site configuration. 54 | * 55 | * They are required fields in order to complete social/semantic meta tags. 56 | */ 57 | type ZasSiteData struct { 58 | BaseURL string 59 | Image string 60 | } 61 | 62 | /* 63 | * Current title, from page's config and first level header (H1), in this order. 64 | */ 65 | func (zd *ZasData) Title() (title string) { 66 | title, ok := zd.Page["title"].(string) 67 | if !ok { 68 | title = zd.FirstTitle 69 | } 70 | return 71 | } 72 | 73 | /* 74 | * Builds URL from current configuration. 75 | */ 76 | func (zd *ZasData) URL() string { 77 | return fmt.Sprintf("%s%s", zd.Site.BaseURL, zd.Path) 78 | } 79 | 80 | /* 81 | * Helper template method to get any value from ZasData.config using pathes. 82 | */ 83 | func (zd *ZasData) Extra(keypath string) (value string, err error) { 84 | keypath = path.Clean(keypath) 85 | if path.IsAbs(keypath) { 86 | keypath = keypath[1:] 87 | } 88 | steps := strings.Split(keypath, "/") 89 | last := len(steps) - 1 90 | key, steps := steps[last], steps[:last] 91 | section := zd.config 92 | for _, step := range steps { 93 | section = section.GetSection(step) 94 | if section == nil { 95 | err = errors.New("not found") 96 | return 97 | } 98 | } 99 | value = section.GetString(key) 100 | return 101 | } 102 | 103 | func (zd *ZasData) Language() (language string) { 104 | return zd.Resolve("language") 105 | } 106 | 107 | func (zd *ZasData) Resolve(id string) string { 108 | var ( 109 | value interface{} 110 | ok bool 111 | ) 112 | value, ok = zd.Page[id] 113 | if !ok { 114 | if zd.Directory != nil { 115 | value, ok = zd.Directory[id] 116 | } 117 | if !ok { 118 | value, _ = zd.Extra(fmt.Sprintf("/site/%s", id)) 119 | } 120 | } 121 | return value.(string) 122 | } 123 | 124 | func (zd *ZasData) E(s string, a ...interface{}) (t string) { 125 | var err error 126 | zd.i18n.SetTarget(zd.Language()) 127 | if len(a) == 0 { 128 | t, err = zd.i18n.Translate(s) 129 | } else { 130 | t, err = zd.i18n.Translate(s, a) 131 | } 132 | if err != nil { 133 | t = "**" + s + "**" 134 | err = nil 135 | } 136 | return 137 | } 138 | 139 | func (zd *ZasData) H(s string, a ...interface{}) (h thtml.HTML) { 140 | return thtml.HTML(zd.E(s, a...)) 141 | } 142 | 143 | func (zd *ZasData) IsHome() bool { 144 | return zd.Path == "/index.html" || zd.Path == fmt.Sprintf("/%s/index.html", zd.Language()) 145 | } 146 | 147 | func NewZasData(filepath string, gen *Generator) (data ZasData) { 148 | // Any path must finish in ".html". 149 | if strings.HasSuffix(filepath, ".md") { 150 | filepath = strings.Replace(filepath, ".md", ".html", -1) 151 | } 152 | data.Path = fmt.Sprintf("/%s", filepath) 153 | data.config = gen.Config 154 | data.i18n = gen.I18n 155 | data.Site.BaseURL = gen.Config.GetSection("site").GetString("baseurl") 156 | data.Site.Image = gen.Config.GetSection("site").GetString("image") 157 | return 158 | } 159 | -------------------------------------------------------------------------------- /generate.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dario Castañé. 3 | * This file is part of Zas. 4 | * 5 | * Zas is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * Zas is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with Zas. If not, see . 17 | */ 18 | package zas 19 | 20 | import ( 21 | "bytes" 22 | "fmt" 23 | "html" 24 | thtml "html/template" 25 | "io" 26 | "os" 27 | "os/exec" 28 | "path/filepath" 29 | "reflect" 30 | "strings" 31 | "sync" 32 | ttext "text/template" 33 | 34 | "github.com/PuerkitoBio/goquery" 35 | "github.com/melvinmt/gt" 36 | markdown "github.com/yuin/goldmark" 37 | html5 "golang.org/x/net/html" 38 | "golang.org/x/net/html/atom" 39 | "golang.org/x/text/cases" 40 | "golang.org/x/text/language" 41 | yaml "gopkg.in/yaml.v2" 42 | ) 43 | 44 | var helpers = thtml.FuncMap{ 45 | "noescape": noescape, 46 | "eq": eq, 47 | } 48 | 49 | /* 50 | * Convenience type to group relevant rendering info. 51 | */ 52 | type Generator struct { 53 | // Verbose output. 54 | Verbose bool 55 | // Full generation (non-incremental mode). 56 | Full bool 57 | // Config from ZAS_CONF_FILE. 58 | Config ConfigSection 59 | // Default layout from Config[ZAS]["layout"]. 60 | Layout *thtml.Template 61 | // i18n helper. 62 | I18n *gt.Build 63 | // ZasDirectoryConfigs cache 64 | cachedZasDirectoryConfigs map[string]ConfigSection 65 | 66 | wg sync.WaitGroup 67 | } 68 | 69 | /* 70 | * Returns deployment base path in config. 71 | */ 72 | func (gen *Generator) GetDeployPath() string { 73 | return gen.Config.GetZString("deploy") 74 | } 75 | 76 | /* 77 | * Builds deployment path for specific file pointed by path. 78 | */ 79 | func (gen *Generator) BuildDeployPath(path string) string { 80 | return filepath.Join(gen.GetDeployPath(), path) 81 | } 82 | 83 | /* 84 | * Renders and writes current file "path" with context "data". 85 | */ 86 | func (gen *Generator) Generate(path string, data *ZasData) (err error) { 87 | var processed bytes.Buffer 88 | if err = gen.Layout.Execute(&processed, data); err != nil { 89 | return 90 | } 91 | doc, err := gen.parseAndReplace(processed, data) 92 | if err != nil { 93 | return 94 | } 95 | f, err := os.OpenFile(gen.BuildDeployPath(data.Path), os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.FileMode(ZAS_DEFAULT_FILE_PERM)) 96 | if err != nil { 97 | return 98 | } 99 | defer f.Close() 100 | err = html5.Render(f, doc.Get(0)) 101 | if err != nil { 102 | return 103 | } 104 | return 105 | } 106 | 107 | func (gen *Generator) parseAndReplace(processed bytes.Buffer, data *ZasData) (doc *goquery.Document, err error) { 108 | // Here we manipulate its result. 109 | doc, err = goquery.NewDocumentFromReader(&processed) 110 | if err != nil { 111 | return 112 | } 113 | err = gen.handleEmbedTags(doc, data) 114 | return 115 | } 116 | 117 | func (gen *Generator) Run() error { 118 | cfg, err := NewConfig() 119 | if err != nil { 120 | if os.IsNotExist(err) { 121 | fmt.Printf("fatal: Not a valid Zas repository: %s\n", err) 122 | return err 123 | } 124 | return err 125 | } 126 | gen.Config = cfg 127 | gen.wg.Add(3) 128 | go gen.parseLayout() 129 | go gen.loadI18N() 130 | go gen.handleDeployPath(gen.Full) 131 | gen.wg.Wait() 132 | // Walking function. It allows to bubble up any error from generator. 133 | walk := func(path string, info os.FileInfo, err error) error { 134 | return gen.walk(path, info, err) 135 | } 136 | if err := filepath.Walk(".", walk); err != nil { 137 | return err 138 | } 139 | gen.wg.Wait() 140 | if !gen.Full { 141 | // TODO Can we go parallel? 142 | // This removes deleted source files in deploy path 143 | reapwalk := func(path string, info os.FileInfo, err error) error { 144 | return gen.reaper(path, info, err) 145 | } 146 | if err = filepath.Walk(gen.GetDeployPath(), reapwalk); err != nil { 147 | return err 148 | } 149 | } 150 | return nil 151 | } 152 | 153 | func (gen *Generator) parseLayout() { 154 | var err error 155 | defer gen.wg.Done() 156 | 157 | layout := gen.Config.GetZString("layout") 158 | if gen.Layout, err = thtml.New(filepath.Base(layout)).Funcs(helpers).ParseFiles(layout); err != nil { 159 | panic(err) 160 | } 161 | } 162 | 163 | func (gen *Generator) loadI18N() { 164 | defer gen.wg.Done() 165 | 166 | mainlang := gen.Config.GetSection("site").GetString("language") 167 | i18nStrings, err := NewI18n(mainlang) 168 | if err != nil { 169 | panic(err) 170 | } 171 | gen.I18n = >.Build{ 172 | Index: i18nStrings, 173 | Origin: mainlang, 174 | } 175 | } 176 | 177 | func (gen *Generator) handleDeployPath(full bool) { 178 | defer gen.wg.Done() 179 | 180 | deployPath := gen.GetDeployPath() 181 | // If deployment path already exists, it must be deleted. 182 | if _, err := os.Stat(deployPath); err == nil && full { 183 | if err = os.RemoveAll(deployPath); err != nil { 184 | panic(err) 185 | } 186 | } 187 | if err := os.MkdirAll(deployPath, os.FileMode(ZAS_DEFAULT_DIR_PERM)); err != nil { 188 | panic(err) 189 | } 190 | } 191 | 192 | /* 193 | * Real walking function. Handles all supported files and copy not supported ones in current deployment path. 194 | */ 195 | func (gen *Generator) walk(path string, info os.FileInfo, err error) (ierr error) { 196 | if strings.HasPrefix(path, ".") || strings.HasPrefix(filepath.Base(path), ".") || strings.Contains(path, fmt.Sprintf("%s/", ZAS_DIR)) { 197 | return 198 | } 199 | if info.IsDir() { 200 | ierr = os.MkdirAll(gen.BuildDeployPath(path), os.FileMode(ZAS_DEFAULT_DIR_PERM)) 201 | } else { 202 | if gen.sourceIsNewer(path, info) { 203 | if gen.Verbose { 204 | fmt.Println("+", path) 205 | } 206 | gen.wg.Add(1) 207 | go gen.renderAsync(path) 208 | } 209 | } 210 | return 211 | } 212 | 213 | func (gen *Generator) renderAsync(path string) { 214 | var err error 215 | defer gen.wg.Done() 216 | 217 | switch { 218 | case strings.HasSuffix(path, ".md"): 219 | err = gen.renderMarkdown(path) 220 | case strings.HasSuffix(path, ".html"): 221 | err = gen.renderHTML(path) 222 | default: 223 | err = gen.copy(gen.BuildDeployPath(path), path) 224 | } 225 | 226 | if err != nil { 227 | fmt.Printf("fatal: %s => %s\n", path, err) 228 | } 229 | } 230 | 231 | /* 232 | * Real reaping function. Reaps all missing source files in current deployment path. 233 | */ 234 | func (gen *Generator) reaper(path string, info os.FileInfo, err error) (ierr error) { 235 | sourcePath := strings.Replace(path, gen.GetDeployPath(), ".", 1) 236 | source, err := os.Open(sourcePath) 237 | // TODO it must clean directories too 238 | if err != nil { 239 | reap := true 240 | if strings.HasSuffix(sourcePath, ".html") { 241 | sourcePath = strings.Replace(sourcePath, ".html", ".md", 1) 242 | sourceNew, err := os.Open(sourcePath) 243 | if err == nil { 244 | sourceNew.Close() 245 | reap = false 246 | } 247 | } 248 | if reap { 249 | if gen.Verbose { 250 | fmt.Println("-", sourcePath) 251 | } 252 | os.RemoveAll(path) 253 | } 254 | } else { 255 | source.Close() 256 | } 257 | return 258 | } 259 | 260 | func (gen *Generator) sourceIsNewer(path string, sourceInfo os.FileInfo) bool { 261 | // Shortcut 262 | if gen.Full { 263 | return true 264 | } 265 | realpath := string(path) 266 | if strings.HasSuffix(path, ".md") { 267 | realpath = strings.Replace(path, ".md", ".html", 1) 268 | } 269 | destination, err := os.Open(gen.BuildDeployPath(realpath)) 270 | if err != nil { 271 | return true 272 | } 273 | defer destination.Close() 274 | destinationInfo, _ := destination.Stat() 275 | return sourceInfo.ModTime().UnixNano() >= destinationInfo.ModTime().UnixNano() 276 | } 277 | 278 | /* 279 | * Renders a Markdown file. 280 | */ 281 | func (gen *Generator) renderMarkdown(path string) (err error) { 282 | input, err := os.ReadFile(path) 283 | if err != nil { 284 | return 285 | } 286 | // This is going to haunt me for a while. 287 | var b bytes.Buffer 288 | if err := markdown.Convert(input, &b); err != nil { 289 | return err 290 | } 291 | md := []byte(html.UnescapeString(b.String())) 292 | return gen.render(path, md) 293 | } 294 | 295 | /* 296 | * Renders a HTML file. 297 | */ 298 | func (gen *Generator) renderHTML(path string) (err error) { 299 | input, err := os.ReadFile(path) 300 | if err != nil { 301 | return 302 | } 303 | return gen.render(path, input) 304 | } 305 | 306 | /* 307 | * Loads ZAS_DIR_CONF_FILE (as defined in constants.go) from current 308 | * directory or previously found ones. 309 | * It must be a YAML file. 310 | */ 311 | func (gen *Generator) loadZasDirectoryConfig(currentpath string) (config ConfigSection, err error) { 312 | var ok bool 313 | path := filepath.Dir(currentpath) 314 | if config, ok = gen.cachedZasDirectoryConfigs[path]; !ok { 315 | data, err := os.ReadFile(fmt.Sprintf("%s/%s", path, ZAS_DIR_CONF_FILE)) 316 | if err != nil { 317 | // Maybe .zas.yml is in an upper directory (already cached or not), 318 | // so we call this recursively. 319 | // Unless we are at current working directory. 320 | if path == "." { 321 | return nil, err 322 | } 323 | return gen.loadZasDirectoryConfig(path) 324 | } 325 | config = make(ConfigSection) 326 | _ = yaml.Unmarshal(data, &config) 327 | if gen.cachedZasDirectoryConfigs == nil { 328 | gen.cachedZasDirectoryConfigs = make(map[string]ConfigSection) 329 | } 330 | gen.cachedZasDirectoryConfigs[path] = config 331 | } 332 | return 333 | } 334 | 335 | /* 336 | * Generic render function. It expects input to be a valid HTML document. 337 | * Input can be a valid Go template. 338 | */ 339 | func (gen *Generator) render(path string, input []byte) (err error) { 340 | template, err := ttext.New("current").Parse(string(input)) 341 | if err != nil { 342 | return 343 | } 344 | var processed bytes.Buffer 345 | // Building context and rendering template. 346 | data := NewZasData(path, gen) 347 | data.Directory, _ = gen.loadZasDirectoryConfig(path) 348 | if err = template.Execute(&processed, data); err != nil { 349 | return 350 | } 351 | doc, err := gen.parseAndReplace(processed, &data) 352 | if err != nil { 353 | fmt.Println(err) 354 | return 355 | } 356 | gen.cleanUnnecessaryPTags(doc) 357 | data.Page, err = gen.extractPageConfig(doc) 358 | if err != nil { 359 | fmt.Println(path, "=>", err) 360 | err = nil 361 | } 362 | data.FirstTitle = gen.getTitle(doc) 363 | body := doc.Find(atom.Body.String()) 364 | if err != nil { 365 | return 366 | } 367 | if body.Size() > 0 { 368 | var bbody bytes.Buffer 369 | err = html5.Render(&bbody, body.Get(0)) 370 | if err != nil { 371 | return 372 | } 373 | data.Body = thtml.HTML(bbody.Bytes()) 374 | } 375 | return gen.Generate(path, &data) 376 | } 377 | 378 | /* 379 | * Removes unnecessary paragraph HTML tags generated during Markdown processing by 380 | * deleting any

without child text nodes (just to avoid deletion if semantic tags 381 | * are inside). 382 | */ 383 | func (gen *Generator) cleanUnnecessaryPTags(doc *goquery.Document) { 384 | doc.Find(atom.P.String()).Each(func(ix int, p *goquery.Selection) { 385 | hasText := false 386 | // Little heuristic to remove nodes with visually empty content. 387 | content := strings.TrimSpace(p.Nodes[0].Data) 388 | if content != "" { 389 | hasText = true 390 | } 391 | // If current

tag doesn't have any child text node, extract children and add to its parent. 392 | if !hasText { 393 | p.ReplaceWithSelection(p.Children()) 394 | } 395 | }) 396 | } 397 | 398 | /* 399 | * Returns first H1 tag as page title. 400 | */ 401 | func (gen *Generator) getTitle(doc *goquery.Document) (title string) { 402 | result := doc.Find(atom.H1.String()) 403 | if result.Size() > 0 { 404 | title = result.First().Text() 405 | } 406 | return 407 | } 408 | 409 | /* 410 | * Extracts first HTML commend as map. It expects it as a valid YAML map. 411 | */ 412 | func (gen *Generator) extractPageConfig(doc *goquery.Document) (config map[interface{}]interface{}, err error) { 413 | var comment *html5.Node 414 | for _, child := range doc.Nodes { 415 | if child.FirstChild == nil { 416 | continue 417 | } 418 | if child.FirstChild.Type == html5.CommentNode { 419 | comment = child.FirstChild 420 | break 421 | } 422 | } 423 | if comment != nil { 424 | _ = yaml.Unmarshal([]byte(comment.Data), &config) 425 | } 426 | return 427 | } 428 | 429 | /* 430 | * Copies a file. 431 | */ 432 | func (gen *Generator) copy(dstPath, srcPath string) (err error) { 433 | src, err := os.Open(srcPath) 434 | if err != nil { 435 | return 436 | } 437 | defer src.Close() 438 | dst, err := os.OpenFile(dstPath, os.O_CREATE|os.O_TRUNC|os.O_RDWR, os.FileMode(ZAS_DEFAULT_FILE_PERM)) 439 | if err != nil { 440 | return 441 | } 442 | defer dst.Close() 443 | _, err = io.Copy(dst, src) 444 | return 445 | } 446 | 447 | /* 448 | * Embeds a Markdown file. 449 | */ 450 | func (gen *Generator) Markdown(e *goquery.Selection, doc *goquery.Document, data *ZasData) (err error) { 451 | if src, ok := e.Attr(atom.Src.String()); ok { 452 | mdInput, err := os.ReadFile(src) 453 | if err != nil { 454 | return err 455 | } 456 | var b bytes.Buffer 457 | if err := markdown.Convert(mdInput, &b); err != nil { 458 | return err 459 | } 460 | mdDoc, err := gen.parseAndReplace(b, data) 461 | if err != nil { 462 | return err 463 | } 464 | e.ReplaceWithSelection(mdDoc.Find(atom.Body.String())) 465 | } 466 | return 467 | } 468 | 469 | /* 470 | * Embeds a plain text file. 471 | */ 472 | func (gen *Generator) Plain(e *goquery.Selection, doc *goquery.Document, data *ZasData) (err error) { 473 | if src, ok := e.Attr(atom.Src.String()); ok { 474 | var input []byte 475 | input, err = os.ReadFile(src) 476 | if err != nil { 477 | return err 478 | } 479 | var template *ttext.Template 480 | template, err = ttext.New("current").Parse(string(input)) 481 | if err != nil { 482 | return 483 | } 484 | var processed bytes.Buffer 485 | if err = template.Execute(&processed, data); err != nil { 486 | return 487 | } 488 | e.Parent().Nodes[0].Data = processed.String() 489 | e.Remove() 490 | } 491 | return 492 | } 493 | 494 | /* 495 | * Embeds a HTML file. 496 | */ 497 | func (gen *Generator) Html(e *goquery.Selection, doc *goquery.Document, data *ZasData) (err error) { 498 | if src, ok := e.Attr(atom.Src.String()); ok { 499 | var input []byte 500 | input, err = os.ReadFile(src) 501 | if err != nil { 502 | return err 503 | } 504 | var htmlDoc *goquery.Document 505 | htmlDoc, err = gen.parseAndReplace(*bytes.NewBuffer(input), data) 506 | if err != nil { 507 | return 508 | } 509 | e.ReplaceWithSelection(htmlDoc.Children()) 510 | } 511 | return 512 | } 513 | 514 | /* 515 | * Handles tags. 516 | * 517 | * They can be handled with MIME type plugins or internal exported methods like Markdown. 518 | */ 519 | func (gen *Generator) handleEmbedTags(doc *goquery.Document, data *ZasData) (err error) { 520 | doc.Find(atom.Embed.String()).EachWithBreak(func(ix int, e *goquery.Selection) bool { 521 | if src, ok := e.Attr(atom.Src.String()); ok { 522 | var typ string 523 | if typ, ok = e.Attr(atom.Type.String()); !ok { 524 | err = fmt.Errorf("missing type attribute for embed '%s'", src) 525 | return false 526 | } 527 | plugin := gen.resolveMIMETypePlugin(typ) 528 | method := reflect.ValueOf(gen).MethodByName(cases.Title(language.English).String(plugin)) 529 | if method == reflect.ValueOf(nil) { 530 | err = gen.handleMIMETypePlugin(e, doc) 531 | } else { 532 | args := make([]reflect.Value, 3) 533 | args[0] = reflect.ValueOf(e) 534 | args[1] = reflect.ValueOf(doc) 535 | args[2] = reflect.ValueOf(data) 536 | r := method.Call(args) 537 | rerr := r[0].Interface() 538 | if ierr, ok := rerr.(error); ok { 539 | err = ierr 540 | } 541 | } 542 | if err != nil { 543 | return false 544 | } 545 | } 546 | return true 547 | }) 548 | return 549 | } 550 | 551 | type bufErr struct { 552 | buffer []byte 553 | err error 554 | } 555 | 556 | /* 557 | * Invokes a MIME type plugin based on current node's type attribute, passing src attribute's value 558 | * as argument. Subcommand's output is piped to Gokogiri through a buffer. 559 | */ 560 | func (gen *Generator) handleMIMETypePlugin(e *goquery.Selection, doc *goquery.Document) (err error) { 561 | var ( 562 | src, typ string 563 | ok bool 564 | ) 565 | if src, ok = e.Attr(atom.Src.String()); ok { 566 | return 567 | } 568 | if typ, ok = e.Attr(atom.Type.String()); ok { 569 | return 570 | } 571 | cmdname := gen.resolveMIMETypePlugin(typ) 572 | if cmdname == "" { 573 | return 574 | } 575 | cmd := exec.Command(fmt.Sprintf("m%s%s", ZAS_PREFIX, cmdname), src) 576 | stdout, err := cmd.StdoutPipe() 577 | if err != nil { 578 | return 579 | } 580 | cmd.Stderr = os.Stderr 581 | c := make(chan bufErr) 582 | go func() { 583 | data, err := io.ReadAll(stdout) 584 | c <- bufErr{data, err} 585 | }() 586 | if err = cmd.Start(); err != nil { 587 | return 588 | } 589 | be := <-c 590 | if err = cmd.Wait(); err != nil { 591 | return 592 | } 593 | if be.err != nil { 594 | return be.err 595 | } 596 | e.ReplaceWithHtml(string(be.buffer)) 597 | return 598 | } 599 | 600 | /* 601 | * Returns registered plugin (without ZAS_PREFIX) from config. 602 | */ 603 | func (gen *Generator) resolveMIMETypePlugin(typ string) string { 604 | return gen.Config.GetSection("mimetypes").GetString(typ) 605 | } 606 | 607 | func noescape(data string) thtml.HTML { 608 | return thtml.HTML(data) 609 | } 610 | 611 | func eq(a, b interface{}) bool { 612 | return a == b 613 | } 614 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/darccio/zas 2 | 3 | go 1.20 4 | 5 | require ( 6 | dario.cat/mergo v1.0.0 7 | github.com/PuerkitoBio/goquery v1.8.1 8 | github.com/melvinmt/gt v1.0.1 9 | github.com/yuin/goldmark v1.6.0 10 | golang.org/x/net v0.23.0 11 | golang.org/x/text v0.14.0 12 | gopkg.in/yaml.v2 v2.4.0 13 | ) 14 | 15 | require ( 16 | github.com/andybalholm/cascadia v1.3.2 // indirect 17 | github.com/kr/pretty v0.3.1 // indirect 18 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 19 | ) 20 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= 2 | dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= 3 | github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM= 4 | github.com/PuerkitoBio/goquery v1.8.1/go.mod h1:Q8ICL1kNUJ2sXGoAhPGUdYDJvgQgHzJsnnd3H7Ho5jQ= 5 | github.com/andybalholm/cascadia v1.3.1/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA= 6 | github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss= 7 | github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU= 8 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 9 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 10 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 11 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 12 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 13 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 14 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 15 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 16 | github.com/melvinmt/gt v1.0.1 h1:0oYILl8UfvRc+OVRk7hymybPvCzOrmixuS46Dr/XzK8= 17 | github.com/melvinmt/gt v1.0.1/go.mod h1:fZvBmiukZgESIMCkh7O+D5uceNkOaAQmST1g8exnu/o= 18 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 19 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= 20 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 21 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 22 | github.com/yuin/goldmark v1.6.0 h1:boZcn2GTjpsynOsC0iJHnBWa4Bi0qzfJjthwauItG68= 23 | github.com/yuin/goldmark v1.6.0/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 24 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 25 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 26 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 27 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 28 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 29 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 30 | golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 31 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 32 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 33 | golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 34 | golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= 35 | golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= 36 | golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= 37 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 38 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 39 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 40 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 41 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 42 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 43 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 44 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 45 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 46 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 47 | golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 48 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 49 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 50 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 51 | golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= 52 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 53 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 54 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 55 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 56 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 57 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 58 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= 59 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 60 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 61 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 62 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 63 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 64 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 65 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 66 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 67 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 68 | gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= 69 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 70 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 71 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 72 | -------------------------------------------------------------------------------- /init.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Dario Castañé. 3 | * This file is part of Zas. 4 | * 5 | * Zas is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU Affero General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * Zas is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with Zas. If not, see . 17 | */ 18 | package zas 19 | 20 | import ( 21 | "fmt" 22 | "os" 23 | "path/filepath" 24 | 25 | "dario.cat/mergo" 26 | "github.com/melvinmt/gt" 27 | yaml "gopkg.in/yaml.v2" 28 | ) 29 | 30 | /* 31 | * Aliasing goyaml's default map type. 32 | */ 33 | type ConfigSection map[interface{}]interface{} 34 | 35 | /* 36 | * Loads ZAS_CONF_FILE (as defined in constants.go). 37 | * It must be a YAML file. 38 | */ 39 | func NewConfig() (ConfigSection, error) { 40 | data, err := os.ReadFile(ZAS_CONF_FILE) 41 | if err != nil { 42 | return nil, err 43 | } 44 | 45 | var config ConfigSection 46 | if err = yaml.Unmarshal(data, &config); err != nil { 47 | return nil, err 48 | } 49 | 50 | if err = mergo.Merge(&config, ZAS_DEFAULT_CONF); err != nil { 51 | return nil, err 52 | } 53 | 54 | return config, nil 55 | } 56 | 57 | /* 58 | * Loads ZAS_I18N_FILE (as defined in constants.go). 59 | * It must be a YAML file. 60 | */ 61 | func NewI18n(mainlang string) (i18n gt.Strings, err error) { 62 | data, err := os.ReadFile(ZAS_I18N_FILE) 63 | i18n = make(gt.Strings) 64 | if err != nil { 65 | if os.IsNotExist(err) { 66 | err = nil 67 | return 68 | } 69 | i18n = nil 70 | return 71 | } 72 | err = yaml.Unmarshal(data, &i18n) 73 | for k, v := range i18n { 74 | if _, ok := v[mainlang]; !ok { 75 | v[mainlang] = k 76 | } 77 | } 78 | return 79 | } 80 | 81 | /* 82 | * Returns a string value from current section. 83 | */ 84 | func (cs ConfigSection) GetString(key string) (value string) { 85 | raw := cs[key] 86 | if raw == nil { 87 | value = "" 88 | } else { 89 | value = raw.(string) 90 | } 91 | return 92 | } 93 | 94 | /* 95 | * Returns a subsection from current section. 96 | */ 97 | func (cs ConfigSection) GetSection(key string) (value ConfigSection) { 98 | var ok bool 99 | if value, ok = cs[key].(ConfigSection); !ok { 100 | value = ConfigSection(cs[key].(map[interface{}]interface{})) 101 | } 102 | return 103 | } 104 | 105 | /* 106 | * Returns a string value from default Zas section. 107 | */ 108 | func (cs ConfigSection) GetZString(key string) string { 109 | s := cs.GetSection(ZAS) 110 | return s.GetString(key) 111 | } 112 | 113 | type Init struct{} 114 | 115 | func (i *Init) Run() { 116 | path, _ := filepath.Abs(ZAS_DIR) 117 | if _, err := os.Stat(ZAS_DIR); os.IsNotExist(err) { 118 | os.Mkdir(ZAS_DIR, os.FileMode(ZAS_DEFAULT_DIR_PERM)) 119 | fmt.Printf("Initialized empty %s repository in %s\n", ZAS_NAME, path) 120 | } else { 121 | fmt.Printf("Reinitialized existing %s repository in %s\n", ZAS_NAME, path) 122 | } 123 | var ( 124 | data []byte 125 | err error 126 | ) 127 | // If default config variable has fields, we store it as ZAS_CONF_FILE (as defined in constants.go). 128 | // It overwrites every time we invoke init subcommand. 129 | if len(ZAS_DEFAULT_CONF) > 0 { 130 | if data, err = yaml.Marshal(&ZAS_DEFAULT_CONF); err != nil { 131 | panic(err) 132 | } 133 | } 134 | if err := os.WriteFile(ZAS_CONF_FILE, data, os.FileMode(ZAS_DEFAULT_FILE_PERM)); err != nil { 135 | panic(err) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /subcommand.go: -------------------------------------------------------------------------------- 1 | package zas 2 | 3 | import ( 4 | "flag" 5 | "strings" 6 | ) 7 | 8 | /* 9 | * Zas internal subcommand. 10 | * 11 | * Inspired by go command. 12 | */ 13 | type Subcommand struct { 14 | // Runs the subcommand 15 | // The args are the arguments after the subcommand name. 16 | Run func() 17 | 18 | // UsageLine is the one-line usage message. 19 | // The first word in the line is taken to be the subcommand name. 20 | UsageLine string 21 | 22 | // Name is the name of the subcommand. 23 | Name string 24 | 25 | // Flag is a set of flags specific to this command. 26 | Flag flag.FlagSet 27 | } 28 | 29 | func NewSubcommand(usageLine string, run func()) *Subcommand { 30 | data := strings.SplitN(usageLine, " ", 2) 31 | return &Subcommand{ 32 | UsageLine: usageLine, 33 | Name: strings.ToLower(data[0]), 34 | Run: run, 35 | } 36 | } 37 | --------------------------------------------------------------------------------