├── .github └── FUNDING.yml ├── .gitignore ├── .gitmodules ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── benches └── main.rs ├── examples ├── Blades.toml ├── assets │ └── logo.svg ├── content │ ├── about │ │ └── index.toml │ ├── gallery.toml │ ├── index.toml │ └── mu.md ├── input.json ├── templates │ ├── gallery.html │ ├── page.html │ ├── section.html │ ├── taxonomy.html │ └── taxonomy_key.html └── transform_plugin.rs └── src ├── lib.rs ├── main.rs ├── page.rs ├── render.rs ├── site.rs ├── sources.rs ├── taxonomies.rs ├── templates ├── Blades.toml ├── atom.xml ├── page.toml ├── rss.xml └── sitemap.xml └── types.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [grego] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | **/*.DS_Store 4 | .env 5 | *.kak* 6 | **.blades* 7 | examples/public/**/* 8 | examples/pages.json 9 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "examples/themes/casper"] 2 | path = examples/themes/casper 3 | url = https://github.com/grego/casper 4 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "arrayvec" 7 | version = "0.7.6" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" 10 | dependencies = [ 11 | "serde", 12 | ] 13 | 14 | [[package]] 15 | name = "autocfg" 16 | version = "1.4.0" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" 19 | 20 | [[package]] 21 | name = "beef" 22 | version = "0.5.2" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" 25 | dependencies = [ 26 | "serde", 27 | ] 28 | 29 | [[package]] 30 | name = "bitflags" 31 | version = "2.7.0" 32 | source = "registry+https://github.com/rust-lang/crates.io-index" 33 | checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be" 34 | 35 | [[package]] 36 | name = "blades" 37 | version = "1.0.0" 38 | dependencies = [ 39 | "arrayvec", 40 | "beef", 41 | "chrono", 42 | "cmark-syntax", 43 | "fnv", 44 | "hashbrown", 45 | "pulldown-cmark", 46 | "ramhorns", 47 | "serde", 48 | "serde-cmd", 49 | "serde_json", 50 | "thiserror", 51 | "toml", 52 | ] 53 | 54 | [[package]] 55 | name = "chrono" 56 | version = "0.4.39" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825" 59 | dependencies = [ 60 | "num-traits", 61 | "serde", 62 | ] 63 | 64 | [[package]] 65 | name = "cmark-syntax" 66 | version = "0.6.0" 67 | source = "registry+https://github.com/rust-lang/crates.io-index" 68 | checksum = "0c31de348cd530d9a4ae532b8ddca97cb42d88293e80c92db1f9b706af197e56" 69 | dependencies = [ 70 | "latex2mathml", 71 | "logos 0.15.0", 72 | "pulldown-cmark", 73 | ] 74 | 75 | [[package]] 76 | name = "fnv" 77 | version = "1.0.7" 78 | source = "registry+https://github.com/rust-lang/crates.io-index" 79 | checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" 80 | 81 | [[package]] 82 | name = "hashbrown" 83 | version = "0.15.2" 84 | source = "registry+https://github.com/rust-lang/crates.io-index" 85 | checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" 86 | dependencies = [ 87 | "serde", 88 | ] 89 | 90 | [[package]] 91 | name = "heck" 92 | version = "0.5.0" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" 95 | 96 | [[package]] 97 | name = "itoa" 98 | version = "1.0.14" 99 | source = "registry+https://github.com/rust-lang/crates.io-index" 100 | checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" 101 | 102 | [[package]] 103 | name = "latex2mathml" 104 | version = "0.2.3" 105 | source = "registry+https://github.com/rust-lang/crates.io-index" 106 | checksum = "678cf5bdb3ba63a264e6e0c9eee36538ca1d2da0afa4dd801c1f96309e710765" 107 | 108 | [[package]] 109 | name = "lazy_static" 110 | version = "1.5.0" 111 | source = "registry+https://github.com/rust-lang/crates.io-index" 112 | checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" 113 | 114 | [[package]] 115 | name = "logos" 116 | version = "0.14.4" 117 | source = "registry+https://github.com/rust-lang/crates.io-index" 118 | checksum = "7251356ef8cb7aec833ddf598c6cb24d17b689d20b993f9d11a3d764e34e6458" 119 | dependencies = [ 120 | "logos-derive 0.14.4", 121 | ] 122 | 123 | [[package]] 124 | name = "logos" 125 | version = "0.15.0" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "ab6f536c1af4c7cc81edf73da1f8029896e7e1e16a219ef09b184e76a296f3db" 128 | dependencies = [ 129 | "logos-derive 0.15.0", 130 | ] 131 | 132 | [[package]] 133 | name = "logos-codegen" 134 | version = "0.14.4" 135 | source = "registry+https://github.com/rust-lang/crates.io-index" 136 | checksum = "59f80069600c0d66734f5ff52cc42f2dabd6b29d205f333d61fd7832e9e9963f" 137 | dependencies = [ 138 | "beef", 139 | "fnv", 140 | "lazy_static", 141 | "proc-macro2", 142 | "quote", 143 | "regex-syntax", 144 | "syn", 145 | ] 146 | 147 | [[package]] 148 | name = "logos-codegen" 149 | version = "0.15.0" 150 | source = "registry+https://github.com/rust-lang/crates.io-index" 151 | checksum = "189bbfd0b61330abea797e5e9276408f2edbe4f822d7ad08685d67419aafb34e" 152 | dependencies = [ 153 | "beef", 154 | "fnv", 155 | "lazy_static", 156 | "proc-macro2", 157 | "quote", 158 | "regex-syntax", 159 | "rustc_version", 160 | "syn", 161 | ] 162 | 163 | [[package]] 164 | name = "logos-derive" 165 | version = "0.14.4" 166 | source = "registry+https://github.com/rust-lang/crates.io-index" 167 | checksum = "24fb722b06a9dc12adb0963ed585f19fc61dc5413e6a9be9422ef92c091e731d" 168 | dependencies = [ 169 | "logos-codegen 0.14.4", 170 | ] 171 | 172 | [[package]] 173 | name = "logos-derive" 174 | version = "0.15.0" 175 | source = "registry+https://github.com/rust-lang/crates.io-index" 176 | checksum = "ebfe8e1a19049ddbfccbd14ac834b215e11b85b90bab0c2dba7c7b92fb5d5cba" 177 | dependencies = [ 178 | "logos-codegen 0.15.0", 179 | ] 180 | 181 | [[package]] 182 | name = "memchr" 183 | version = "2.7.4" 184 | source = "registry+https://github.com/rust-lang/crates.io-index" 185 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 186 | 187 | [[package]] 188 | name = "num-traits" 189 | version = "0.2.19" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 192 | dependencies = [ 193 | "autocfg", 194 | ] 195 | 196 | [[package]] 197 | name = "proc-macro2" 198 | version = "1.0.93" 199 | source = "registry+https://github.com/rust-lang/crates.io-index" 200 | checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" 201 | dependencies = [ 202 | "unicode-ident", 203 | ] 204 | 205 | [[package]] 206 | name = "pulldown-cmark" 207 | version = "0.12.2" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14" 210 | dependencies = [ 211 | "bitflags", 212 | "memchr", 213 | "pulldown-cmark-escape", 214 | "unicase", 215 | ] 216 | 217 | [[package]] 218 | name = "pulldown-cmark-escape" 219 | version = "0.11.0" 220 | source = "registry+https://github.com/rust-lang/crates.io-index" 221 | checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" 222 | 223 | [[package]] 224 | name = "quote" 225 | version = "1.0.38" 226 | source = "registry+https://github.com/rust-lang/crates.io-index" 227 | checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" 228 | dependencies = [ 229 | "proc-macro2", 230 | ] 231 | 232 | [[package]] 233 | name = "ramhorns" 234 | version = "1.0.1" 235 | source = "registry+https://github.com/rust-lang/crates.io-index" 236 | checksum = "c61d64e28e1069d26c22d4f085ca7f9e2e2eaee16f9d6f80e5fdce62cbf8670f" 237 | dependencies = [ 238 | "arrayvec", 239 | "beef", 240 | "fnv", 241 | "logos 0.14.4", 242 | "pulldown-cmark", 243 | "ramhorns-derive", 244 | ] 245 | 246 | [[package]] 247 | name = "ramhorns-derive" 248 | version = "1.0.1" 249 | source = "registry+https://github.com/rust-lang/crates.io-index" 250 | checksum = "c55c1eb278808d0120a6dd2109f39a8da8fd279fc9bfcd5511e9b13e41dfcae9" 251 | dependencies = [ 252 | "fnv", 253 | "heck", 254 | "proc-macro2", 255 | "quote", 256 | "syn", 257 | ] 258 | 259 | [[package]] 260 | name = "regex-syntax" 261 | version = "0.8.5" 262 | source = "registry+https://github.com/rust-lang/crates.io-index" 263 | checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" 264 | 265 | [[package]] 266 | name = "rustc_version" 267 | version = "0.4.1" 268 | source = "registry+https://github.com/rust-lang/crates.io-index" 269 | checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" 270 | dependencies = [ 271 | "semver", 272 | ] 273 | 274 | [[package]] 275 | name = "ryu" 276 | version = "1.0.18" 277 | source = "registry+https://github.com/rust-lang/crates.io-index" 278 | checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" 279 | 280 | [[package]] 281 | name = "semver" 282 | version = "1.0.24" 283 | source = "registry+https://github.com/rust-lang/crates.io-index" 284 | checksum = "3cb6eb87a131f756572d7fb904f6e7b68633f09cca868c5df1c4b8d1a694bbba" 285 | 286 | [[package]] 287 | name = "serde" 288 | version = "1.0.217" 289 | source = "registry+https://github.com/rust-lang/crates.io-index" 290 | checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" 291 | dependencies = [ 292 | "serde_derive", 293 | ] 294 | 295 | [[package]] 296 | name = "serde-cmd" 297 | version = "0.1.3" 298 | source = "registry+https://github.com/rust-lang/crates.io-index" 299 | checksum = "a028d1e0d8ef44f5e726821adf48b1c62ddf0c2c0332cd527b79e1626d1cc865" 300 | dependencies = [ 301 | "serde", 302 | ] 303 | 304 | [[package]] 305 | name = "serde_derive" 306 | version = "1.0.217" 307 | source = "registry+https://github.com/rust-lang/crates.io-index" 308 | checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" 309 | dependencies = [ 310 | "proc-macro2", 311 | "quote", 312 | "syn", 313 | ] 314 | 315 | [[package]] 316 | name = "serde_json" 317 | version = "1.0.135" 318 | source = "registry+https://github.com/rust-lang/crates.io-index" 319 | checksum = "2b0d7ba2887406110130a978386c4e1befb98c674b4fba677954e4db976630d9" 320 | dependencies = [ 321 | "itoa", 322 | "memchr", 323 | "ryu", 324 | "serde", 325 | ] 326 | 327 | [[package]] 328 | name = "syn" 329 | version = "2.0.96" 330 | source = "registry+https://github.com/rust-lang/crates.io-index" 331 | checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80" 332 | dependencies = [ 333 | "proc-macro2", 334 | "quote", 335 | "unicode-ident", 336 | ] 337 | 338 | [[package]] 339 | name = "thiserror" 340 | version = "2.0.11" 341 | source = "registry+https://github.com/rust-lang/crates.io-index" 342 | checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc" 343 | dependencies = [ 344 | "thiserror-impl", 345 | ] 346 | 347 | [[package]] 348 | name = "thiserror-impl" 349 | version = "2.0.11" 350 | source = "registry+https://github.com/rust-lang/crates.io-index" 351 | checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" 352 | dependencies = [ 353 | "proc-macro2", 354 | "quote", 355 | "syn", 356 | ] 357 | 358 | [[package]] 359 | name = "toml" 360 | version = "0.5.11" 361 | source = "registry+https://github.com/rust-lang/crates.io-index" 362 | checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" 363 | dependencies = [ 364 | "serde", 365 | ] 366 | 367 | [[package]] 368 | name = "unicase" 369 | version = "2.8.1" 370 | source = "registry+https://github.com/rust-lang/crates.io-index" 371 | checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" 372 | 373 | [[package]] 374 | name = "unicode-ident" 375 | version = "1.0.14" 376 | source = "registry+https://github.com/rust-lang/crates.io-index" 377 | checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" 378 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "blades" 3 | version = "0.6.0" 4 | authors = ["Maroš Grego "] 5 | edition = "2021" 6 | description = "Blazing fast dead simple static site generator" 7 | repository = "https://github.com/grego/blades" 8 | keywords = ["website", "site", "generator"] 9 | categories = ["command-line-utilities", "web-programming"] 10 | license = "GPL-3.0-or-later" 11 | readme = "README.md" 12 | homepage = "https://getblades.org" 13 | 14 | [dependencies] 15 | ramhorns = "^1.0.1" 16 | arrayvec = { version = "0.7", features = ["serde"] } 17 | beef = { version = "0.5", features = ["impl_serde"]} 18 | serde = { version = "^1.0.126", features = ["derive"] } 19 | chrono = { version = "^0.4.19", features = ["std", "serde"], default-features = false } 20 | fnv = "1.0" 21 | hashbrown = { version = "0.15", features = ["inline-more", "serde", "raw-entry"], default-features = false } 22 | pulldown-cmark = { version = "0.12", default-features = false, features = ["html"] } 23 | cmark-syntax = "^0.6" 24 | 25 | # Cargo doesn't support binary-only dependencies yet. 26 | toml = { version = "0.5.9", optional = true } 27 | thiserror = { version = "2", optional = true } 28 | serde_json = { version = "1", optional = true } 29 | serde-cmd = { version = "0.1.3", optional = true } 30 | 31 | [features] 32 | bin = ["toml", "thiserror", "serde_json", "serde-cmd"] 33 | mathml = ["cmark-syntax/latex2mathml"] 34 | default = ["bin", "mathml"] 35 | 36 | [profile.release] 37 | lto = true 38 | opt-level = 3 39 | strip = "debuginfo" 40 | panic = "abort" 41 | codegen-units = 1 42 | 43 | [profile.bench] 44 | lto = true 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Blades logo 2 | 3 | # Blades 4 | 5 | [![Crates.io status](https://badgen.net/crates/v/blades)](https://crates.io/crates/blades) 6 | [![Docs](https://docs.rs/blades/badge.svg)](https://docs.rs/blades) 7 | 8 | ``` 9 | blazing fast 10 | dead simple 11 | static site generator 12 | ``` 13 | 14 | [User manual](http://www.getblades.org) 15 | 16 | Blades is made to do one job and do it well - generate HTML files from the provided 17 | content using the provided templates. 18 | Thanks to [zero-copy](https://serde.rs/lifetimes.html#borrowing-data-in-a-derived-impl) deserialization 19 | and the [Ramhorns](https://github.com/maciejhirsz/ramhorns) templating engine, 20 | it renders the whole site in milliseconds, possibly more than 21 | [20 times](https://github.com/grego/ssg-bench) faster than other generators like Hugo. 22 | 23 | It's made for easy setup and use. A static site generator should be a no brainer. 24 | It uses [mustache](https://mustache.github.io/mustache.5.html) templates with extremely minimal 25 | and obvious syntax (like 7 rules!), providing the necessary building blocks 26 | to let you focus on your content. 27 | 28 | ## Features 29 | * Powerful plugin system 30 | * Themes 31 | * Image gallery generation 32 | * [CommonMark](https://commonmark.org) markdown with tables and footnotes for content 33 | * Rendering of LaTeX formulas into [MathML](https://developer.mozilla.org/docs/Web/MathML), 34 | (supported by [all major browsers](https://caniuse.com/mathml)), with content between 35 | `$` rendered in inline mode and content between `$$` rendered in display mode. 36 | * Syntax highlighting using [cmark-syntax](https://github.com/grego/cmark-syntax) 37 | * Customizable taxonomies (like categories or tags) 38 | * Pagination 39 | * Breadcrumbs 40 | * Asset colocation 41 | * Table of contents with access to all of the site data 42 | * Automatic sitemap, Atom and RSS feed generation 43 | 44 | ## Why not _`blades`_? 45 | Unlike other monolithic generators, Blades is modest in scope. All it does is to generate a site. 46 | It doesn't do any fancy stuff like transpiling Haskell to minified Javascript, or ever 47 | watching the site for changes. For that, you can use a dedicated tool like 48 | [caretaker](https://github.com/grego/caretaker). 49 | 50 | Nevertheless, if you have a feature request or ran into some issue using Blades, please submit an 51 | [issue](https://github.com/grego/blades). Any contribution is welcome! `:)` 52 | 53 | ## Why _`blades`_? 54 | They shave the [mustache](https://mustache.github.io/mustache.5.html) off. 55 | 56 | ## Installing 57 | With the Rust toolchain installed, you can install Blades from [crates.io](https://crates.io/crates/blades) 58 | ```bash 59 | cargo install blades 60 | ``` 61 | 62 | Or from its repository 63 | ```bash 64 | git clone https://github.com/grego/blades 65 | cd blades 66 | cargo install --path . 67 | ``` 68 | 69 | ## macOS 70 | Using the package manager [Homebrew](https://www.brew.sh) 71 | ```bash 72 | brew install blades 73 | ``` 74 | 75 | Using the package manager [MacPorts](https://www.macports.org) 76 | ```bash 77 | sudo port install blades 78 | ``` 79 | 80 | ## Running 81 | Then, you can run the executable `blades` with the following subcommands: 82 | * `init`: Initialize the site in the current directory, creating the basic files and folders 83 | * `build`: Build the site according to config, content, templates and themes in the current directory 84 | * `colocate`: Move the assets from the "assets" directory and from the theme, if one is used, into the output directory 85 | * `all`: Build the site and colocate the assets 86 | * `lazy`: Build the site and (colocate assets only if the theme was switched) [default] 87 | * `new`: Create a new page 88 | 89 | ## Plugins 90 | There are 4 types of plugins that can be used with Blades. 91 | * **input** - they put a JSON-serialised list of [pages](https://www.getblades.org/pages.html) on the standard output, can be used 92 | to get pages from different sources 93 | * **output** - they receive a JSON-serialised list of [pages](https://www.getblades.org/pages.html) on the standard input and can be 94 | used to generate further page data, such as processing images 95 | * **transform** - they receive a JSON-serialised list of [pages](https://www.getblades.org/pages.html) on the standard output and output 96 | another such list on the standard output, can transform anything on the pages 97 | * **content** - they receive a markdown content of one page on standard input and output markdown on the standard output; they are enabled 98 | on per-page basis 99 | 100 | Any code in any language can be used, as only using the standard input and output is assumed. For Rust, Blades also provides a 101 | [library](https://docs.rs/blades) for automatic serialisation and deserialisation pages. 102 | 103 | ### Example 104 | Example plugin configuration can be found in [examples](examples/Blades.toml), as well as an 105 | example toy [transform plugin](examples/transform_plugin.rs). 106 | To try it, first build the plugin: 107 | ```bash 108 | cargo build --release transform_plugin 109 | ``` 110 | Then run Blades in the `examples` directory: 111 | ```bash 112 | cargo run --release 113 | ``` 114 | 115 | For more on plugins, check their [documentation](https://www.getblades.org/making-plugins.html) and 116 | [existing plugins](https://www.getblades.org/plugins/) 117 | 118 | ## Themes 119 | When you specify a theme in the [config](https://www.getblades.org/config.html), templates and assets from the theme are used. 120 | Every site that doesn't use a theme can be used as a theme for another site. 121 | Therefore, the easiest way to use a theme is to just clone the corresponding theme's repository 122 | into the `themes` directory. A list of available themes can be found [here](https://www.getblades.org/themes/). 123 | 124 | To overwrite the theme, simply use the files in the `templates`, resp. `assets` subdirectories of the 125 | page root directory. 126 | 127 | When initializing a Blades project with `blades init`, it provides an option to start with 128 | a minimal working template to allow you to quickly start working on your content. 129 | 130 | ## Assets 131 | All the files from the `assets` directory (and from the theme) are moved into the directory 132 | specified in the [config](https://www.getblades.org/config.html), which is emptied before. This is a subdirectory of the 133 | output directory (defaults to `assets`). 134 | 135 | Blades takes of the pages it rendered before and if some of them is deleted, the corresponding 136 | files in the output directory will be deleted, too. The other files in the output directory 137 | are left intact. This way, you can place anything in the output directory and (as long as its name 138 | differs from all the page names and it's not in the assets subdirectory), Blades won't touch it. 139 | 140 | ## Meta 141 | Blades renders [sitemap](https://www.sitemaps.org) (into `sitemap.xml`), [Atom](https://en.wikipedia.org/wiki/Atom_(Web_standard)) (into `atom.xml`) 142 | and [RSS](https://en.wikipedia.org/wiki/RSS) (into `rss.xml`) feeds, unless explicitly disabled in the [config](https://www.getblades.org/config.html). 143 | 144 | ## Using Blades as a library 145 | Main components of Blades are also exported as a library. They are parser agnostic, so they can be used 146 | to generate a website using any format that implements `serde::Deserialize`. 147 | Currently, Cargo doesn't support binary-only dependencies. As such, these dependencies are behind 148 | the `bin` feature gate, which is enabled by default. When using Blades as a library, they are not 149 | necessary, so it is recommended to import blades with `default_features = false`. 150 | 151 | ## Contribution 152 | If you found a bug or would like to see some feature in Blades, you are the most welcome to submit an issue 153 | or a pull request! Likewise if you found something in this documentation not clear or imprecise. 154 | 155 | ## License 156 | Blades is free software, and is released under the terms of the GNU General Public 157 | License version 3. See [LICENSE](LICENSE). 158 | -------------------------------------------------------------------------------- /benches/main.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | extern crate test; 3 | use blades::{Page, Parser, Sources}; 4 | use std::thread; 5 | use test::{black_box, Bencher}; 6 | 7 | static SOURCE: &str = "{{title}}

{{ title }}

{{{body}}}
"; 8 | const RENDERED_BYTES: u64 = 9 | "Hello, Ramhorns!This is a really simple test of the rendering!

".len() as u64; 10 | 11 | #[derive(Default)] 12 | struct Toml; 13 | 14 | impl Parser for Toml { 15 | type Error = toml::de::Error; 16 | 17 | fn from_extension(_ext: &std::ffi::OsStr) -> Option { 18 | Some(Toml) 19 | } 20 | 21 | fn parse<'a>(&self, data: &'a [u8]) -> Result, Self::Error> { 22 | toml::de::from_slice(data) 23 | } 24 | } 25 | 26 | #[bench] 27 | fn fnv_hashmap(b: &mut Bencher) { 28 | let tpl = ramhorns::Template::new(SOURCE).unwrap(); 29 | 30 | let mut map: std::collections::HashMap<_, _, fnv::FnvBuildHasher> = Default::default(); 31 | map.insert("title", "Hello, Ramhorns!"); 32 | map.insert("body", "This is a really simple test of the rendering!"); 33 | 34 | b.bytes = RENDERED_BYTES; 35 | b.iter(|| black_box(tpl.render(&map))); 36 | } 37 | 38 | #[bench] 39 | fn blades_hashmap(b: &mut Bencher) { 40 | let tpl = ramhorns::Template::new(SOURCE).unwrap(); 41 | 42 | let mut map = blades::HashMap::default(); 43 | map.insert("title", "Hello, Ramhorns!"); 44 | map.insert("body", "This is a really simple test of the rendering!"); 45 | 46 | b.bytes = RENDERED_BYTES; 47 | b.iter(|| black_box(tpl.render(&map))); 48 | } 49 | 50 | #[bench] 51 | fn parse_pages(b: &mut Bencher) { 52 | let sources: Sources = Sources::load("examples/content").unwrap(); 53 | b.iter(|| { 54 | sources 55 | .sources() 56 | .iter() 57 | .map(|src| Page::new(src, &sources)) 58 | .collect::>() 59 | }); 60 | } 61 | 62 | #[bench] 63 | fn spawn_and_join(b: &mut Bencher) { 64 | b.iter(|| thread::spawn(|| 1 + 2).join()); 65 | } 66 | -------------------------------------------------------------------------------- /examples/Blades.toml: -------------------------------------------------------------------------------- 1 | title = "My site!" 2 | 3 | [plugins] 4 | input = ["cat input.json"] 5 | transform = ["../target/release/examples/transform_plugin"] 6 | output = ["dd status=none of=pages.json"] 7 | 8 | [plugins.content] 9 | erase = "echo \"hahaha erased\"" 10 | -------------------------------------------------------------------------------- /examples/assets/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 13 | 15 | 21 | 27 | 28 | 30 | 31 | 33 | image/svg+xml 34 | 36 | 37 | 38 | 39 | 40 | 43 | 47 | 51 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /examples/content/about/index.toml: -------------------------------------------------------------------------------- 1 | title = "About" 2 | plugins = ["erase"] 3 | content = """ 4 | Tuvan throat singing, Khoomei, is one particular variant of overtone singing practiced by people in Tuva and Siberia. In 2009, it was inscribed on the Representative List of the Intangible Cultural Heritage of Humanity of UNESCO. 5 | """ 6 | -------------------------------------------------------------------------------- /examples/content/gallery.toml: -------------------------------------------------------------------------------- 1 | title = "A gallery" 2 | date = 2020-09-19 3 | image = "img/gallery.jpg" 4 | summary = "Open this post to see a gallery!" 5 | content = """ 6 | This page is just a placeholder 7 | To show you a functionality 8 | Of generating 9 | A picture gallery 10 | 11 | With this generator 12 | """ 13 | gallery = true 14 | 15 | [[pictures]] 16 | file = "/assets/logo.svg" 17 | alt = "A trash can." 18 | caption = "a view of reality" 19 | pid = "tiles" 20 | 21 | [taxonomies] 22 | tags = ["finger", "lisp"] 23 | -------------------------------------------------------------------------------- /examples/content/index.toml: -------------------------------------------------------------------------------- 1 | title = "Index" 2 | paginate_by = 3 3 | -------------------------------------------------------------------------------- /examples/content/mu.md: -------------------------------------------------------------------------------- 1 | +++ 2 | title = "Mu" 3 | date = 2020-09-18 4 | image = "img/mu.jpg" 5 | summary = """A monk asked Joshu, "Has the dog the Buddha nature?" """ 6 | 7 | [taxonomies] 8 | tags = ["pets"] 9 | +++ 10 | A monk asked Joshu, "Has the dog the Buddha nature?"[^cool] 11 | Joshu replied, "Mu" 12 | 13 | $$\sum_{n=0}^\infty \frac{1}{n^2}$$ 14 | 15 | ### Mumon's Comment: 16 | > For the pursuit of Zen, you must pass through the barriers (gates) set up by the Zen masters. To attain his mysterious awareness one must completely uproot all the normal workings of one's mind. If you do not pass through the barriers, nor uproot the normal workings of your mind, whatever you do and whatever you think is a tangle of ghost. Now what are the barriers? This one word "Mu" is the sole barrier. This is why it is called the Gateless Gate of Zen. The one who passes through this barrier shall meet with Joshu face to face and also see with the same eyes, hear with the same ears and walk together in the long train of the patriarchs. Wouldn't that be pleasant? 17 | > Would you like to pass through this barrier? Then concentrate your whole body, with its 360 bones and joints, and 84,000 hair follicles, into this question of what "Mu" is; day and night, without ceasing, hold it before you. It is neither nothingness, nor its relative "not" of "is" and "is not." It must be like gulping a hot iron ball that you can neither swallow nor spit out. 18 | 19 | ```rust 20 | #[inline] 21 | pub(crate) fn render_content(source: &str, encoder: &mut E) -> Result<(), E::Error> { 22 | let parser = pulldown_cmark::Parser::new_ext(source, pulldown_cmark::Options::all()); 23 | let processed = cmark_syntax::SyntaxPreprocessor::new(parser); 24 | encoder.write_html(processed) 25 | } 26 | ``` 27 | 28 | [^cool]: This is a really cool story. 29 | -------------------------------------------------------------------------------- /examples/input.json: -------------------------------------------------------------------------------- 1 | [{"title":"Random page","slug":"random","summary":"A port of a random page.","taxonomies":{"tags":["another"]}},{"title":"Another section","slug":"more","content":"This section is another.\n","is_section":true,"taxonomies":{"tags":["more"]}},{"title":"Another page","slug":"another","path":"more","content":"This page is another.\n","taxonomies":{"tags":["more"]}}] 2 | -------------------------------------------------------------------------------- /examples/templates/gallery.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{#parent title}}{{title}} | {{/title parent}}{{site title}} 5 | 6 | 7 | 8 | {{#current}}
9 | {{alt}} 10 |
{{caption}}
11 |
{{/current}} 12 | {{#previous}}{{/previous}} 13 | {{#parent}}{{title}}{{/parent}} 14 | {{#next}}{{/next}} 15 | 16 | 17 | -------------------------------------------------------------------------------- /examples/templates/page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{#title}}{{title}} | {{/title}}{{site title}} 5 | 6 | 7 | 8 |

{{title}}

9 |

{{#date}}{{d}}/{{m}}/{{y}} | {{/date}}{{site title}}

10 | {{content}} 11 | {{#pictures}} 12 |
13 | {{alt}} 14 | 15 |
16 |
{{/pictures}} 17 | 18 | 19 | -------------------------------------------------------------------------------- /examples/templates/section.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{#title}}{{title}} | {{/title}}{{site title}} 5 | 6 | 7 | 8 |

{{title}}

9 | 10 | {{content}} 11 | 13 | {{#pictures}} 14 |
15 | {{alt}} 16 | 17 |
18 |
{{/pictures}} 19 | 20 | 21 | -------------------------------------------------------------------------------- /examples/templates/taxonomy.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{#title}}{{title}} | {{/title}}{{site title}} 5 | 6 | 7 | 8 |

{{title}}

9 | {{description}} 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /examples/templates/taxonomy_key.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{#title}}{{title}} | {{/title}}{{site title}} 5 | 6 | 7 | 8 |

{{taxonomy title}}: {{title}}

9 | {{#site}}{{title}}{{/site}} 10 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /examples/transform_plugin.rs: -------------------------------------------------------------------------------- 1 | use blades::Page; 2 | use std::io::Read; 3 | 4 | fn main() -> Result<(), Box> { 5 | let mut source = Vec::new(); 6 | std::io::stdin().read_to_end(&mut source)?; 7 | // When deserializing from a slice, zero-copy deserialiation can be used 8 | let mut pages: Vec = serde_json::from_slice(&source)?; 9 | 10 | for page in &mut pages { 11 | if page.content.find("dog").is_some() { 12 | page.summary = "WARNING! CONTAINS DOGS!".into(); 13 | } 14 | } 15 | 16 | serde_json::to_writer(std::io::stdout(), &pages)?; 17 | Ok(()) 18 | } 19 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Blades Copyright (C) 2021 Maroš Grego 2 | // 3 | // This file is part of Blades. This program comes with ABSOLUTELY NO WARRANTY; 4 | // This is free software, and you are welcome to redistribute it under the 5 | // conditions of the GNU General Public License version 3.0. 6 | // 7 | // You should have received a copy of the GNU General Public License 8 | // along with Blades. If not, see 9 | 10 | //! Blazing fast 11 | //! dead simple 12 | //! static site generator. 13 | //! 14 | //! # Features 15 | //! Currently, Cargo doesn't support binary-only dependencies. As such, these dependencies are behind 16 | //! the `bin` feature gate, which is enabled by default. When using Blades as a library, they are not 17 | //! necessary, so it is recommended to import blades with `default_features = false`. 18 | #![warn(missing_docs)] 19 | mod page; 20 | mod render; 21 | mod site; 22 | mod sources; 23 | mod taxonomies; 24 | mod types; 25 | 26 | pub use page::{Context, Page, Pages, Picture}; 27 | pub use render::render_meta; 28 | pub use site::Site; 29 | pub use sources::{Parser, Source, Sources}; 30 | pub use taxonomies::{TaxonMeta, Taxonomies, Taxonomy}; 31 | pub use types::{Ancestors, Any, DateTime, HashMap}; 32 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // Blades Copyright (C) 2021 Maroš Grego 2 | // 3 | // This file is part of Blades. This program comes with ABSOLUTELY NO WARRANTY; 4 | // This is free software, and you are welcome to redistribute it under the 5 | // conditions of the GNU General Public License version 3.0. 6 | // 7 | // You should have received a copy of the GNU General Public License 8 | // along with Blades. If not, see 9 | use blades::*; 10 | 11 | use beef::lean::Cow; 12 | use ramhorns::{Content, Ramhorns, Template}; 13 | use serde::Deserialize; 14 | use serde_cmd::CmdBorrowed; 15 | 16 | use std::collections::BTreeSet; 17 | use std::env; 18 | use std::ffi::OsStr; 19 | use std::fs::{self, File}; 20 | use std::io::{self, stdin, stdout, BufRead, BufReader, BufWriter, ErrorKind, Lines, Write}; 21 | use std::path::{self, Path, PathBuf}; 22 | use std::process::{Command, Output, Stdio}; 23 | use std::time::{Instant, SystemTime}; 24 | use std::{cmp, thread}; 25 | use thiserror::Error; 26 | 27 | static HELP: &str = r#"Blazing fast dead simple static site generator 28 | 29 | Usage: blades [COMMAND] 30 | 31 | Commands: 32 | init Initialize the site in the current directory, creating the basic files and folders 33 | new Create a new page 34 | build Build the site according to config, content, templates and themes in the current directory 35 | colocate Move assets from the "assets" directory and from the theme, if one is used, into the output directory 36 | all Build the site and colocate the assets 37 | lazy Build the site and (colocate assets only if the theme was switched) [default] 38 | help Print this message 39 | version Print version information 40 | 41 | Environment variables: 42 | BLADES_CONFIG File to read the site config from [default: Blades.toml] 43 | "#; 44 | static VAR_CONFIG: &str = "BLADES_CONFIG"; 45 | static CONFIG_FILE: &str = "Blades.toml"; 46 | 47 | const BUFFER_SIZE: usize = 16384; 48 | 49 | #[derive(PartialEq, Eq)] 50 | enum Cmd { 51 | Init, 52 | New, 53 | Build, 54 | Colocate, 55 | All, 56 | Lazy, 57 | Help, 58 | Version, 59 | Invalid, 60 | } 61 | 62 | /// Main configuration where all the site settings are set. 63 | /// Blades deserializes it from a given TOML file. 64 | #[derive(Default, Deserialize)] 65 | struct Config<'c> { 66 | /// The directory of the content 67 | #[serde(borrow, default = "default_content_dir")] 68 | content_dir: Cow<'c, str>, 69 | /// The directory where the output should be rendered to 70 | #[serde(borrow, default = "default_output_dir")] 71 | output_dir: Cow<'c, str>, 72 | /// The directory where the themes are 73 | #[serde(borrow, default = "default_theme_dir")] 74 | theme_dir: Cow<'c, str>, 75 | /// Name of the directory of a theme this site is using, empty if none. 76 | #[serde(borrow, default)] 77 | theme: Cow<'c, str>, 78 | /// Taxonomies of the site 79 | #[serde(default)] 80 | taxonomies: HashMap<&'c str, TaxonMeta<'c>>, 81 | /// Generate taxonomies not specified in the config? 82 | #[serde(default = "default_true")] 83 | implicit_taxonomies: bool, 84 | 85 | /// Information about the site usable in templates 86 | #[serde(flatten)] 87 | site: Site<'c>, 88 | 89 | /// Configuration of plugins for building the site. 90 | #[serde(default)] 91 | plugins: Plugins<'c>, 92 | } 93 | 94 | /// Plugins to use when building the site. 95 | #[derive(Default, Deserialize)] 96 | struct Plugins<'p> { 97 | /// Plugins to get the input from, in the form of serialized list of pages. 98 | #[serde(borrow, default)] 99 | input: Box<[CmdBorrowed<'p>]>, 100 | /// Plugins that transform the serialized list of pages. 101 | #[serde(borrow, default)] 102 | transform: Box<[CmdBorrowed<'p>]>, 103 | /// Plugins that get the serialized list of pages and might do something with it. 104 | #[serde(borrow, default)] 105 | output: Box<[CmdBorrowed<'p>]>, 106 | /// Plugins that transform the content of pages. 107 | /// They are identified by their name and must be enabled for each page. 108 | #[serde(borrow, default)] 109 | content: HashMap<&'p str, CmdBorrowed<'p>>, 110 | /// A list of names of content plugins that should be applied to every page. 111 | #[serde(default)] 112 | default: Box<[&'p str]>, 113 | } 114 | 115 | #[inline] 116 | const fn default_content_dir() -> Cow<'static, str> { 117 | Cow::const_str("content") 118 | } 119 | 120 | #[inline] 121 | const fn default_output_dir() -> Cow<'static, str> { 122 | Cow::const_str("public") 123 | } 124 | 125 | #[inline] 126 | const fn default_theme_dir() -> Cow<'static, str> { 127 | Cow::const_str("themes") 128 | } 129 | 130 | #[inline] 131 | const fn default_true() -> bool { 132 | true 133 | } 134 | 135 | /// Where the templates are located, relative to the site directrory. 136 | static TEMPLATE_DIR: &str = "templates"; 137 | /// Where the assets will be copied from, relative to the site directrory. 138 | static ASSET_SRC_DIR: &str = "assets"; 139 | static FILELIST: &str = ".blades"; 140 | static OLD_THEME: &str = ".bladestheme"; 141 | 142 | #[derive(Content)] 143 | struct MockConfig { 144 | title: String, 145 | author: String, 146 | } 147 | 148 | #[derive(Content)] 149 | struct MockPage { 150 | title: String, 151 | slug: String, 152 | date: String, 153 | } 154 | 155 | /// Possible formats of the source. 156 | #[derive(Default)] 157 | enum Format { 158 | #[default] 159 | Toml, 160 | Markdown, 161 | } 162 | 163 | #[derive(Debug, Error)] 164 | enum ParseError { 165 | #[error("TOML error: {0}")] 166 | Toml(#[from] toml::de::Error), 167 | #[error("Invalid UTF8: {0}")] 168 | Utf8(#[from] std::str::Utf8Error), 169 | } 170 | 171 | #[derive(Debug, Error)] 172 | enum Error { 173 | #[error("I/O error: {0}")] 174 | Io(#[from] std::io::Error), 175 | #[error("Template error: {0}")] 176 | Ramhorns(#[from] ramhorns::Error), 177 | #[error("Error parsing {1}: {0}")] 178 | Parse(ParseError, Box), 179 | #[error("JSON error: {0}")] 180 | Json(#[from] serde_json::Error), 181 | #[error("Error in plugin {0}: {1}")] 182 | Plugin(Box, Box), 183 | #[error("Plugin {0} returned invalid UTF8 data: {1}")] 184 | Utf8(Box, std::string::FromUtf8Error), 185 | } 186 | 187 | impl From<(ParseError, Box)> for Error { 188 | fn from((e, s): (ParseError, Box)) -> Self { 189 | Self::Parse(e, s) 190 | } 191 | } 192 | 193 | /// A helper trait to simplify the command logic. 194 | trait OutputResult { 195 | fn output_result(self, name: &str) -> Result, Error>; 196 | } 197 | 198 | impl OutputResult for Output { 199 | fn output_result(self, name: &str) -> Result, Error> { 200 | if self.status.success() { 201 | Ok(self.stdout) 202 | } else { 203 | Err(Error::Plugin( 204 | name.into(), 205 | String::from_utf8_lossy(&self.stderr).into(), 206 | )) 207 | } 208 | } 209 | } 210 | 211 | impl Parser for Format { 212 | type Error = ParseError; 213 | 214 | /// The kind of parser that should be used, based on the file extension. 215 | fn from_extension(ext: &OsStr) -> Option { 216 | if ext == "toml" { 217 | Some(Format::Toml) 218 | } else if ext == "md" { 219 | Some(Format::Markdown) 220 | } else { 221 | None 222 | } 223 | } 224 | 225 | /// Parse the binary data into a Page. 226 | fn parse<'a>(&self, data: &'a [u8]) -> Result, Self::Error> { 227 | Ok(match self { 228 | Format::Toml => toml::from_slice(data)?, 229 | Format::Markdown => { 230 | let (header, content) = separate_md_header(data); 231 | let mut page: Page = toml::from_slice(header)?; 232 | let content = std::str::from_utf8(content)?; 233 | page.content = content.trim().into(); 234 | page 235 | } 236 | }) 237 | } 238 | } 239 | 240 | /// Separate a TOML header in `+++` from the markdown file. 241 | #[inline] 242 | fn separate_md_header(source: &[u8]) -> (&[u8], &[u8]) { 243 | if source.len() < 4 || &source[..3] != b"+++" { 244 | return (&[], source); 245 | } 246 | 247 | enum State { 248 | None, 249 | Quote(u8), 250 | } 251 | let mut state = State::None; 252 | for (len, w) in source 253 | .windows(3) 254 | .map(|w| [w[0], w[1], w[2]]) 255 | .enumerate() 256 | .skip(3) 257 | { 258 | if (w[1] == b'"' || w[1] == b'\'') && w[0] != b'\\' { 259 | state = match state { 260 | State::None => State::Quote(w[1]), 261 | State::Quote(q) if q == w[1] => State::None, 262 | State::Quote(r) => State::Quote(r), 263 | } 264 | } else if let State::None = state { 265 | if w == [b'+', b'+', b'+'] { 266 | if source.len() <= len + 3 { 267 | return (&source[3..len], &[]); 268 | } else { 269 | return (&source[3..len], &source[len + 3..]); 270 | } 271 | } 272 | } 273 | } 274 | (&source[3..], &[]) 275 | } 276 | 277 | trait Unwind { 278 | type Value; 279 | 280 | fn unwind(self) -> Self::Value; 281 | } 282 | 283 | impl Unwind for thread::Result { 284 | type Value = T; 285 | 286 | fn unwind(self) -> T { 287 | match self { 288 | Ok(t) => t, 289 | Err(e) => std::panic::resume_unwind(e), 290 | } 291 | } 292 | } 293 | 294 | /// Get the next line from the standard input after displaying some message 295 | fn next_line(lines: &mut Lines, message: &str) -> Result { 296 | print!("{} ", message); 297 | stdout().flush()?; 298 | lines.next().transpose().map(|s| s.unwrap_or_default()) 299 | } 300 | 301 | /// Initialise the site 302 | fn init() -> Result<(), Error> { 303 | println!("Enter the basic site info"); 304 | let mut lines = BufReader::new(stdin().lock()).lines(); 305 | let title = next_line(&mut lines, "Name:")?; 306 | let author = next_line(&mut lines, "Author:")?; 307 | let config = MockConfig { title, author }; 308 | Template::new(include_str!("templates/Blades.toml"))?.render_to_file(CONFIG_FILE, &config)?; 309 | fs::create_dir_all("content")?; 310 | let thm = next_line(&mut lines, "Start with a minimal working template? (Select no to use a theme; then put the theme inside the 'themes' directory.) [Y/n]")?; 311 | if &thm == "n" || &thm == "N" || &thm == "no" || &thm == "No" { 312 | fs::create_dir_all("themes").map_err(Into::into) 313 | } else { 314 | fs::create_dir_all("templates")?; 315 | fs::write( 316 | "templates/page.html", 317 | include_str!("../examples/templates/page.html"), 318 | )?; 319 | fs::write( 320 | "templates/section.html", 321 | include_str!("../examples/templates/section.html"), 322 | )?; 323 | fs::write( 324 | "templates/taxonomy.html", 325 | include_str!("../examples/templates/taxonomy.html"), 326 | )?; 327 | fs::write( 328 | "templates/taxonomy_key.html", 329 | include_str!("../examples/templates/taxonomy_key.html"), 330 | )?; 331 | fs::write( 332 | "templates/gallery.html", 333 | include_str!("../examples/templates/gallery.html"), 334 | )?; 335 | Ok(()) 336 | } 337 | } 338 | 339 | /// Create a new page and edit it if the EDITOR variable is set 340 | fn new_page(config: &Config) -> Result<(), Error> { 341 | println!("Enter the basic info of the new page"); 342 | let mut lines = BufReader::new(stdin().lock()).lines(); 343 | let title = next_line(&mut lines, "Title:")?; 344 | let slug = next_line(&mut lines, "Slug (short name in the URL):")?; 345 | let mut path = Path::new(config.content_dir.as_ref()).join(next_line( 346 | &mut lines, 347 | "Path (relative to the content directory):", 348 | )?); 349 | fs::create_dir_all(&path)?; 350 | 351 | let date: chrono::DateTime = SystemTime::now().into(); 352 | let date = date.format("%Y-%m-%d").to_string(); 353 | path.push(format!("{}-{}.toml", &date, &slug)); 354 | 355 | if path.exists() { 356 | let mut answer = next_line( 357 | &mut lines, 358 | &format!( 359 | "The path {:?} already exists, do you want to overwrite in? [y/N]", 360 | &path 361 | ), 362 | )?; 363 | answer.make_ascii_lowercase(); 364 | if answer != "y" || answer != "yes" { 365 | return Ok(()); 366 | } 367 | } 368 | let page = MockPage { title, slug, date }; 369 | Template::new(include_str!("templates/page.toml"))?.render_to_file(&path, &page)?; 370 | println!("{:?} created", &path); 371 | 372 | if let Ok(editor) = env::var("EDITOR") { 373 | Command::new(editor).arg(&path).status()?; 374 | } else { 375 | println!("Set the EDITOR environment variable to edit new pages immediately"); 376 | } 377 | Ok(()) 378 | } 379 | 380 | fn copy_dir(src: &mut PathBuf, dest: &mut PathBuf) -> Result<(), io::Error> { 381 | let iter = match fs::read_dir(&src) { 382 | Ok(iter) => iter, 383 | Err(e) if e.kind() == ErrorKind::NotFound => return Ok(()), 384 | Err(e) => return Err(e), 385 | }; 386 | fs::create_dir_all(&dest)?; 387 | for entry in iter.filter_map(Result::ok) { 388 | let file_type = entry.file_type()?; 389 | let file_name = entry.file_name(); 390 | src.push(&file_name); 391 | dest.push(&file_name); 392 | if file_type.is_file() { 393 | fs::copy(&src, &dest)?; 394 | } else if file_type.is_dir() { 395 | copy_dir(src, dest)?; 396 | } 397 | src.pop(); 398 | dest.pop(); 399 | } 400 | Ok(()) 401 | } 402 | 403 | /// Place assets located in the `assets` directory or in the `assets` subdirectory of the theme, 404 | /// if used, into a dedicated subdirectory of the output directory specified in the config 405 | /// (defaults to `assets`, too). 406 | fn colocate_assets(config: &Config) -> Result<(), io::Error> { 407 | let mut output = Path::new(config.output_dir.as_ref()).join(config.site.assets.as_ref()); 408 | match fs::remove_dir_all(&output) { 409 | Ok(_) => Ok(()), 410 | Err(e) if e.kind() == ErrorKind::NotFound => Ok(()), 411 | Err(e) => Err(e), 412 | }?; 413 | let mut src = PathBuf::with_capacity(64); 414 | if !config.theme.is_empty() { 415 | src.push(config.theme_dir.as_ref()); 416 | src.push(config.theme.as_ref()); 417 | src.push(ASSET_SRC_DIR); 418 | copy_dir(&mut src, &mut output)?; 419 | src.clear(); 420 | } 421 | src.push(ASSET_SRC_DIR); 422 | copy_dir(&mut src, &mut output) 423 | } 424 | 425 | /// Load the templates from the directories specified by the config. 426 | fn load_templates(config: &Config) -> Result { 427 | fs::create_dir_all(TEMPLATE_DIR)?; 428 | let mut templates = Ramhorns::from_folder(TEMPLATE_DIR)?; 429 | if !config.theme.is_empty() { 430 | let mut theme_path = Path::new(config.theme_dir.as_ref()).join(config.theme.as_ref()); 431 | theme_path.push(TEMPLATE_DIR); 432 | if theme_path.exists() { 433 | templates.extend_from_folder(theme_path)?; 434 | } 435 | } 436 | Ok(templates) 437 | } 438 | 439 | /// Delete all the pages that were present in the previous render, but not the current one. 440 | /// Then, write all the paths that were rendered to the file `filelist` 441 | fn cleanup(mut rendered: Vec, filelist: &str) -> Result<(), io::Error> { 442 | let mut set = BTreeSet::new(); 443 | for path in rendered.drain(..) { 444 | if let Some(p) = set.replace(path) { 445 | println!("Warning: more paths render to {}", p.to_string_lossy()); 446 | } 447 | } 448 | 449 | if let Ok(f) = File::open(filelist) { 450 | BufReader::new(f).lines().try_for_each(|filename| { 451 | let filename = filename?; 452 | if !set.contains(Path::new(&filename)) { 453 | // Every directory has its index rendered 454 | if let Some(dir) = filename.strip_suffix("index.html") { 455 | if dir.ends_with(path::is_separator) { 456 | return match fs::remove_dir_all(dir) { 457 | Ok(_) => Ok(()), 458 | Err(e) if e.kind() == ErrorKind::NotFound => Ok(()), 459 | Err(e) => Err(e), 460 | }; 461 | } 462 | } 463 | match fs::remove_file(&filename) { 464 | Ok(_) => Ok(()), 465 | Err(e) if e.kind() == ErrorKind::NotFound => Ok(()), 466 | Err(e) => Err(e), 467 | } 468 | } else { 469 | Ok(()) 470 | } 471 | })?; 472 | }; 473 | 474 | let f = File::create(filelist)?; 475 | let mut f = BufWriter::new(f); 476 | for path in rendered.drain(..) { 477 | // It was already checked that the paths contain valid UTF-8 478 | let path = path.into_os_string().into_string().unwrap(); 479 | writeln!(&mut f, "{}", path)?; 480 | } 481 | 482 | Ok(()) 483 | } 484 | 485 | /// A helper trait to print the name of the file that was not found. 486 | trait PrintIfNotFound { 487 | /// Print the name of the file that was not found. 488 | fn print_if_not_found(self, name: &str) -> Self; 489 | } 490 | 491 | impl PrintIfNotFound for io::Result { 492 | /// Print the name of the file that was not found. 493 | fn print_if_not_found(self, name: &str) -> Self { 494 | if let Err(ref e) = self { 495 | if e.kind() == ErrorKind::NotFound { 496 | eprintln!("Error: {} not found", name) 497 | } 498 | } 499 | self 500 | } 501 | } 502 | 503 | /// The actual logic of task parallelisation. 504 | fn build(config: &Config) -> Result<(), Error> { 505 | const MIN_PER_THREAD: usize = 5; 506 | 507 | let sources: Sources = Sources::load(config.content_dir.as_ref())?; 508 | let num_pages = sources.sources().len(); 509 | let num_threads = thread::available_parallelism() 510 | .map(|n| n.get()) 511 | .unwrap_or(1); 512 | let num_threads = cmp::max(num_threads - 1, num_pages / MIN_PER_THREAD); 513 | let per_thread = (num_pages / num_threads) + 1; 514 | 515 | let (templates, pages) = thread::scope(|s| { 516 | let mut threads = Vec::with_capacity(num_threads); 517 | for chunk in sources.sources().chunks(per_thread) { 518 | threads.push(s.spawn(|| { 519 | chunk 520 | .iter() 521 | .map(|src| Page::new(src, &sources)) 522 | .collect::, _>>() 523 | })); 524 | } 525 | let templates = load_templates(config)?; 526 | let mut pages = Vec::with_capacity(num_pages); 527 | for thread in threads.drain(..) { 528 | pages.append(&mut thread.join().unwind()?); 529 | } 530 | Ok::<_, Error>((templates, pages)) 531 | })?; 532 | 533 | // Input plugins 534 | // Store input pages separately, so that we can borrow from the data 535 | let inputs = config 536 | .plugins 537 | .input 538 | .iter() 539 | .map(|cmd| { 540 | cmd.make_command() 541 | .output() 542 | .print_if_not_found(&cmd.path)? 543 | .output_result(&cmd.path) 544 | }) 545 | .collect::, _>>()?; 546 | let input_pages = inputs 547 | .iter() 548 | .map(|input| serde_json::from_slice(input)) 549 | .collect::>, _>>()?; 550 | let mut pages = pages; 551 | pages.extend(input_pages.into_iter().flat_map(|ip| ip.into_iter())); 552 | 553 | // Transform plugins 554 | let mut transformed: Option> = None; 555 | for cmd in config.plugins.transform.iter() { 556 | let mut child = cmd 557 | .make_command() 558 | .stdin(Stdio::piped()) 559 | .stdout(Stdio::piped()) 560 | .stderr(Stdio::piped()) 561 | .spawn() 562 | .print_if_not_found(&cmd.path)?; 563 | let mut stdin = child.stdin.take().expect("Failed to open child stdin"); 564 | if let Some(ref source) = transformed { 565 | stdin.write_all(source)?; 566 | } else { 567 | serde_json::to_writer(&stdin, &pages)?; 568 | } 569 | drop(stdin); 570 | let output = child.wait_with_output()?.output_result(&cmd.path)?; 571 | transformed = Some(output); 572 | } 573 | let mut pages = pages; 574 | if let Some(ref source) = transformed { 575 | pages = serde_json::from_slice(source)?; 576 | } 577 | 578 | // Content plugins 579 | if !config.plugins.content.is_empty() { 580 | pages.iter_mut().try_for_each(|page| { 581 | let mut output: Option = None; 582 | for &cmd in config.plugins.default.iter().chain(page.plugins.iter()) { 583 | let mut child = config.plugins.content[cmd] 584 | .make_command() 585 | .stdin(Stdio::piped()) 586 | .stdout(Stdio::piped()) 587 | .stderr(Stdio::piped()) 588 | .spawn() 589 | .print_if_not_found(&config.plugins.content[cmd].path)?; 590 | let mut stdin = child.stdin.take().expect("Failed to open child stdin"); 591 | if let Some(ref out) = output { 592 | stdin.write_all(out.as_ref())?; 593 | } else { 594 | stdin.write_all(page.content.as_ref().as_ref())?; 595 | } 596 | drop(stdin); 597 | let out = child.wait_with_output()?.output_result(cmd)?; 598 | output = Some(String::from_utf8(out).map_err(|e| Error::Utf8(cmd.into(), e))?); 599 | } 600 | if let Some(out) = output { 601 | page.content = out.into(); 602 | } 603 | Ok::<_, Error>(()) 604 | })?; 605 | } 606 | 607 | let pages = if !inputs.is_empty() || transformed.is_some() { 608 | pages.sort_unstable(); 609 | Pages::from_external(pages) 610 | } else { 611 | Pages::from_sources(pages) 612 | }; 613 | 614 | for page in pages.iter() { 615 | page.create_directory(config.output_dir.as_ref())?; 616 | } 617 | 618 | let taxonomies = Taxonomy::classify( 619 | &pages, 620 | config.taxonomies.iter(), 621 | &config.site.url, 622 | config.implicit_taxonomies, 623 | ); 624 | 625 | let output_dir = config.output_dir.as_ref().as_ref(); 626 | let context = Context(&pages, &config.site, &taxonomies, &templates, output_dir); 627 | let rendered = thread::scope(|s| { 628 | let mut threads = Vec::with_capacity(num_threads); 629 | for chunk in pages.chunks(per_thread) { 630 | threads.push(s.spawn(|| { 631 | let mut rendered = Vec::with_capacity(2 * per_thread); 632 | let mut buffer = Vec::with_capacity(BUFFER_SIZE); 633 | for page in chunk.iter() { 634 | page.render(context, &mut rendered, &mut buffer)?; 635 | } 636 | Ok::<_, Error>(rendered) 637 | })); 638 | } 639 | 640 | let tax_count = taxonomies.len() 641 | + taxonomies 642 | .iter() 643 | .map(|(_, t)| t.keys().len()) 644 | .sum::(); 645 | let mut rendered = Vec::with_capacity(tax_count + 2 * pages.len()); 646 | let mut buffer = Vec::with_capacity(BUFFER_SIZE); 647 | for (_, taxonomy) in taxonomies.iter() { 648 | taxonomy.render(context, &mut rendered, &mut buffer)?; 649 | for (n, l) in taxonomy.keys().iter() { 650 | taxonomy.render_key(n, l, context, &mut rendered, &mut buffer)?; 651 | } 652 | } 653 | render_meta(&pages, &config.site, &taxonomies, output_dir, &mut buffer)?; 654 | 655 | for thread in threads.drain(..) { 656 | let mut other = thread.join().unwind()?; 657 | rendered.append(&mut other); 658 | } 659 | Ok::<_, Error>(rendered) 660 | })?; 661 | 662 | cleanup(rendered, FILELIST)?; 663 | 664 | // Output plugins 665 | if !config.plugins.output.is_empty() { 666 | let pagedata = serde_json::to_string(&pages)?; 667 | for cmd in config.plugins.output.iter() { 668 | let mut child = cmd 669 | .make_command() 670 | .stdin(Stdio::piped()) 671 | .stderr(Stdio::piped()) 672 | .spawn() 673 | .print_if_not_found(&cmd.path)?; 674 | let mut stdin = child.stdin.take().expect("Failed to open child stdin"); 675 | stdin.write_all(pagedata.as_ref())?; 676 | drop(stdin); 677 | child 678 | .wait_with_output()? 679 | .output_result(&cmd.path) 680 | .map(drop)?; 681 | } 682 | } 683 | Ok(()) 684 | } 685 | 686 | fn get_command() -> Cmd { 687 | let mut args = env::args().skip(1); 688 | let command = match args.next().as_deref() { 689 | Some("init") => Cmd::Init, 690 | Some("new") => Cmd::New, 691 | Some("build") => Cmd::Build, 692 | Some("colocate") => Cmd::Colocate, 693 | Some("all") => Cmd::All, 694 | Some("lazy") | None => Cmd::Lazy, 695 | Some("help") => Cmd::Help, 696 | Some("version") => Cmd::Version, 697 | _ => Cmd::Invalid, 698 | }; 699 | if args.next().is_some() { 700 | Cmd::Invalid 701 | } else { 702 | command 703 | } 704 | } 705 | 706 | fn main() { 707 | let cmd = get_command(); 708 | let config_name: Cow = env::var(VAR_CONFIG) 709 | .map(Into::into) 710 | .unwrap_or_else(|_| CONFIG_FILE.into()); 711 | 712 | let start = Instant::now(); 713 | 714 | match cmd { 715 | Cmd::Help => { 716 | print!("{}", HELP); 717 | return; 718 | } 719 | Cmd::Version => { 720 | println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); 721 | return; 722 | } 723 | Cmd::Invalid => { 724 | eprintln!("Error: invalid arguments"); 725 | print!("{}", HELP); 726 | return; 727 | } 728 | _ => {} 729 | } 730 | 731 | let config_file = match std::fs::read_to_string(config_name.as_ref()) { 732 | Ok(cf) => cf, 733 | // Don't need a config file for initialisation. 734 | Err(_) if cmd == Cmd::Init => "".to_string(), 735 | Err(e) => { 736 | eprintln!("Can't read {}: {}", config_name, e); 737 | return; 738 | } 739 | }; 740 | let config: Config = match toml::from_str(&config_file) { 741 | Ok(cfg) => cfg, 742 | Err(e) => { 743 | eprintln!("Error parsing config file {}: {}", config_name, e); 744 | return; 745 | } 746 | }; 747 | 748 | if let Err(e) = match cmd { 749 | Cmd::Init => { 750 | if config_file.is_empty() { 751 | init() 752 | } else { 753 | println!("Config file {} already present; exiting", &config_name); 754 | Ok(()) 755 | } 756 | } 757 | Cmd::New => new_page(&config), 758 | Cmd::Build => build(&config), 759 | Cmd::Colocate => colocate_assets(&config).map_err(Into::into), 760 | Cmd::All => build(&config).and_then(|_| colocate_assets(&config).map_err(Into::into)), 761 | Cmd::Lazy => build(&config).and_then(|_| { 762 | if fs::read_to_string(OLD_THEME) 763 | .map(|old| old != config.theme) 764 | .unwrap_or(true) 765 | { 766 | colocate_assets(&config)?; 767 | fs::write(OLD_THEME, config.theme.as_ref()).map_err(Into::into) 768 | } else { 769 | Ok(()) 770 | } 771 | }), 772 | _ => { 773 | unreachable!() 774 | } 775 | } { 776 | eprintln!("{}", e); 777 | return; 778 | } 779 | 780 | println!("Done in {}ms.", start.elapsed().as_micros() as f64 / 1000.0) 781 | } 782 | -------------------------------------------------------------------------------- /src/page.rs: -------------------------------------------------------------------------------- 1 | // Blades Copyright (C) 2021 Maroš Grego 2 | // 3 | // This file is part of Blades. This program comes with ABSOLUTELY NO WARRANTY; 4 | // This is free software, and you are welcome to redistribute it under the 5 | // conditions of the GNU General Public License version 3.0. 6 | // 7 | // You should have received a copy of the GNU General Public License 8 | // along with Blades. If not, see 9 | use crate::render::render; 10 | use crate::site::{default_true, Site}; 11 | use crate::sources::{Parser, Source, Sources}; 12 | use crate::taxonomies::{Classification, Taxonomies}; 13 | use crate::types::{Ancestors, Any, DateTime, HashMap}; 14 | 15 | use beef::lean::Cow; 16 | use chrono::NaiveDate; 17 | use ramhorns::{ 18 | encoding::Encoder, traits::ContentSequence, Content, Error, Ramhorns, Section, Template, 19 | }; 20 | use serde::{Deserialize, Serialize}; 21 | 22 | use std::cmp::{min, Ordering, Reverse}; 23 | use std::fs::create_dir_all; 24 | use std::io; 25 | use std::num::NonZeroUsize; 26 | use std::ops::Range; 27 | use std::ops::{Deref, DerefMut}; 28 | use std::path::{is_separator, Path, PathBuf}; 29 | 30 | /// All the information regarding one page 31 | #[derive(Content, Default, Deserialize, Serialize)] 32 | pub struct Page<'p> { 33 | /// Title of the page. 34 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 35 | pub title: Cow<'p, str>, 36 | /// The file name this page is rendered into, without the .html extension. 37 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 38 | pub slug: Cow<'p, str>, 39 | /// The path in the output directory this page is rendered into. 40 | #[serde(borrow, default, skip_serializing_if = "is_ancestors_empty")] 41 | pub path: Ancestors<'p>, 42 | /// A list of alternative paths to render this page in, relative to the output directory. 43 | #[serde(default, skip_serializing_if = "is_slice_empty")] 44 | pub alternative_paths: Box<[&'p str]>, 45 | /// A weight of the page, used if a collection this page is in is sorted by weight. 46 | #[serde(default, skip_serializing_if = "equal_zero")] 47 | #[ramhorns(skip)] 48 | pub weight: i64, 49 | /// A template to render this page with. 50 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 51 | #[ramhorns(skip)] 52 | pub template: Cow<'p, str>, 53 | /// A template to render every subpage with (unless it specifies another template). 54 | #[serde(borrow, default = "def_page", skip_serializing_if = "eq_def_page")] 55 | #[ramhorns(skip)] 56 | pub page_template: Cow<'p, str>, 57 | /// A template to render every subsection with (unless it specifies another template). 58 | #[serde(borrow, default = "def_section", skip_serializing_if = "eq_def_sect")] 59 | #[ramhorns(skip)] 60 | pub section_template: Cow<'p, str>, 61 | /// A template to render the gallery pictures with. 62 | #[serde(borrow, default = "def_gallery", skip_serializing_if = "eq_def_gall")] 63 | #[ramhorns(skip)] 64 | pub gallery_template: Cow<'p, str>, 65 | /// A number of pages to paginate by, if this number is exceeded. 66 | #[serde(skip_serializing_if = "Option::is_none")] 67 | #[ramhorns(skip)] 68 | pub paginate_by: Option, 69 | /// An image representing the page. 70 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 71 | pub image: Cow<'p, str>, 72 | /// A brief summary of the page content. 73 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 74 | pub summary: Cow<'p, str>, 75 | /// The main content of the page. 76 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 77 | #[ramhorns(callback = render_content)] 78 | pub content: Cow<'p, str>, 79 | 80 | /// Date when the page was created. 81 | #[serde(skip_serializing_if = "Option::is_none")] 82 | pub date: Option, 83 | 84 | /// Whether to sort subpages and subsetions by their provided weight. 85 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] 86 | #[ramhorns(skip)] 87 | pub sort_by_weight: bool, 88 | /// Is this page a section? 89 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] 90 | pub is_section: bool, 91 | /// Hide the page from the list of its parent's subpages or subsections. 92 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] 93 | pub hidden: bool, 94 | 95 | #[serde(skip, default = "default_range")] 96 | #[ramhorns(skip)] 97 | pages: Range, 98 | #[serde(skip, default = "default_range")] 99 | #[ramhorns(skip)] 100 | subsections: Range, 101 | #[serde(skip)] 102 | #[ramhorns(skip)] 103 | parent: usize, 104 | #[serde(skip)] 105 | #[ramhorns(skip)] 106 | previous: usize, 107 | #[serde(skip)] 108 | #[ramhorns(skip)] 109 | next: usize, 110 | #[serde(skip, default = "default_true")] 111 | #[ramhorns(skip)] 112 | nonstandard_path: bool, 113 | /// Priority of this page in the sitemap 114 | #[serde(skip, default = "default_priority")] 115 | pub priority: f32, 116 | 117 | /// A list of pictures associated with this page. 118 | #[serde(default, skip_serializing_if = "is_slice_empty")] 119 | #[ramhorns(skip)] 120 | pub pictures: Box<[Picture<'p>]>, 121 | 122 | /// A map of lists to classify this page with. 123 | #[serde(default, skip_serializing_if = "HashMap::is_empty")] 124 | pub taxonomies: Taxonomies<'p>, 125 | /// A list of plugins to use to transform the content of this page. 126 | #[serde(default, skip_serializing_if = "is_slice_empty")] 127 | #[ramhorns(skip)] 128 | pub plugins: Box<[&'p str]>, 129 | 130 | /// A unique number to determine whether this is the active page 131 | #[serde(skip)] 132 | #[ramhorns(skip)] 133 | id: usize, 134 | 135 | /// Any "key = value" of any type can be used here for templates. 136 | #[serde(flatten)] 137 | #[ramhorns(flatten)] 138 | pub extra: HashMap<&'p str, Any<'p>>, 139 | } 140 | 141 | /// A list of pages properly sorted and linked within. It dereferences to `[Page]`. 142 | #[derive(Serialize)] 143 | #[serde(transparent)] 144 | pub struct Pages<'p>(Box<[Page<'p>]>); 145 | 146 | /// A single picture on a page. 147 | #[derive(Clone, Content, Deserialize, Serialize)] 148 | pub struct Picture<'p> { 149 | /// An alternative text displayed when the image can't be loaded or for accessibility. 150 | #[serde(borrow, default)] 151 | pub alt: Cow<'p, str>, 152 | /// An associated caption of the picture. 153 | #[serde(borrow, default)] 154 | pub caption: Cow<'p, str>, 155 | /// File name of the image. 156 | #[serde(borrow)] 157 | pub file: Cow<'p, str>, 158 | /// Id string of the picture, used for the generated URL in the gallery page. 159 | #[serde(borrow)] 160 | pub pid: Cow<'p, str>, 161 | /// Date and time of when the image was taken. 162 | pub taken: Option, 163 | } 164 | 165 | /// Whole context for rendering the site 166 | #[derive(Clone, Copy)] 167 | pub struct Context<'p, 'r>( 168 | pub &'r Pages<'p>, 169 | pub &'r Site<'p>, 170 | pub &'r Classification<'p, 'r>, 171 | pub &'r Ramhorns, 172 | pub &'r Path, 173 | ); 174 | 175 | /// Page bundled with references to its subpages and subsections for rendering 176 | #[derive(Clone, Content)] 177 | pub(crate) struct PageRef<'p, 'r> { 178 | pages: PageList<'p, 'r>, 179 | subsections: PageList<'p, 'r>, 180 | pictures: Pictures<'p, 'r>, 181 | permalink: Permalink<'p, 'r>, 182 | active: bool, 183 | #[ramhorns(flatten)] 184 | page: &'r Page<'p>, 185 | } 186 | 187 | /// Page bundled with the context of the whole site for rendering 188 | #[derive(Clone, Content)] 189 | struct PageContext<'p, 'r> { 190 | pages: PageList<'p, 'r>, 191 | subsections: PageList<'p, 'r>, 192 | previous: Option>, 193 | next: Option>, 194 | parent: PageRef<'p, 'r>, 195 | pictures: Pictures<'p, 'r>, 196 | index: PageRef<'p, 'r>, 197 | pagination: Option, 198 | permalink: Permalink<'p, 'r>, 199 | site: &'r Site<'p>, 200 | classification: &'r Classification<'p, 'r>, 201 | /// Always true, because this is the current page 202 | active: Active, 203 | #[ramhorns(flatten)] 204 | page: &'r Page<'p>, 205 | } 206 | 207 | /// (all pages, range we are interested in, id of the active page) 208 | /// Uses special Content implementation to render the given range of pages in context. 209 | #[derive(Clone)] 210 | pub(crate) struct PageList<'p, 'r> { 211 | all: &'r [Page<'p>], 212 | range: Range, 213 | active: usize, 214 | site_url: &'r str, 215 | } 216 | 217 | /// Information about the current position in pagination 218 | #[derive(Clone, Content, Copy)] 219 | pub(crate) struct Pagination { 220 | previous: Option, 221 | next: Option, 222 | current: usize, 223 | length: usize, 224 | } 225 | 226 | /// A view of one picture on some page 227 | #[derive(Content)] 228 | struct PictureRef<'p, 'r> { 229 | #[ramhorns(flatten)] 230 | picture: Picture<'r>, 231 | permalink: PicturePermalink<'p, 'r>, 232 | } 233 | 234 | /// One picture bundled with the context of the whole site for rendering 235 | #[derive(Content)] 236 | struct PictureView<'p, 'r> { 237 | current: PictureRef<'p, 'r>, 238 | previous: PictureRef<'p, 'r>, 239 | next: PictureRef<'p, 'r>, 240 | parent: PageRef<'p, 'r>, 241 | index: PageRef<'p, 'r>, 242 | site: &'r Site<'p>, 243 | classification: &'r Classification<'p, 'r>, 244 | } 245 | 246 | /// A list of pictures 247 | /// The last str is the site URL, kept for generating permalinks 248 | #[derive(Clone)] 249 | struct Pictures<'p, 'r>(&'r [Picture<'p>], &'r Page<'p>, &'r str); 250 | 251 | #[derive(Clone)] 252 | struct Active; 253 | impl Content for Active {} 254 | 255 | /// A struct to generate the full link for the given page 256 | // (page, site_url) 257 | #[derive(Clone)] 258 | pub struct Permalink<'p, 'r>(pub(crate) &'r Page<'p>, pub(crate) &'r str); 259 | 260 | /// A struct to generate the full link for the given page 261 | /// (page, site_url, pid) 262 | struct PicturePermalink<'p, 'r>(&'r Page<'p>, &'r str, &'r str); 263 | 264 | /// Trait representing types that can be rendered with some of their subpages separately 265 | pub(crate) trait Paginate: Content + Sized { 266 | /// Return `self`, but only with pages in the given range. 267 | fn paginate(&self, pages: Range, length: usize, current: usize) -> Self; 268 | 269 | /// Render `self` into separate pages where each can view just a subslice of `self`'s subpages. 270 | fn render_paginated( 271 | &self, 272 | range: Range, 273 | by: usize, 274 | path: &mut PathBuf, 275 | tpl: &Template, 276 | rendered: &mut Vec, 277 | buffer: &mut Vec, 278 | ) -> Result<(), io::Error> { 279 | let (mut first, last) = (range.start, range.end); 280 | let count = last - first; 281 | let by = min(by, count); 282 | let len = count / by + ((count % by != 0) as usize); 283 | render( 284 | tpl, 285 | &path, 286 | &self.paginate(first..(first + by), len, 1), 287 | rendered, 288 | buffer, 289 | )?; 290 | for i in 0..len { 291 | path.pop(); 292 | path.push((i + 1).to_string()); 293 | path.set_extension("html"); 294 | let end = min(first + by, last); 295 | render( 296 | tpl, 297 | &path, 298 | &self.paginate(first..end, len, i + 1), 299 | rendered, 300 | buffer, 301 | )?; 302 | first = end; 303 | } 304 | Ok(()) 305 | } 306 | } 307 | 308 | impl<'p> Page<'p> { 309 | /// Construct a new page from the source. 310 | #[inline] 311 | pub fn new( 312 | source: &'p Source

, 313 | data: &'p Sources

, 314 | ) -> Result)> { 315 | let path = std::str::from_utf8(&data.data[source.path.clone()]).unwrap(); 316 | let mut page = source 317 | .format 318 | .parse(&data.data[source.source.clone()]) 319 | .map_err(|e| (e, path.into()))?; 320 | 321 | let is_section = source.is_section; 322 | page.is_section = is_section; 323 | page.pages = source.pages.clone(); 324 | page.subsections = source.subsections.clone(); 325 | page.parent = source.parent; 326 | 327 | let slug = path.rsplit(is_separator).next().unwrap_or_default(); 328 | page.date = page 329 | .date 330 | .or_else(|| { 331 | slug.get(..10).and_then(|p| { 332 | p.parse::() 333 | .map(|d| DateTime(d.and_hms_opt(0, 0, 0).unwrap())) 334 | .ok() 335 | }) 336 | }) 337 | .or_else(|| source.date.map(|d| d.into())); 338 | 339 | if is_section || page.slug.is_empty() || page.slug.contains(is_separator) { 340 | let slug = path.rsplit(is_separator).next().unwrap_or_default(); 341 | page.slug = Cow::const_str(slug); 342 | } 343 | let page_path = page.path.as_ref(); 344 | if is_section || page_path.is_empty() || Path::new(page_path).is_absolute() { 345 | let path = &path[0..path.rfind(is_separator).unwrap_or_default()]; 346 | page.path = Cow::const_str(path).into(); 347 | page.nonstandard_path = false; 348 | } else if page_path == "." { 349 | page.path = Cow::const_str("").into(); 350 | } 351 | 352 | Ok(page) 353 | } 354 | 355 | /// Get a reference of the page, in context of its subpages and subsections. 356 | #[inline] 357 | pub(crate) fn by_ref<'r>(&'r self, all: &'r [Self], i: usize, url: &'r str) -> PageRef<'p, 'r> { 358 | PageRef { 359 | pages: PageList::new(all, self.pages.clone(), i, url), 360 | subsections: PageList::new(all, self.subsections.clone(), i, url), 361 | pictures: Pictures(&self.pictures, self, url), 362 | page: self, 363 | permalink: Permalink(self, url), 364 | active: self.id == i, 365 | } 366 | } 367 | 368 | /// Get a reference of the page bundled with the context of the whole site. 369 | #[inline] 370 | fn in_context<'r>( 371 | &'r self, 372 | all: &'r [Self], 373 | site: &'r Site<'p>, 374 | classification: &'r Classification<'p, 'r>, 375 | ) -> PageContext<'p, 'r> { 376 | PageContext { 377 | pages: PageList::new(all, self.pages.clone(), self.id, &site.url), 378 | subsections: PageList::new(all, self.subsections.clone(), self.id, &site.url), 379 | previous: Some(self.previous) 380 | .filter(|&i| i != 0) 381 | .map(|i| all[i].by_ref(all, self.id, &site.url)), 382 | next: Some(self.next) 383 | .filter(|&i| i != 0) 384 | .map(|i| all[i].by_ref(all, self.id, &site.url)), 385 | parent: all[self.parent].by_ref(all, self.id, &site.url), 386 | pictures: Pictures(&self.pictures, self, &site.url), 387 | permalink: Permalink(self, &site.url), 388 | index: all[0].by_ref(all, self.id, &site.url), 389 | pagination: None, 390 | classification, 391 | site, 392 | active: Active, 393 | page: self, 394 | } 395 | } 396 | 397 | /// If the page is section, create a directory where it will be rendered to. 398 | /// Also creates the directories specified in `alternative_paths`. 399 | pub fn create_directory>(&self, output_dir: P) -> Result<(), io::Error> { 400 | let output_dir = output_dir.as_ref(); 401 | 402 | for path in self.alternative_paths.iter() { 403 | let path = output_dir.join(path); 404 | create_dir_all(path)?; 405 | } 406 | 407 | if self.is_section || !self.pictures.is_empty() { 408 | let mut path = output_dir.join(self.path.as_ref()); 409 | path.push(self.slug.as_ref()); 410 | create_dir_all(path) 411 | } else if self.nonstandard_path { 412 | let path = output_dir.join(self.path.as_ref()); 413 | create_dir_all(path) 414 | } else { 415 | Ok(()) 416 | } 417 | } 418 | 419 | /// Render the page to the output directory specified by the config. 420 | /// `buffer` is used to store the result before writing it to the disk and expected to be empty. 421 | #[inline] 422 | pub fn render( 423 | &self, 424 | Context(all, site, classification, templates, output_dir): Context<'p, '_>, 425 | rendered: &mut Vec, 426 | buffer: &mut Vec, 427 | ) -> Result<(), Error> { 428 | let mut output = output_dir.join(self.path.as_ref()); 429 | output.push(self.slug.as_ref()); 430 | if self.is_section { 431 | output.push("index"); 432 | } 433 | output.set_extension("html"); 434 | 435 | let template = if self.template.is_empty() { 436 | if self.is_section { 437 | &all[self.parent].section_template 438 | } else { 439 | &all[self.parent].page_template 440 | } 441 | } else { 442 | &self.template 443 | }; 444 | let template = templates 445 | .get(template) 446 | .ok_or_else(|| Error::NotFound(template.as_ref().into()))?; 447 | 448 | let page = self.in_context(all, site, classification); 449 | let by = self.paginate_by.map(NonZeroUsize::get).unwrap_or(0); 450 | if by > 0 && self.pages.len() > by { 451 | let (start, end) = (self.pages.start, self.pages.end); 452 | page.render_paginated(start..end, by, &mut output, template, rendered, buffer)? 453 | } else if !self.pictures.is_empty() { 454 | render(template, &output, &page, rendered, buffer)?; 455 | 456 | if self.is_section { 457 | output.pop(); 458 | } else { 459 | output.set_extension(""); 460 | }; 461 | 462 | let template = templates 463 | .get(&self.gallery_template) 464 | .ok_or_else(|| Error::NotFound(self.gallery_template.as_ref().into()))?; 465 | 466 | // Make gallery circular, with the last photo referencing the first and vice-versa 467 | let pictures = &self.pictures; 468 | let last = pictures.len() - 1; 469 | for i in 0..=last { 470 | let page = PictureView { 471 | current: pictures[i].by_ref(self, &site.url), 472 | previous: pictures[if i == 0 { last } else { i - 1 }].by_ref(self, &site.url), 473 | next: pictures[if i == last { 0 } else { i + 1 }].by_ref(self, &site.url), 474 | parent: self.by_ref(all, self.id, &site.url), 475 | index: all[0].by_ref(all, self.id, &site.url), 476 | site, 477 | classification, 478 | }; 479 | output.push(pictures[i].pid.as_ref()); 480 | output.set_extension("html"); 481 | render(template, &output, &page, rendered, buffer)?; 482 | output.pop(); 483 | } 484 | } else { 485 | render(template, output, &page, rendered, buffer)?; 486 | } 487 | 488 | for path in self.alternative_paths.iter() { 489 | let mut output = output_dir.join(path); 490 | output.push("index.html"); 491 | render(template, output, &page, rendered, buffer)?; 492 | } 493 | Ok(()) 494 | } 495 | } 496 | 497 | impl<'p> Pages<'p> { 498 | /// Appropriately sort the given vector of pages and create all the directories where 499 | /// they will be rendered to. 500 | /// When applied to pages from external sources, the pages will not have any content 501 | /// hierarchy (subpages, subsections). 502 | #[inline] 503 | pub fn from_sources(mut pages: Vec>) -> Self { 504 | for i in 0..pages.len() { 505 | let page = &pages[i]; 506 | 507 | let subpages = page.pages.clone(); 508 | let subsects = page.subsections.clone(); 509 | if page.sort_by_weight { 510 | pages[subpages.clone()].sort_unstable_by_key(|p| p.weight); 511 | pages[subsects.clone()].sort_unstable_by_key(|p| p.weight); 512 | } else { 513 | pages[subpages.clone()].sort_unstable_by_key(|p| Reverse(p.date)); 514 | pages[subsects.clone()].sort_unstable_by_key(|p| Reverse(p.date)); 515 | } 516 | 517 | for i in subpages.clone().skip(1) { 518 | pages[i].previous = i - 1; 519 | } 520 | for i in subpages.clone().take_while(|i| *i != subpages.end - 1) { 521 | pages[i].next = i + 1; 522 | } 523 | for i in subsects.clone().skip(1) { 524 | pages[i].previous = i - 1; 525 | } 526 | for i in subsects.clone().take_while(|i| *i != subsects.end - 1) { 527 | pages[i].next = i + 1; 528 | } 529 | 530 | // Assign a unique identifier 531 | pages[i].id = i; 532 | } 533 | Pages(pages.into()) 534 | } 535 | 536 | /// Build up the internal hierarchical structure of pages loaded from the external source. 537 | /// The vector of pages MUST be sorted before (using the `Ord` implementation of `Page`), 538 | /// otherwise the hierarchy will be incomplete. 539 | #[inline] 540 | #[allow(clippy::needless_range_loop)] 541 | pub fn from_external(mut pages: Vec>) -> Self { 542 | #[inline] 543 | fn is_subpage(path: &str, section_path: &str, section_slug: &str) -> bool { 544 | path.strip_suffix(is_separator) 545 | .unwrap_or(path) 546 | .strip_suffix(section_slug) 547 | .and_then(|p| p.strip_prefix(section_path)) 548 | .filter(|s| s.chars().all(is_separator)) 549 | .is_some() 550 | } 551 | 552 | // Pages are sorted in a way that makes subpages and subsections adjacent 553 | for i in 0..pages.len() { 554 | if !pages[i].is_section { 555 | continue; 556 | } 557 | 558 | let (mut found, mut subpage_found) = (false, false); 559 | // subsections 560 | let (mut start, mut end) = (0, 0); 561 | // subpages 562 | let (mut pstart, mut pend) = (0, 0); 563 | for j in i + 1..pages.len() { 564 | if !is_subpage(&pages[j].path.0, &pages[i].path.0, &pages[i].slug) { 565 | if !found { 566 | continue; 567 | } else { 568 | if subpage_found { 569 | pend = j; 570 | } else { 571 | end = j; 572 | } 573 | break; 574 | } 575 | } 576 | if !found { 577 | found = true; 578 | if !pages[j].is_section { 579 | subpage_found = true; 580 | pstart = j; 581 | } else { 582 | start = j; 583 | } 584 | } else if !subpage_found && !pages[j].is_section { 585 | subpage_found = true; 586 | pstart = j; 587 | end = j; 588 | } 589 | pages[j].parent = i; 590 | } 591 | 592 | if end == 0 && start != 0 { 593 | end = pages.len() 594 | } else if pend == 0 && pstart != 0 { 595 | pend = pages.len() 596 | } 597 | 598 | pages[i].subsections = start..end; 599 | pages[i].pages = pstart..pend; 600 | if pages[i].sort_by_weight { 601 | pages[start..end].sort_unstable_by_key(|p| p.weight); 602 | pages[pstart..pend].sort_unstable_by_key(|p| p.weight); 603 | } 604 | if end != 0 { 605 | for j in start + 1..end { 606 | pages[j].previous = j - 1; 607 | } 608 | for j in start..end - 1 { 609 | pages[j].next = j + 1; 610 | } 611 | } 612 | if pend != 0 { 613 | for j in pstart + 1..pend { 614 | pages[j].previous = j - 1; 615 | } 616 | for j in pstart..pend - 1 { 617 | pages[j].next = j + 1; 618 | } 619 | } 620 | 621 | // Assign a unique identifier 622 | pages[i].id = i; 623 | } 624 | Pages(pages.into()) 625 | } 626 | } 627 | 628 | impl Ord for Page<'_> { 629 | fn cmp(&self, other: &Self) -> Ordering { 630 | let mut self_paths = self.path.0.split(is_separator); 631 | let mut other_paths = other.path.0.split(is_separator); 632 | loop { 633 | match (self_paths.next(), other_paths.next()) { 634 | (Some(s1), Some(s2)) => match s1.cmp(s2) { 635 | Ordering::Less => return Ordering::Less, 636 | Ordering::Greater => return Ordering::Greater, 637 | _ => continue, 638 | }, 639 | (None, Some(_)) => return Ordering::Less, 640 | (Some(_), None) => return Ordering::Greater, 641 | (None, None) => break, 642 | } 643 | } 644 | match (self.is_section, other.is_section) { 645 | (true, true) => self.slug.cmp(&other.slug), 646 | (true, false) => Ordering::Less, 647 | (false, true) => Ordering::Greater, 648 | (false, false) => Reverse(self.date).cmp(&Reverse(other.date)), 649 | } 650 | } 651 | } 652 | 653 | impl PartialOrd for Page<'_> { 654 | fn partial_cmp(&self, other: &Self) -> Option { 655 | Some(self.cmp(other)) 656 | } 657 | } 658 | 659 | impl PartialEq for Page<'_> { 660 | fn eq(&self, other: &Self) -> bool { 661 | self.path.0 == other.path.0 && self.slug == other.slug && self.id == other.id 662 | } 663 | } 664 | 665 | impl Eq for Page<'_> {} 666 | 667 | impl Paginate for PageContext<'_, '_> { 668 | #[inline] 669 | fn paginate(&self, pages: Range, length: usize, current: usize) -> Self { 670 | let old = &self.pages; 671 | Self { 672 | pages: PageList::new(old.all, pages, old.active, old.site_url), 673 | pagination: Some(Pagination::new(length, current)), 674 | ..self.clone() 675 | } 676 | } 677 | } 678 | 679 | impl Pagination { 680 | #[inline] 681 | pub(crate) fn new(length: usize, current: usize) -> Self { 682 | Self { 683 | length, 684 | current, 685 | previous: Some(current - 1).filter(|&i| i > 0), 686 | next: Some(current + 1).filter(|&i| i <= length), 687 | } 688 | } 689 | } 690 | 691 | impl<'p> Picture<'p> { 692 | fn by_ref<'r>(&'r self, page: &'r Page<'p>, site_url: &'r str) -> PictureRef<'p, 'r> { 693 | PictureRef { 694 | picture: Picture { 695 | alt: self.alt.as_ref().into(), 696 | caption: self.caption.as_ref().into(), 697 | pid: self.pid.as_ref().into(), 698 | file: self.file.as_ref().into(), 699 | taken: self.taken, 700 | }, 701 | permalink: PicturePermalink(page, site_url, &self.pid), 702 | } 703 | } 704 | } 705 | 706 | impl<'p, 'r> PageList<'p, 'r> { 707 | pub(crate) fn new(all: &'r [Page<'p>], range: Range, id: usize, url: &'r str) -> Self { 708 | Self { 709 | all, 710 | range, 711 | active: id, 712 | site_url: url, 713 | } 714 | } 715 | } 716 | 717 | #[inline] 718 | fn render_content(source: &str, encoder: &mut E) -> Result<(), E::Error> { 719 | use pulldown_cmark::Options; 720 | 721 | let options = Options::ENABLE_TABLES 722 | | Options::ENABLE_FOOTNOTES 723 | | Options::ENABLE_STRIKETHROUGH 724 | | Options::ENABLE_TASKLISTS 725 | | Options::ENABLE_SMART_PUNCTUATION 726 | | Options::ENABLE_HEADING_ATTRIBUTES 727 | | Options::ENABLE_MATH 728 | | Options::ENABLE_GFM; 729 | let parser = pulldown_cmark::Parser::new_ext(source, options); 730 | let processed = cmark_syntax::SyntaxPreprocessor::new(parser); 731 | encoder.write_html(processed) 732 | } 733 | 734 | impl Content for PageList<'_, '_> { 735 | #[inline] 736 | fn is_truthy(&self) -> bool { 737 | !self.range.is_empty() 738 | } 739 | 740 | #[inline] 741 | fn render_section(&self, section: Section, encoder: &mut E) -> Result<(), E::Error> 742 | where 743 | C: ContentSequence, 744 | E: Encoder, 745 | { 746 | let range = self.range.clone(); 747 | for page in self.all[range].iter().filter(|p| !p.hidden) { 748 | page.by_ref(self.all, self.active, self.site_url) 749 | .render_section(section, encoder)?; 750 | } 751 | 752 | Ok(()) 753 | } 754 | } 755 | 756 | impl Content for Permalink<'_, '_> { 757 | #[inline] 758 | fn is_truthy(&self) -> bool { 759 | true 760 | } 761 | 762 | #[inline] 763 | fn render_escaped(&self, encoder: &mut E) -> Result<(), E::Error> { 764 | encoder.write_escaped(self.1)?; 765 | self.0.path.render_escaped(encoder)?; 766 | if !self.0.slug.is_empty() { 767 | encoder.write_unescaped("/")?; 768 | self.0.slug.render_escaped(encoder)?; 769 | } 770 | if self.0.is_section { 771 | encoder.write_unescaped("/") 772 | } else { 773 | encoder.write_unescaped(".html") 774 | } 775 | } 776 | 777 | #[inline] 778 | fn render_unescaped(&self, encoder: &mut E) -> Result<(), E::Error> { 779 | encoder.write_unescaped(self.1)?; 780 | self.0.path.render_unescaped(encoder)?; 781 | if !self.0.slug.is_empty() { 782 | encoder.write_unescaped("/")?; 783 | self.0.slug.render_unescaped(encoder)?; 784 | } 785 | if self.0.is_section { 786 | encoder.write_unescaped("/") 787 | } else { 788 | encoder.write_unescaped(".html") 789 | } 790 | } 791 | } 792 | 793 | impl Content for Pictures<'_, '_> { 794 | #[inline] 795 | fn is_truthy(&self) -> bool { 796 | !self.0.is_empty() 797 | } 798 | 799 | #[inline] 800 | fn render_section(&self, section: Section, encoder: &mut E) -> Result<(), E::Error> 801 | where 802 | C: ContentSequence, 803 | E: Encoder, 804 | { 805 | for picture in self.0 { 806 | picture 807 | .by_ref(self.1, self.2) 808 | .render_section(section, encoder)?; 809 | } 810 | 811 | Ok(()) 812 | } 813 | } 814 | 815 | impl Content for PicturePermalink<'_, '_> { 816 | #[inline] 817 | fn is_truthy(&self) -> bool { 818 | true 819 | } 820 | 821 | #[inline] 822 | fn render_escaped(&self, encoder: &mut E) -> Result<(), E::Error> { 823 | encoder.write_escaped(self.1)?; 824 | self.0.path.render_escaped(encoder)?; 825 | if !self.0.slug.is_empty() { 826 | encoder.write_unescaped("/")?; 827 | self.0.slug.render_escaped(encoder)?; 828 | } 829 | encoder.write_unescaped("/")?; 830 | encoder.write_escaped(self.2)?; 831 | encoder.write_unescaped(".html") 832 | } 833 | 834 | #[inline] 835 | fn render_unescaped(&self, encoder: &mut E) -> Result<(), E::Error> { 836 | encoder.write_unescaped(self.1)?; 837 | self.0.path.render_unescaped(encoder)?; 838 | if !self.0.slug.is_empty() { 839 | encoder.write_unescaped("/")?; 840 | self.0.slug.render_unescaped(encoder)?; 841 | } 842 | encoder.write_unescaped("/")?; 843 | encoder.write_unescaped(self.2)?; 844 | encoder.write_unescaped(".html") 845 | } 846 | } 847 | 848 | impl<'p> Deref for Pages<'p> { 849 | type Target = [Page<'p>]; 850 | 851 | fn deref(&self) -> &Self::Target { 852 | &self.0 853 | } 854 | } 855 | 856 | impl DerefMut for Pages<'_> { 857 | fn deref_mut(&mut self) -> &mut Self::Target { 858 | &mut self.0 859 | } 860 | } 861 | 862 | #[inline] 863 | const fn default_priority() -> f32 { 864 | 0.5 865 | } 866 | 867 | #[inline] 868 | const fn default_range() -> Range { 869 | 0..0 870 | } 871 | 872 | #[inline] 873 | const fn def_gallery() -> Cow<'static, str> { 874 | Cow::const_str("gallery.html") 875 | } 876 | 877 | #[inline] 878 | const fn def_page() -> Cow<'static, str> { 879 | Cow::const_str("page.html") 880 | } 881 | 882 | #[inline] 883 | const fn def_section() -> Cow<'static, str> { 884 | Cow::const_str("section.html") 885 | } 886 | 887 | #[inline] 888 | fn eq_def_gall(c: &str) -> bool { 889 | c == "gallery.html" 890 | } 891 | 892 | #[inline] 893 | fn eq_def_page(c: &str) -> bool { 894 | c == "page.html" 895 | } 896 | 897 | #[inline] 898 | fn eq_def_sect(c: &str) -> bool { 899 | c == "section.html" 900 | } 901 | 902 | #[inline] 903 | const fn equal_zero(i: &i64) -> bool { 904 | *i == 0 905 | } 906 | 907 | #[inline] 908 | fn is_slice_empty(s: &[T]) -> bool { 909 | s.is_empty() 910 | } 911 | 912 | #[inline] 913 | fn is_ancestors_empty(s: &Ancestors) -> bool { 914 | s.0.is_empty() 915 | } 916 | -------------------------------------------------------------------------------- /src/render.rs: -------------------------------------------------------------------------------- 1 | // Blades Copyright (C) 2021 Maroš Grego 2 | // 3 | // This file is part of Blades. This program comes with ABSOLUTELY NO WARRANTY; 4 | // This is free software, and you are welcome to redistribute it under the 5 | // conditions of the GNU General Public License version 3.0. 6 | // 7 | // You should have received a copy of the GNU General Public License 8 | // along with Blades. If not, see 9 | use crate::page::{Page, PageList}; 10 | use crate::site::Site; 11 | use crate::taxonomies::{Classification, TaxonList}; 12 | use crate::types::DateTime; 13 | 14 | use std::fs; 15 | use std::io; 16 | use std::path::{Path, PathBuf}; 17 | 18 | use ramhorns::{Content, Template}; 19 | 20 | #[inline] 21 | pub(crate) fn render( 22 | template: &Template, 23 | path: P, 24 | content: &C, 25 | rendered: &mut Vec, 26 | buffer: &mut Vec, 27 | ) -> Result<(), io::Error> 28 | where 29 | C: Content, 30 | P: Into, 31 | { 32 | let path = path.into(); 33 | // Can't fail 34 | let _ = template.render_to_writer(buffer, content); 35 | fs::write(&path, &buffer)?; 36 | buffer.clear(); 37 | rendered.push(path); 38 | Ok(()) 39 | } 40 | 41 | #[derive(Content)] 42 | struct Meta<'p, 'r>( 43 | #[ramhorns(rename = "date")] DateTime, 44 | #[ramhorns(rename = "pages")] PageList<'p, 'r>, 45 | #[ramhorns(rename = "taxons")] TaxonList<'p, 'r>, 46 | #[ramhorns(rename = "site")] &'r Site<'p>, 47 | ); 48 | 49 | impl Meta<'_, '_> { 50 | #[inline] 51 | fn render( 52 | &self, 53 | name: &str, 54 | template: &str, 55 | path: &Path, 56 | buffer: &mut Vec, 57 | ) -> Result<(), ramhorns::Error> { 58 | let _ = Template::new(template)?.render_to_writer(buffer, self); 59 | fs::write(path.join(name), &buffer)?; 60 | buffer.clear(); 61 | Ok(()) 62 | } 63 | } 64 | 65 | /// Render sitemap, Atom and RSS feeds if enabled in the config. 66 | pub fn render_meta<'p>( 67 | pages: &[Page<'p>], 68 | site: &Site<'p>, 69 | taxons: &Classification<'p, '_>, 70 | output_dir: &Path, 71 | buffer: &mut Vec, 72 | ) -> Result<(), ramhorns::Error> { 73 | let pages = PageList::new(pages, 0..pages.len(), 0, &site.url); 74 | let meta = Meta(DateTime::now(), pages, TaxonList(taxons), site); 75 | 76 | if site.sitemap { 77 | let sitemap = include_str!("templates/sitemap.xml"); 78 | meta.render("sitemap.xml", sitemap, output_dir, buffer)?; 79 | } 80 | if site.rss { 81 | let rss = include_str!("templates/rss.xml"); 82 | meta.render("rss.xml", rss, output_dir, buffer)?; 83 | } 84 | if site.atom { 85 | let atom = include_str!("templates/atom.xml"); 86 | meta.render("atom.xml", atom, output_dir, buffer)?; 87 | } 88 | Ok(()) 89 | } 90 | -------------------------------------------------------------------------------- /src/site.rs: -------------------------------------------------------------------------------- 1 | // Blades Copyright (C) 2021 Maroš Grego 2 | // 3 | // This file is part of Blades. This program comes with ABSOLUTELY NO WARRANTY; 4 | // This is free software, and you are welcome to redistribute it under the 5 | // conditions of the GNU General Public License version 3.0. 6 | // 7 | // You should have received a copy of the GNU General Public License 8 | // along with Blades. If not, see 9 | use crate::types::{Any, HashMap}; 10 | 11 | use beef::lean::Cow; 12 | use ramhorns::Content; 13 | use serde::{Deserialize, Serialize}; 14 | 15 | /// Information about the site usable in templates 16 | #[derive(Content, Default, Deserialize, Serialize)] 17 | pub struct Site<'c> { 18 | /// Where the assets will be copied to, relative to the site directory. 19 | #[serde(borrow, default = "default_assets")] 20 | pub assets: Cow<'c, str>, 21 | /// Title of the site 22 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 23 | pub title: Cow<'c, str>, 24 | /// Description of the site 25 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 26 | pub description: Cow<'c, str>, 27 | /// Keywords of the site 28 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 29 | pub keywords: Cow<'c, str>, 30 | /// A representative image of the site 31 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 32 | pub image: Cow<'c, str>, 33 | /// Language of the site 34 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 35 | pub lang: Cow<'c, str>, 36 | /// Name of the author of the site 37 | #[serde(borrow, default)] 38 | pub author: Cow<'c, str>, 39 | /// Email of the webmaster 40 | #[serde(borrow, default)] 41 | pub email: Cow<'c, str>, 42 | /// URL of the site 43 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 44 | pub url: Cow<'c, str>, 45 | 46 | /// Generate a sitemap? 47 | #[serde(default = "default_true")] 48 | pub sitemap: bool, 49 | /// Generate RSS feed? 50 | #[serde(default = "default_true")] 51 | pub rss: bool, 52 | /// Generate Atom feed? 53 | #[serde(default = "default_true")] 54 | pub atom: bool, 55 | 56 | /// Extra values provided by the user 57 | #[serde(flatten)] 58 | #[ramhorns(flatten)] 59 | pub extra: HashMap<&'c str, Any<'c>>, 60 | } 61 | 62 | #[inline] 63 | const fn default_assets() -> Cow<'static, str> { 64 | Cow::const_str("assets") 65 | } 66 | 67 | #[inline] 68 | pub(crate) const fn default_true() -> bool { 69 | true 70 | } 71 | -------------------------------------------------------------------------------- /src/sources.rs: -------------------------------------------------------------------------------- 1 | // Blades Copyright (C) 2021 Maroš Grego 2 | // 3 | // This file is part of Blades. This program comes with ABSOLUTELY NO WARRANTY; 4 | // This is free software, and you are welcome to redistribute it under the 5 | // conditions of the GNU General Public License version 3.0. 6 | // 7 | // You should have received a copy of the GNU General Public License 8 | // along with Blades. If not, see 9 | use crate::page::Page; 10 | 11 | use std::ffi::OsStr; 12 | use std::fs::{read_dir, File}; 13 | use std::io::{self, Read}; 14 | use std::ops::Range; 15 | use std::path::{is_separator, PathBuf}; 16 | use std::time::SystemTime; 17 | 18 | /// A structure that can parse Page from binary data. 19 | /// Is typically a deserializer or an enum of deserializers. 20 | pub trait Parser: Default + Sized { 21 | /// The error that can happen during parsing. 22 | type Error: std::error::Error; 23 | 24 | /// The kind of parser that should be used, based on the file extension. 25 | fn from_extension(_extension: &OsStr) -> Option { 26 | Some(Self::default()) 27 | } 28 | 29 | /// Parse the binary data into a Page. 30 | fn parse<'a>(&self, data: &'a [u8]) -> Result, Self::Error>; 31 | } 32 | 33 | /// Data about where the source of a one particular file is located 34 | pub struct Source { 35 | /// Range in the slice of data 36 | pub(crate) source: Range, 37 | /// Range in the slice of data 38 | pub(crate) path: Range, 39 | /// Range in the slice of sources 40 | pub(crate) pages: Range, 41 | /// Range in the slice of sources 42 | pub(crate) subsections: Range, 43 | pub(crate) is_section: bool, 44 | pub(crate) parent: usize, 45 | pub(crate) date: Option, 46 | pub(crate) to_load: Option, 47 | pub(crate) format: P, 48 | } 49 | 50 | /// All of the site source files 51 | pub struct Sources { 52 | /// Binary data read of all the files 53 | pub(crate) data: Vec, 54 | /// Info about where the particular files are loaded 55 | sources: Vec>, 56 | } 57 | 58 | impl Source

{ 59 | #[inline] 60 | fn new( 61 | path: Range, 62 | src: Range, 63 | parent: usize, 64 | date: Option, 65 | format: P, 66 | ) -> Self { 67 | Self { 68 | source: src, 69 | path, 70 | pages: 0..0, 71 | subsections: 0..0, 72 | is_section: false, 73 | parent, 74 | date, 75 | to_load: None, 76 | format, 77 | } 78 | } 79 | 80 | /// Create a placeholder source, not referencing any data. 81 | #[inline] 82 | fn empty(section: PathBuf, parent: usize) -> Self { 83 | Self { 84 | source: 0..0, 85 | path: 0..0, 86 | pages: 0..0, 87 | subsections: 0..0, 88 | is_section: true, 89 | parent, 90 | date: None, 91 | to_load: Some(section), 92 | format: P::default(), 93 | } 94 | } 95 | } 96 | 97 | impl Sources

{ 98 | /// Add all the sources from the current directory to `self`. 99 | #[inline] 100 | fn step( 101 | &mut self, 102 | index: usize, 103 | path: PathBuf, 104 | dirs: &mut Vec, 105 | content_dir: &str, 106 | ) -> Result<(), io::Error> { 107 | let start = self.sources.len(); 108 | let mut index_file = None; 109 | for (path, date, format) in read_dir(&path)? 110 | .filter_map(Result::ok) 111 | .filter(|entry| { 112 | entry 113 | .file_type() 114 | .map(|ft| { 115 | if ft.is_dir() { 116 | dirs.push(entry.path()); 117 | false 118 | } else { 119 | ft.is_file() 120 | } 121 | }) 122 | .unwrap_or(false) 123 | }) 124 | .map(|entry| { 125 | let date = entry.metadata().and_then(|m| m.created()).ok(); 126 | (entry.path(), date) 127 | }) 128 | .filter_map(|(path, date)| { 129 | let ext = path.extension().unwrap_or_default(); 130 | let format = P::from_extension(ext)?; 131 | if path.file_stem()? == "index" { 132 | index_file = Some((path, date, format)); 133 | return None; 134 | }; 135 | Some((path, date, format)) 136 | }) 137 | { 138 | let start = self.data.len(); 139 | let read = File::open(&path)?.read_to_end(&mut self.data)?; 140 | let mid = start + read; 141 | let path = path.to_string_lossy(); 142 | let p = path.strip_prefix(content_dir).unwrap_or(&path); 143 | let p = p.strip_prefix(is_separator).unwrap_or(p); 144 | let ext_start = p.rfind('.').unwrap_or(p.len()); 145 | self.data.extend_from_slice(p[..ext_start].as_ref()); 146 | let end = self.data.len(); 147 | self.sources 148 | .push(Source::new(mid..end, start..mid, index, date, format)); 149 | } 150 | let end = self.sources.len(); 151 | 152 | for dir in dirs.drain(..) { 153 | self.sources.push(Source::empty(dir, index)); 154 | } 155 | let len = self.sources.len(); 156 | 157 | let source_start = self.data.len(); 158 | let read = if let Some((path, date, format)) = index_file { 159 | self.sources[index].date = date; 160 | self.sources[index].format = format; 161 | File::open(path)?.read_to_end(&mut self.data)? 162 | } else { 163 | 0 164 | }; 165 | let mid = source_start + read; 166 | 167 | let path = path.to_string_lossy(); 168 | let p = path.strip_prefix(content_dir).unwrap_or(&path); 169 | let p = p.strip_prefix(is_separator).unwrap_or(p); 170 | self.data.extend_from_slice(p.as_ref()); 171 | let source_end = self.data.len(); 172 | 173 | self.sources[index].path = mid..source_end; 174 | self.sources[index].source = source_start..mid; 175 | self.sources[index].pages = start..end; 176 | if len > end { 177 | self.sources[index].subsections = end..len; 178 | } 179 | 180 | Ok(()) 181 | } 182 | 183 | /// Load all the sources from the directory 184 | pub fn load(dir: &str) -> Result { 185 | let mut sources = Self { 186 | data: Vec::with_capacity(65536), 187 | sources: Vec::with_capacity(64), 188 | }; 189 | sources.sources.push(Source::empty(dir.into(), 0)); 190 | 191 | let mut dirs_buffer = Vec::new(); 192 | let mut i = 0; 193 | // Check all the sources whether they contain something more to load. 194 | while i < sources.sources.len() { 195 | if let Some(path) = sources.sources[i].to_load.take() { 196 | sources.step(i, path, &mut dirs_buffer, dir)?; 197 | } 198 | i += 1; 199 | } 200 | 201 | Ok(sources) 202 | } 203 | 204 | /// Get a reference of the inner list of sources. 205 | pub fn sources(&self) -> &[Source

] { 206 | &self.sources 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /src/taxonomies.rs: -------------------------------------------------------------------------------- 1 | // Blades Copyright (C) 2021 Maroš Grego 2 | // 3 | // This file is part of Blades. This program comes with ABSOLUTELY NO WARRANTY; 4 | // This is free software, and you are welcome to redistribute it under the 5 | // conditions of the GNU General Public License version 3.0. 6 | // 7 | // You should have received a copy of the GNU General Public License 8 | // along with Blades. If not, see 9 | use crate::page::{Context, Page, PageRef, Paginate, Pagination, Permalink}; 10 | use crate::render::render; 11 | use crate::site::Site; 12 | use crate::types::HashMap; 13 | 14 | use arrayvec::ArrayVec; 15 | use beef::lean::Cow; 16 | use hashbrown::hash_map::Entry; 17 | use ramhorns::{encoding::Encoder, traits::ContentSequence, Content, Error, Section}; 18 | use serde::{Deserialize, Serialize}; 19 | 20 | use std::cmp::Reverse; 21 | use std::collections::BTreeMap; 22 | use std::fs::create_dir_all; 23 | use std::num::NonZeroUsize; 24 | use std::ops::{Deref, Range}; 25 | use std::path::PathBuf; 26 | 27 | const DEFAULT_TEMPLATE: &str = "taxonomy.html"; 28 | const DEFAULT_KEY_TEMPLATE: &str = "taxonomy_key.html"; 29 | 30 | /// One class a page is a species of. 31 | #[derive(Clone, Content, Deserialize, Serialize)] 32 | #[serde(transparent)] 33 | pub struct Species<'s>( 34 | #[ramhorns(rename = "name")] 35 | #[serde(borrow)] 36 | Cow<'s, str>, 37 | ); 38 | 39 | /// All the classes in all taxonomies one page belongs to. 40 | pub type Taxonomies<'p> = HashMap<&'p str, ArrayVec, 6>>; 41 | 42 | /// Classification of all pages on the site. 43 | pub type Classification<'t, 'r> = HashMap<&'r str, Taxonomy<'t, 'r>>; 44 | 45 | /// Information abouth the given taxonomy. 46 | #[derive(Content, Clone, Default, Deserialize, Serialize)] 47 | pub struct TaxonMeta<'t> { 48 | /// Title of the taxonomy 49 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 50 | pub title: Cow<'t, str>, 51 | /// Description of the taxonomy 52 | #[serde(borrow, default, skip_serializing_if = "str::is_empty")] 53 | pub description: Cow<'t, str>, 54 | /// The template used to render the taxonomy 55 | #[serde(borrow, default = "default_template")] 56 | #[ramhorns(skip)] 57 | pub template: Cow<'t, str>, 58 | /// The template used to render one key in the taxonomy 59 | #[serde(borrow, default = "default_key_template")] 60 | #[ramhorns(skip)] 61 | pub key_template: Cow<'t, str>, 62 | /// Paginate the pages for keys with the provided number per each page 63 | #[ramhorns(skip)] 64 | pub paginate_by: Option, 65 | /// Sort the pages for keys by weight 66 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] 67 | #[ramhorns(skip)] 68 | pub sort_by_weight: bool, 69 | } 70 | 71 | /// One taxonomical category of the site (e.g. tags, categories). 72 | #[derive(Content)] 73 | pub struct Taxonomy<'t, 'r> { 74 | #[ramhorns(flatten)] 75 | taxonomy: TaxonMeta<'r>, 76 | slug: &'t str, 77 | keys: TaxDict<'t, 'r>, 78 | } 79 | 80 | /// All the pages in one taxonomical category, classified by the class name 81 | struct TaxDict<'t, 'r>(BTreeMap<&'r str, Vec>>); 82 | 83 | /// One taxonomical key, in the context of the whole site. 84 | #[derive(Content, Clone)] 85 | struct TaxKey<'t, 'r> { 86 | title: &'r str, 87 | taxonomy: &'r Taxonomy<'t, 'r>, 88 | pages: &'r [PageLinked<'t, 'r>], 89 | index: PageRef<'t, 'r>, 90 | site: &'r Site<'t>, 91 | classification: &'r Classification<'t, 'r>, 92 | pagination: Option, 93 | } 94 | 95 | /// One taxonomy in the context of the whole site. 96 | #[derive(Content)] 97 | struct TaxContext<'t, 'r> { 98 | #[ramhorns(flatten)] 99 | taxonomy: &'r Taxonomy<'t, 'r>, 100 | index: PageRef<'t, 'r>, 101 | site: &'r Site<'t>, 102 | classification: &'r Classification<'t, 'r>, 103 | } 104 | 105 | /// Classification of the whole site that's rendered as a list instead of a map (for sitemap) 106 | pub(crate) struct TaxonList<'t, 'r>(pub(crate) &'r Classification<'t, 'r>); 107 | 108 | /// Name of the taxonomical classes and its species 109 | #[derive(Content)] 110 | struct Coupled<'t, 'r>( 111 | #[ramhorns(rename = "key")] &'r str, 112 | #[ramhorns(rename = "pages")] &'r [PageLinked<'t, 'r>], 113 | ); 114 | 115 | /// Reference to a page, coupled with it's permalink 116 | #[derive(Content)] 117 | pub struct PageLinked<'t, 'r>( 118 | #[ramhorns(flatten)] &'r Page<'t>, 119 | #[ramhorns(rename = "permalink")] Permalink<'t, 'r>, 120 | ); 121 | 122 | impl<'t, 'r> Taxonomy<'t, 'r> { 123 | #[inline] 124 | fn empty(slug: &'t str) -> Self { 125 | Self { 126 | taxonomy: TaxonMeta { 127 | title: Cow::owned(title_case(slug)), 128 | description: Cow::const_str(""), 129 | template: Cow::const_str("taxonomy.html"), 130 | key_template: Cow::const_str("taxonomy_key.html"), 131 | paginate_by: None, 132 | sort_by_weight: false, 133 | }, 134 | slug, 135 | keys: TaxDict(Default::default()), 136 | } 137 | } 138 | 139 | #[inline] 140 | fn new(slug: &'t str, other: &'r TaxonMeta<'t>) -> Self { 141 | Self { 142 | taxonomy: TaxonMeta { 143 | title: Cow::const_str(&other.title), 144 | description: Cow::const_str(&other.description), 145 | template: Cow::const_str(&other.template), 146 | key_template: Cow::const_str(&other.key_template), 147 | paginate_by: other.paginate_by, 148 | sort_by_weight: other.sort_by_weight, 149 | }, 150 | slug, 151 | keys: TaxDict(Default::default()), 152 | } 153 | } 154 | 155 | #[inline] 156 | fn add(&mut self, species: &'r str, page: PageLinked<'t, 'r>) { 157 | self.keys.0.entry(species).or_default().push(page) 158 | } 159 | 160 | /// Classify the given pages into taxonomies specified by the config. 161 | #[inline] 162 | pub fn classify( 163 | pages: &'r [Page<'t>], 164 | taxonomies: I, 165 | url: &'r str, 166 | implicit: bool, 167 | ) -> Classification<'t, 'r> 168 | where 169 | I: Iterator)>, 170 | { 171 | let mut named: Classification = HashMap( 172 | taxonomies 173 | .into_iter() 174 | .map(|(&key, tax)| (key, Taxonomy::new(key, tax))) 175 | .collect(), 176 | ); 177 | 178 | for page in pages { 179 | for (class, family) in page.taxonomies.iter() { 180 | if let Some(taxon) = named.get_mut(class) { 181 | for species in family { 182 | taxon.add(species, PageLinked(page, Permalink(page, url))); 183 | } 184 | } else if implicit { 185 | let taxon = match named.entry(class) { 186 | Entry::Occupied(o) => o.into_mut(), 187 | Entry::Vacant(v) => { 188 | let taxonomy = Taxonomy::empty(class); 189 | v.insert(taxonomy) 190 | } 191 | }; 192 | for species in family { 193 | taxon.add(species, PageLinked(page, Permalink(page, url))); 194 | } 195 | } 196 | } 197 | } 198 | 199 | for taxon in named.values_mut() { 200 | if taxon.taxonomy.sort_by_weight { 201 | taxon 202 | .keys 203 | .0 204 | .iter_mut() 205 | .for_each(|(_, pages)| pages.sort_unstable_by_key(|page| page.0.weight)) 206 | } else { 207 | taxon 208 | .keys 209 | .0 210 | .iter_mut() 211 | .for_each(|(_, pages)| pages.sort_unstable_by_key(|page| Reverse(page.0.date))) 212 | } 213 | } 214 | named 215 | } 216 | 217 | /// Get a reference to the key map of the given taxonomy. 218 | #[inline] 219 | pub fn keys(&self) -> &BTreeMap<&'r str, Vec>> { 220 | &self.keys.0 221 | } 222 | 223 | /// Render this taxonomy into the output directory specified by the config. 224 | /// `buffer` is used to store the result before writing it to the disk and expected to be empty. 225 | #[inline] 226 | pub fn render( 227 | &self, 228 | Context(all, site, classification, templates, output_dir): Context<'t, '_>, 229 | rendered: &mut Vec, 230 | buffer: &mut Vec, 231 | ) -> Result<(), Error> { 232 | let mut path = output_dir.join(self.slug); 233 | create_dir_all(&path)?; 234 | path.push("index.html"); 235 | 236 | let contexted = TaxContext { 237 | taxonomy: self, 238 | site, 239 | index: all[0].by_ref(all, usize::MAX, &site.url), 240 | classification, 241 | }; 242 | let template = templates 243 | .get(&self.taxonomy.template) 244 | .ok_or_else(|| Error::NotFound(self.taxonomy.template.as_ref().into()))?; 245 | render(template, path, &contexted, rendered, buffer).map_err(Into::into) 246 | } 247 | 248 | /// Render one key of this taxonomy into the output directory specified by the config. 249 | /// `buffer` is used to store the result before writing it to the disk and expected to be empty. 250 | #[inline] 251 | pub fn render_key( 252 | &self, 253 | title: &str, 254 | pages: &[PageLinked<'t, '_>], 255 | Context(all, site, classification, templates, output_dir): Context<'t, '_>, 256 | rendered: &mut Vec, 257 | buffer: &mut Vec, 258 | ) -> Result<(), Error> { 259 | let mut output = output_dir.join(self.slug); 260 | output.push(title); 261 | create_dir_all(&output)?; 262 | output.push("index.html"); 263 | 264 | let contexted = TaxKey { 265 | title, 266 | taxonomy: self, 267 | pages, 268 | index: all[0].by_ref(all, usize::MAX, &site.url), 269 | site, 270 | classification, 271 | pagination: None, 272 | }; 273 | 274 | let by = self 275 | .taxonomy 276 | .paginate_by 277 | .map(NonZeroUsize::get) 278 | .unwrap_or(0); 279 | let template = templates 280 | .get(&self.taxonomy.key_template) 281 | .ok_or_else(|| Error::NotFound(self.taxonomy.key_template.as_ref().into()))?; 282 | if by > 0 && pages.len() > by { 283 | contexted.render_paginated(0..pages.len(), by, &mut output, template, rendered, buffer) 284 | } else { 285 | render(template, output, &contexted, rendered, buffer) 286 | } 287 | .map_err(Into::into) 288 | } 289 | } 290 | 291 | impl Paginate for TaxKey<'_, '_> { 292 | fn paginate(&self, range: Range, length: usize, current: usize) -> Self { 293 | Self { 294 | pages: &self.pages[range], 295 | pagination: Some(Pagination::new(length, current)), 296 | // range in PageRef doesn't implement Copy 297 | ..self.clone() 298 | } 299 | } 300 | } 301 | 302 | impl Content for TaxDict<'_, '_> { 303 | #[inline] 304 | fn is_truthy(&self) -> bool { 305 | !self.0.is_empty() 306 | } 307 | 308 | #[inline] 309 | fn render_section(&self, section: Section, encoder: &mut E) -> Result<(), E::Error> 310 | where 311 | C: ContentSequence, 312 | E: Encoder, 313 | { 314 | for (key, pages) in self.0.iter() { 315 | section.with(&Coupled(key, pages)).render(encoder)?; 316 | } 317 | Ok(()) 318 | } 319 | } 320 | 321 | impl Content for TaxonList<'_, '_> { 322 | #[inline] 323 | fn is_truthy(&self) -> bool { 324 | !self.0.is_empty() 325 | } 326 | 327 | #[inline] 328 | fn render_section(&self, section: Section, encoder: &mut E) -> Result<(), E::Error> 329 | where 330 | C: ContentSequence, 331 | E: Encoder, 332 | { 333 | for taxonomy in self.0.values() { 334 | section.with(taxonomy).render(encoder)?; 335 | } 336 | Ok(()) 337 | } 338 | } 339 | 340 | impl Deref for Species<'_> { 341 | type Target = str; 342 | fn deref(&self) -> &Self::Target { 343 | self.0.as_ref() 344 | } 345 | } 346 | 347 | #[inline] 348 | fn title_case(s: &str) -> String { 349 | let mut c = s.chars(); 350 | match c.next() { 351 | None => String::new(), 352 | Some(f) => f.to_uppercase().collect::() + c.as_str(), 353 | } 354 | } 355 | 356 | #[inline] 357 | const fn default_template() -> Cow<'static, str> { 358 | Cow::const_str(DEFAULT_TEMPLATE) 359 | } 360 | 361 | #[inline] 362 | const fn default_key_template() -> Cow<'static, str> { 363 | Cow::const_str(DEFAULT_KEY_TEMPLATE) 364 | } 365 | -------------------------------------------------------------------------------- /src/templates/Blades.toml: -------------------------------------------------------------------------------- 1 | title = "{{title}}" 2 | description = "" 3 | keywords = "" 4 | image = "" 5 | theme = "" 6 | author = "{{author}}" 7 | -------------------------------------------------------------------------------- /src/templates/atom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | {{#site}} 4 | {{title}} 5 | 6 | {{url}} 7 | {{#author}} 8 | {{author}} 9 | {{#email}}{{email}}{{/email}} 10 | {{/author}} 11 | {{description}} 12 | blades 13 | {{#date}}{{y}}-{{m}}-{{d}}T{{H}}:{{M}}:{{S}}Z{{/date}} 14 | {{/site}} 15 | {{#pages}} 16 | 17 | {{title}} 18 | 19 | {{#site}}{{url}}{{/site}}{{path}}{{#slug}}/{{slug}}{{/slug}} 20 |

{{summary}} 21 | {{content}} 22 | {{#date}}{{y}}-{{m}}-{{d}}T{{H}}:{{M}}:{{S}}Z{{/date}} 23 | 24 | {{#pictures}} 25 | 26 | {{caption}} 27 | 28 | {{#site}}{{url}}{{/site}}{{path}}{{#slug}}/{{slug}}{{/slug}}/{{pid}} 29 | {{alt}} 30 | {{summary}} 31 | {{#taken}}{{y}}-{{m}}-{{d}}T{{H}}:{{M}}:{{S}}Z{{/taken}} 32 | {{^taken}}{{#date}}{{y}}-{{m}}-{{d}}T{{H}}:{{M}}:{{S}}Z{{/date}}{{/taken}} 33 | 34 | {{/pictures}} 35 | {{/pages}} 36 | 37 | -------------------------------------------------------------------------------- /src/templates/page.toml: -------------------------------------------------------------------------------- 1 | title = "{{title}}" 2 | slug = "{{slug}}" 3 | date = {{date}} 4 | 5 | content = """ 6 | Put your *possibly markdowned* content here. 7 | """ 8 | -------------------------------------------------------------------------------- /src/templates/rss.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{#site}} 5 | {{title}} 6 | {{url}} 7 | {{description}} 8 | 1440 9 | blades 10 | {{#date}}{{a}}, {{d}} {{b}} {{y}} {{H}}:{{M}}:{{S}} GMT{{/date}} 11 | {{#email}}{{email}} 12 | {{email}}{{/email}} 13 | {{/site}} 14 | {{#pages}} 15 | 16 | {{title}} 17 | {{permalink}} 18 | {{summary}} 19 | {{#date}}{{a}}, {{d}} {{b}} {{y}} {{H}}:{{M}}:{{S}} GMT{{/date}} 20 | 21 | {{#pictures}} 22 | {{caption}} 23 | {{permalink}} 24 | {{alt}} 25 | {{#taken}}{{a}}, {{d}} {{b}} {{y}} {{H}}:{{M}}:{{S}} GMT{{/taken}} 26 | {{^taken}}{{#date}}{{a}}, {{d}} {{b}} {{y}} {{H}}:{{M}}:{{S}} GMT{{/date}}{{/taken}} 27 | {{/pictures}} 28 | {{/pages}} 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/templates/sitemap.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | {{#pages}} 4 | {{permalink}} 5 | {{priority}} 6 | {{/pages}} 7 | {{#taxons}} 8 | /{{slug}}/ 9 | 0.2 10 | 11 | {{#keys}} 12 | /{{slug}}/{{key}}/ 13 | 0.3 14 | {{/keys}}{{/taxons}} 15 | 16 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | // Blades Copyright (C) 2021 Maroš Grego 2 | // 3 | // This file is part of Blades. This program comes with ABSOLUTELY NO WARRANTY; 4 | // This is free software, and you are welcome to redistribute it under the 5 | // conditions of the GNU General Public License version 3.0. 6 | // 7 | // You should have received a copy of the GNU General Public License 8 | // along with Blades. If not, see 9 | use beef::lean::Cow; 10 | use chrono::{DateTime as CDateTime, Datelike, FixedOffset, NaiveDate, NaiveDateTime, Timelike}; 11 | use ramhorns::encoding::Encoder; 12 | use ramhorns::traits::ContentSequence; 13 | use ramhorns::{Content, Section}; 14 | use serde::de::{self, Deserialize, Deserializer, Visitor}; 15 | 16 | use std::borrow::Borrow; 17 | use std::fmt; 18 | use std::hash::Hash; 19 | use std::ops::{Deref, DerefMut}; 20 | use std::path::is_separator; 21 | use std::time::SystemTime; 22 | 23 | /// A hash map wrapper that can render fields directly by the hash. 24 | #[derive(Clone, serde::Deserialize, serde::Serialize)] 25 | #[serde(transparent)] 26 | pub struct HashMap(pub(crate) hashbrown::HashMap); 27 | 28 | /// A wrapper around the `chrono::NaiveDateTime`, used for rendering of dates. 29 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)] 30 | #[serde(transparent)] 31 | pub struct DateTime(pub NaiveDateTime); 32 | 33 | /// A wrapper around a `str` representing a path, `Content` implementation 34 | /// acts like an iterator over the path segmets. 35 | #[derive(serde::Deserialize, serde::Serialize)] 36 | #[serde(transparent)] 37 | pub struct Ancestors<'a>(#[serde(borrow)] pub Cow<'a, str>); 38 | 39 | /// One segment of a path. 40 | #[derive(Content)] 41 | struct Segment<'a>( 42 | /// This segment. 43 | #[ramhorns(rename = "name")] 44 | &'a str, 45 | /// Full path up to this segment. 46 | #[ramhorns(rename = "full")] 47 | &'a str, 48 | ); 49 | 50 | /// A sum of all the types that can be used in a TOML file. 51 | #[derive(Clone, serde::Deserialize, serde::Serialize)] 52 | #[serde(untagged)] 53 | pub enum Any<'a> { 54 | /// A string. 55 | String(#[serde(borrow)] Cow<'a, str>), 56 | /// A number. 57 | Number(f64), 58 | /// A boolean value. 59 | Bool(bool), 60 | /// Date and time data. 61 | DateTime(DateTime), 62 | /// A list. 63 | List(Vec>), 64 | /// A key-value map. 65 | Map(HashMap<&'a str, Any<'a>>), 66 | } 67 | 68 | impl Content for Ancestors<'_> { 69 | #[inline] 70 | fn is_truthy(&self) -> bool { 71 | !self.0.is_empty() 72 | } 73 | 74 | #[inline] 75 | fn render_escaped(&self, encoder: &mut E) -> Result<(), E::Error> { 76 | // The path was stripped of leading separators. 77 | if !self.0.is_empty() { 78 | encoder.write_unescaped("/")?; 79 | encoder.write_escaped(&self.0)?; 80 | } 81 | Ok(()) 82 | } 83 | 84 | #[inline] 85 | fn render_unescaped(&self, encoder: &mut E) -> Result<(), E::Error> { 86 | if !self.0.is_empty() { 87 | encoder.write_unescaped("/")?; 88 | encoder.write_unescaped(&self.0)?; 89 | } 90 | Ok(()) 91 | } 92 | 93 | #[inline] 94 | fn render_section(&self, section: Section, encoder: &mut E) -> Result<(), E::Error> 95 | where 96 | C: ContentSequence, 97 | E: Encoder, 98 | { 99 | let s = self.0.as_ref(); 100 | if s.is_empty() { 101 | return Ok(()); 102 | } 103 | 104 | let mut previous = 0; 105 | for (i, sep) in s.match_indices(is_separator) { 106 | section 107 | .with(&Segment(&s[previous..i], &s[0..i])) 108 | .render(encoder)?; 109 | previous = i + sep.len(); 110 | } 111 | if previous != 0 { 112 | section 113 | .with(&Segment(&s[previous..], s)) 114 | .render(encoder)?; 115 | } else { 116 | section.with(&Segment(s, s)).render(encoder)?; 117 | } 118 | Ok(()) 119 | } 120 | } 121 | 122 | impl AsRef for Ancestors<'_> { 123 | fn as_ref(&self) -> &str { 124 | self.0.as_ref() 125 | } 126 | } 127 | 128 | impl Default for Ancestors<'_> { 129 | #[inline] 130 | fn default() -> Self { 131 | Ancestors(Cow::const_str("")) 132 | } 133 | } 134 | 135 | impl<'a> From> for Ancestors<'a> { 136 | #[inline] 137 | fn from(s: Cow<'a, str>) -> Self { 138 | Ancestors(s) 139 | } 140 | } 141 | 142 | #[inline] 143 | fn content_without_paragraphs(source: &str, encoder: &mut E) -> Result<(), E::Error> { 144 | use pulldown_cmark::{Event, Tag, TagEnd}; 145 | let parser = 146 | pulldown_cmark::Parser::new_ext(source, pulldown_cmark::Options::all()).filter(|event| { 147 | !matches!( 148 | event, 149 | Event::Start(Tag::Paragraph) | Event::End(TagEnd::Paragraph), 150 | ) 151 | }); 152 | let processed = cmark_syntax::SyntaxPreprocessor::new(parser); 153 | encoder.write_html(processed) 154 | } 155 | 156 | impl Content for Any<'_> { 157 | #[inline] 158 | fn is_truthy(&self) -> bool { 159 | match self { 160 | Any::Bool(b) => *b, 161 | Any::List(vec) => !vec.is_empty(), 162 | Any::Map(map) => !map.is_empty(), 163 | Any::String(s) => !s.is_empty(), 164 | Any::Number(n) => n.abs() > f64::EPSILON, 165 | _ => true, 166 | } 167 | } 168 | 169 | #[inline] 170 | fn render_escaped(&self, encoder: &mut E) -> Result<(), E::Error> { 171 | match self { 172 | Any::Bool(b) => b.render_escaped(encoder), 173 | Any::String(ref s) => content_without_paragraphs(s, encoder), 174 | Any::Number(n) => n.render_escaped(encoder), 175 | Any::DateTime(dt) => dt.render_escaped(encoder), 176 | Any::List(vec) => vec.render_escaped(encoder), 177 | Any::Map(map) => map.render_escaped(encoder), 178 | } 179 | } 180 | 181 | #[inline] 182 | fn render_unescaped(&self, encoder: &mut E) -> Result<(), E::Error> { 183 | match self { 184 | Any::Bool(b) => b.render_unescaped(encoder), 185 | Any::String(s) => s.render_unescaped(encoder), 186 | Any::Number(n) => n.render_unescaped(encoder), 187 | Any::DateTime(dt) => dt.render_unescaped(encoder), 188 | Any::List(vec) => vec.render_unescaped(encoder), 189 | Any::Map(map) => map.render_unescaped(encoder), 190 | } 191 | } 192 | 193 | #[inline] 194 | fn render_section(&self, section: Section, encoder: &mut E) -> Result<(), E::Error> 195 | where 196 | C: ContentSequence, 197 | E: Encoder, 198 | { 199 | match self { 200 | Any::List(vec) => vec.render_section(section, encoder), 201 | Any::Map(map) => map.render_section(section, encoder), 202 | Any::DateTime(dt) => dt.render_section(section, encoder), 203 | _ => { 204 | if self.is_truthy() { 205 | section.render(encoder) 206 | } else { 207 | Ok(()) 208 | } 209 | } 210 | } 211 | } 212 | 213 | #[inline] 214 | fn render_field_escaped(&self, h: u64, name: &str, enc: &mut E) -> Result 215 | where 216 | E: Encoder, 217 | { 218 | match self { 219 | Any::Map(map) => map.render_field_escaped(h, name, enc), 220 | _ => Ok(false), 221 | } 222 | } 223 | 224 | #[inline] 225 | fn render_field_unescaped(&self, h: u64, name: &str, enc: &mut E) -> Result 226 | where 227 | E: Encoder, 228 | { 229 | match self { 230 | Any::Map(map) => map.render_field_unescaped(h, name, enc), 231 | _ => Ok(false), 232 | } 233 | } 234 | 235 | #[inline] 236 | fn render_field_section( 237 | &self, 238 | hash: u64, 239 | name: &str, 240 | section: Section, 241 | encoder: &mut E, 242 | ) -> Result 243 | where 244 | C: ContentSequence, 245 | E: Encoder, 246 | { 247 | match self { 248 | Any::Map(map) => map.render_field_section(hash, name, section, encoder), 249 | _ => Ok(false), 250 | } 251 | } 252 | 253 | #[inline] 254 | fn render_field_inverse( 255 | &self, 256 | hash: u64, 257 | name: &str, 258 | section: Section, 259 | encoder: &mut E, 260 | ) -> Result 261 | where 262 | C: ContentSequence, 263 | E: Encoder, 264 | { 265 | match self { 266 | Any::Map(map) => map.render_field_inverse(hash, name, section, encoder), 267 | _ => Ok(false), 268 | } 269 | } 270 | } 271 | 272 | impl DateTime { 273 | /// The date and time right now. 274 | pub fn now() -> Self { 275 | SystemTime::now().into() 276 | } 277 | } 278 | 279 | impl Content for DateTime { 280 | #[inline] 281 | fn render_section(&self, section: Section, encoder: &mut E) -> Result<(), E::Error> 282 | where 283 | C: ContentSequence, 284 | E: Encoder, 285 | { 286 | section.with(self).render(encoder) 287 | } 288 | 289 | #[inline] 290 | fn render_field_escaped(&self, _: u64, name: &str, enc: &mut E) -> Result 291 | where 292 | E: Encoder, 293 | { 294 | if name.len() != 1 { 295 | return Ok(false); 296 | } 297 | 298 | const WEEKDAYS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; 299 | const MONTHS: [&str; 12] = [ 300 | "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", 301 | ]; 302 | const NUMS: [&str; 60] = [ 303 | "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", 304 | "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", 305 | "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", 306 | "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", 307 | "56", "57", "58", "59", 308 | ]; 309 | 310 | match name.bytes().next().unwrap_or(0) { 311 | b'y' => self.0.year().render_unescaped(enc).map(|_| true), 312 | b'm' => enc 313 | .write_unescaped(NUMS[self.0.month() as usize]) 314 | .map(|_| true), 315 | b'd' => enc 316 | .write_unescaped(NUMS[self.0.day() as usize]) 317 | .map(|_| true), 318 | b'e' => self.0.day().render_unescaped(enc).map(|_| true), 319 | b'H' => enc 320 | .write_unescaped(NUMS[self.0.hour() as usize]) 321 | .map(|_| true), 322 | b'M' => enc 323 | .write_unescaped(NUMS[self.0.minute() as usize]) 324 | .map(|_| true), 325 | b'S' => enc 326 | .write_unescaped(NUMS[self.0.second() as usize]) 327 | .map(|_| true), 328 | b'a' => enc 329 | .write_unescaped(WEEKDAYS[self.0.weekday().num_days_from_sunday() as usize]) 330 | .map(|_| true), 331 | b'b' => enc 332 | .write_unescaped(MONTHS[self.0.month0() as usize]) 333 | .map(|_| true), 334 | _ => Ok(false), 335 | } 336 | } 337 | 338 | #[inline] 339 | fn render_field_unescaped(&self, h: u64, name: &str, enc: &mut E) -> Result 340 | where 341 | E: Encoder, 342 | { 343 | self.render_field_escaped(h, name, enc) 344 | } 345 | } 346 | 347 | // Toml crate currently doesn't supprot deserializing dates into types other than String, 348 | // so an ugly hack based on its `Deserializer` private fields needs to be used. 349 | const FIELD: &str = "$__toml_private_datetime"; 350 | 351 | impl<'de> Deserialize<'de> for DateTime { 352 | fn deserialize(deserializer: D) -> Result 353 | where 354 | D: Deserializer<'de>, 355 | { 356 | struct DateTimeKey; 357 | struct DateTimeVisitor; 358 | 359 | impl<'de> Deserialize<'de> for DateTimeKey { 360 | fn deserialize(deserializer: D) -> Result 361 | where 362 | D: de::Deserializer<'de>, 363 | { 364 | struct FieldVisitor; 365 | 366 | impl de::Visitor<'_> for FieldVisitor { 367 | type Value = (); 368 | 369 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 370 | formatter.write_str("a valid datetime field") 371 | } 372 | 373 | fn visit_str(self, s: &str) -> Result<(), E> 374 | where 375 | E: de::Error, 376 | { 377 | if s == FIELD { 378 | Ok(()) 379 | } else { 380 | Err(de::Error::custom("expected field with a custom name")) 381 | } 382 | } 383 | } 384 | 385 | deserializer.deserialize_identifier(FieldVisitor)?; 386 | Ok(DateTimeKey) 387 | } 388 | } 389 | 390 | impl<'de> Visitor<'de> for DateTimeVisitor { 391 | type Value = DateTime; 392 | 393 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 394 | formatter.write_str("a TOML datetime") 395 | } 396 | 397 | fn visit_map(self, mut visitor: V) -> Result 398 | where 399 | V: de::MapAccess<'de>, 400 | { 401 | let value = visitor.next_key::()?; 402 | if value.is_none() { 403 | return Err(de::Error::custom("datetime key not found")); 404 | } 405 | let v: &str = visitor.next_value()?; 406 | self.visit_str(v) 407 | } 408 | 409 | fn visit_str(self, v: &str) -> Result { 410 | v.parse::() 411 | .or_else(|_| { 412 | v.parse::() 413 | .map(|d| d.and_hms_opt(0, 0, 0).unwrap()) 414 | }) 415 | .or_else(|_| NaiveDateTime::parse_from_str(v, "%F %T%.f")) 416 | .or_else(|_| v.parse::>().map(|d| d.naive_utc())) 417 | .map(DateTime) 418 | .map_err(|_| { 419 | de::Error::custom(format!("unable to parse date and time from {}", v)) 420 | }) 421 | } 422 | } 423 | 424 | deserializer.deserialize_str(DateTimeVisitor) 425 | } 426 | } 427 | 428 | impl From for DateTime { 429 | fn from(st: SystemTime) -> Self { 430 | let time: chrono::DateTime = st.into(); 431 | DateTime(time.naive_utc()) 432 | } 433 | } 434 | 435 | impl + Hash + Eq, V: Content> Content for HashMap { 436 | #[inline] 437 | fn is_truthy(&self) -> bool { 438 | !self.is_empty() 439 | } 440 | 441 | /// Render a section with self. 442 | #[inline] 443 | fn render_section(&self, section: Section, encoder: &mut E) -> Result<(), E::Error> 444 | where 445 | C: ContentSequence, 446 | E: Encoder, 447 | { 448 | if self.is_truthy() { 449 | section.with(self).render(encoder) 450 | } else { 451 | Ok(()) 452 | } 453 | } 454 | 455 | #[inline] 456 | fn render_field_escaped( 457 | &self, 458 | hash: u64, 459 | _name: &str, 460 | encoder: &mut E, 461 | ) -> Result 462 | where 463 | E: Encoder, 464 | { 465 | match self.raw_entry().from_hash(hash, |_| true) { 466 | Some((_, v)) => v.render_escaped(encoder).map(|_| true), 467 | None => Ok(false), 468 | } 469 | } 470 | 471 | #[inline] 472 | fn render_field_unescaped( 473 | &self, 474 | hash: u64, 475 | _name: &str, 476 | encoder: &mut E, 477 | ) -> Result 478 | where 479 | E: Encoder, 480 | { 481 | match self.raw_entry().from_hash(hash, |_| true) { 482 | Some((_, v)) => v.render_unescaped(encoder).map(|_| true), 483 | None => Ok(false), 484 | } 485 | } 486 | 487 | #[inline] 488 | fn render_field_section( 489 | &self, 490 | hash: u64, 491 | _name: &str, 492 | section: Section, 493 | encoder: &mut E, 494 | ) -> Result 495 | where 496 | C: ContentSequence, 497 | E: Encoder, 498 | { 499 | match self.raw_entry().from_hash(hash, |_| true) { 500 | Some((_, v)) => v.render_section(section, encoder).map(|_| true), 501 | None => Ok(false), 502 | } 503 | } 504 | 505 | #[inline] 506 | fn render_field_inverse( 507 | &self, 508 | hash: u64, 509 | _name: &str, 510 | section: Section, 511 | encoder: &mut E, 512 | ) -> Result 513 | where 514 | C: ContentSequence, 515 | E: Encoder, 516 | { 517 | match self.raw_entry().from_hash(hash, |_| true) { 518 | Some((_, v)) => v.render_inverse(section, encoder).map(|_| true), 519 | None => Ok(false), 520 | } 521 | } 522 | } 523 | 524 | impl Default for HashMap { 525 | #[inline] 526 | fn default() -> Self { 527 | Self(Default::default()) 528 | } 529 | } 530 | 531 | impl Deref for HashMap { 532 | type Target = hashbrown::HashMap; 533 | 534 | #[inline] 535 | fn deref(&self) -> &Self::Target { 536 | &self.0 537 | } 538 | } 539 | 540 | impl DerefMut for HashMap { 541 | #[inline] 542 | fn deref_mut(&mut self) -> &mut Self::Target { 543 | &mut self.0 544 | } 545 | } 546 | 547 | impl HashMap { 548 | #[inline] 549 | pub(crate) fn is_empty(&self) -> bool { 550 | self.0.is_empty() 551 | } 552 | } 553 | 554 | #[cfg(test)] 555 | mod test { 556 | #[test] 557 | fn simple_render_hash_map() { 558 | use super::HashMap; 559 | 560 | let source = "{{title}}

{{ title }}

{{body}}
"; 561 | let tpl = ramhorns::Template::new(source).unwrap(); 562 | 563 | let mut map = HashMap::default(); 564 | 565 | map.insert("title", "Hello, Ramhorns!"); 566 | map.insert( 567 | "body", 568 | "This is a test of rendering a template with a HashMap Content!", 569 | ); 570 | 571 | let rendered = tpl.render(&map); 572 | 573 | assert_eq!( 574 | &rendered, 575 | "Hello, Ramhorns!

Hello, Ramhorns!

\ 576 |
This is a test of rendering a template with a HashMap Content!
" 577 | ); 578 | } 579 | } 580 | --------------------------------------------------------------------------------