├── .circleci └── config.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── book ├── .gitignore ├── book.toml └── src │ ├── SUMMARY.md │ ├── contributing │ └── README.md │ ├── introduction.md │ └── test-cases │ ├── README.md │ ├── escaped │ └── README.md │ └── tag-import │ ├── README.md │ └── fixture.css ├── src ├── lib.rs └── main.rs └── test.sh /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | jobs: 4 | 5 | test: 6 | docker: 7 | - image: rust:latest 8 | steps: 9 | - checkout 10 | 11 | - restore_cache: 12 | keys: 13 | - v1-cargo-cache-test-{{ arch }}-{{ .Branch }} 14 | - v1-cargo-cache-test-{{ arch }} 15 | 16 | # Install Rust Stable 17 | - run: 18 | name: Install Rust stable 19 | command: rustup update stable && rustup default stable 20 | 21 | # Show versions 22 | - run: 23 | name: Show versions 24 | command: rustc --version && cargo --version 25 | 26 | # Run tests 27 | - run: 28 | name: Run all tests 29 | command: ./test.sh 30 | 31 | # Save cache 32 | - save_cache: 33 | key: v1-cargo-cache-test-{{ arch }}-{{ .Branch }} 34 | paths: 35 | - target 36 | - /usr/local/cargo 37 | 38 | docs-build: 39 | docker: 40 | - image: rust:latest 41 | steps: 42 | - checkout 43 | 44 | - restore_cache: 45 | keys: 46 | - v1-cargo-cache-docs-{{ arch }}-{{ .Branch }} 47 | - v1-cargo-cache-docs-{{ arch }} 48 | 49 | # Install Rust Stable 50 | - run: 51 | name: Install Rust stable 52 | command: rustup update stable && rustup default stable 53 | 54 | # Show versions 55 | - run: 56 | name: Show versions 57 | command: rustc --version && cargo --version 58 | 59 | # Install mdbook 60 | - run: 61 | name: Install mdbook 62 | command: > 63 | (test -x $CARGO_HOME/bin/cargo-install-update || cargo install cargo-update) 64 | && (test -x $CARGO_HOME/bin/mdbook || cargo install --vers "^0.2" mdbook) 65 | && (cargo install --path . -f) # Install mdbook-bookimport from our local code 66 | && mv ~/.gitconfig ~/.gitconfig.disabled # Workaround for https://github.com/nabijaczleweli/cargo-update/issues/100 67 | && cargo install-update -a 68 | && mv ~/.gitconfig.disabled ~/.gitconfig 69 | 70 | # Build docs 71 | - run: 72 | name: Build docs 73 | command: > 74 | (cd book && mdbook build) 75 | && cargo doc --no-deps -p mdbook-bookimport 76 | && cp -R target/doc book/book/api 77 | - persist_to_workspace: 78 | root: book 79 | paths: book 80 | 81 | # Save cache 82 | - save_cache: 83 | key: v1-cargo-cache-docs-{{ arch }}-{{ .Branch }} 84 | paths: 85 | - target 86 | - /usr/local/cargo 87 | 88 | docs-deploy: 89 | docker: 90 | - image: node:10 91 | steps: 92 | - checkout 93 | - attach_workspace: 94 | at: book 95 | - run: 96 | name: Disable jekyll builds 97 | command: touch book/book/.nojekyll 98 | - run: 99 | name: Install and configure dependencies 100 | command: > 101 | npm install -g gh-pages@2 102 | && git config user.email "ci-build@circleci" 103 | && git config user.name "ci-build" 104 | - add_ssh_keys: 105 | fingerprints: 106 | - "e6:88:2d:b4:4d:bc:48:2c:25:42:c7:0c:73:0b:2e:b1" 107 | - run: 108 | name: Deploy docs to gh-pages branch 109 | command: gh-pages --dotfiles --message "[skip ci] Updates" --dist book/book 110 | 111 | workflows: 112 | version: 2 113 | build: 114 | jobs: 115 | - test 116 | - docs-build 117 | - docs-deploy: 118 | requires: 119 | - docs-build 120 | filters: 121 | branches: 122 | only: master 123 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | .idea 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "mdbook-bookimport" 3 | version = "0.1.1" 4 | authors = ["The Tailwind Developers "] 5 | description = "Import code/text from other files into your mdbook - without the link rot." 6 | keywords = ["mdbook", "include", "import", "code", "embed"] 7 | documentation = "https://tailwind.github.io/mdbook-bookimport/" 8 | repository = "https://github.com/tailwind/mdbook-bookimport" 9 | license = "MIT/Apache-2.0" 10 | edition = "2018" 11 | 12 | [dependencies] 13 | chrono = "0.4.6" 14 | clap = "2.32.0" 15 | env_logger = "0.6.1" 16 | failure = "0.1.5" 17 | lazy_static = "1.3.0" 18 | log = "0.4" 19 | mdbook = "0.2.3" 20 | regex = "1.1.2" 21 | serde_json = "1.0.39" 22 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 The Tailwind Developers 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 The Tailwind Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | mdbook-bookimport 2 | ===== 3 | 4 | [![Build status](https://circleci.com/gh/tailwind/mdbook-bookimport.svg?style=shield&circle-token=:circle-token)](https://circleci.com/gh/tailwind/mdbook-bookimport) 5 | 6 | > Import code/text from other files into your mdbook - without the link rot. 7 | 8 | ## Background / Initial Motivation 9 | 10 | `mdbook-bookimport` started as an issue in [mdbook #879](https://github.com/rust-lang-nursery/mdBook/issues/879). 11 | 12 | At this time the default `#include` preprocessor in `mdbook` only supports importing smaller sections of a file by specifying 13 | line numbers - so if you're including pieces of files that are actively maintained/changed you end up forgetting to update 14 | the line numbers of your imports as your files change. 15 | 16 | `mdbook-bookimport` allows you to import pieces of files based on text in the file - so that are you modify the file you continue 17 | to import the code that you expected to. 18 | 19 | ## Quickstart 20 | 21 | ```sh 22 | cargo install mdbook-bookimport 23 | ``` 24 | 25 | ```toml 26 | # In your book.toml 27 | [preprocessor.bookimport] 28 | ``` 29 | 30 | ```md 31 | 32 | 33 | {{#bookimport ../path/to/file.foo@some-tag-name-here}} 34 | ``` 35 | 36 | ```rust 37 | // Some file named "file.foo" 38 | fn main () { 39 | let not_imported = "This will NOT be imported!"; 40 | 41 | // @book start some-tag-name-here 42 | 43 | // ... 44 | let imported = "This will be imported!" 45 | let also_imported = "Everyting between start/end gets imported." 46 | // ... 47 | 48 | // @book end some-tag-name-here 49 | } 50 | ``` 51 | 52 | ```md 53 | 54 | 55 | 56 | // ... 57 | let imported = "This will be imported!" 58 | let also_imported = "Everyting between start/end gets imported." 59 | // ... 60 | 61 | 62 | ``` 63 | 64 | ## [Full Guide](https://tailwind.github.io/mdbook-bookimport/) 65 | 66 | [The mdbook-bookimport guide](https://tailwind.github.io/mdbook-bookimport/) 67 | 68 | ## [API Documentation](https://tailwind.github.io/mdbook-bookimport/api/mdbook_bookimport) 69 | 70 | [API](https://tailwind.github.io/mdbook-bookimport/api/mdbook_bookimport) 71 | 72 | ## Troubleshooting 73 | 74 | If for some reason something ever went wrong for any reason..: 75 | 76 | `RUST_LOG=debug mdbook build` would give more information. 77 | 78 | ## To Test 79 | 80 | ```sh 81 | ./test.sh 82 | ``` 83 | 84 | ## See Also 85 | 86 | - [mdbook](https://github.com/rust-lang-nursery/mdBook) 87 | 88 | ## License 89 | 90 | Apache 2.0 / MIT 91 | -------------------------------------------------------------------------------- /book/.gitignore: -------------------------------------------------------------------------------- 1 | book 2 | -------------------------------------------------------------------------------- /book/book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["Chinedu Francis Nwafili"] 3 | multilingual = false 4 | src = "src" 5 | title = "The Mdbook Bookimport Book" 6 | 7 | # @book start book-section 8 | [preprocessor.bookimport] 9 | 10 | # @book end book-section 11 | -------------------------------------------------------------------------------- /book/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | [Introduction](./introduction.md) 4 | 5 | --- 6 | 7 | - [Contributing](./contributing/README.md) 8 | - [Test Cases](./test-cases/README.md) 9 | - [Tag Import](./test-cases/tag-import/README.md) 10 | - [Escaped](./test-cases/escaped/README.md) 11 | -------------------------------------------------------------------------------- /book/src/contributing/README.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ...TODO... 4 | -------------------------------------------------------------------------------- /book/src/introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | When working on a book/guide for a repository you'll sometimes find yourself wanting to 4 | import some of your source code into your guide so that you can discuss it or provide 5 | higher level context. 6 | 7 | `mdbook` comes with a way to `#include` in between two line numbers in a file - but this 8 | can be prone to link rot when you modify a file but forget to modify all of the sections 9 | in your guide that refer to a file. 10 | 11 | `Bookimport` seeks to address this by allowing you to import sections of a file by annotating 12 | the file. 13 | 14 | This allows you to modify the code between the annotations as much as you like and the import will 15 | still behave as you originally intended. 16 | 17 | `Bookimport` was originally created to close [mdbook issue #879](https://github.com/rust-lang-nursery/mdBook/issues/879). 18 | 19 | ## Installation 20 | 21 | ```sh 22 | cargo install mdbook-bookimport 23 | ``` 24 | 25 | ## In your book.toml 26 | 27 | ```md 28 | {{#bookimport ../book.toml@book-section }} 29 | ``` 30 | 31 | ## Usage 32 | 33 | Annotate any file with. 34 | 35 | ```rust 36 | // @book start some-tag 37 | // ... contents go here ... 38 | // @book end some-tag 39 | ``` 40 | 41 | Bookimport only looks for the `@book {start,end} some-tag`, so depending on 42 | the file type that you're in you'll want to comment thoe annotation out 43 | appropriately. 44 | 45 | --- 46 | 47 | Here's how to use bookimport to import a section of a file 48 | labeled `book-section`. 49 | 50 | ```md 51 | 52 | 53 | /{{#bookimport ../book.toml@book-section }} 54 | ``` 55 | 56 | ```toml 57 | # Contents of book.toml 58 | 59 | # ... 60 | 61 | # @book start book-section 62 | src = "src" 63 | title = "The Mdbook Bookimport Book" 64 | # @book end book-section 65 | 66 | # ... 67 | ``` 68 | -------------------------------------------------------------------------------- /book/src/test-cases/README.md: -------------------------------------------------------------------------------- 1 | # Test Cases 2 | 3 | This section contains different chapters that our test cases 4 | will use to verify that Bookimport works as expected. 5 | -------------------------------------------------------------------------------- /book/src/test-cases/escaped/README.md: -------------------------------------------------------------------------------- 1 | # Escaped Bookimport 2 | 3 | ``` 4 | /{{#bookimport ./ignored.txt@foo-bar}} 5 | ``` 6 | -------------------------------------------------------------------------------- /book/src/test-cases/tag-import/README.md: -------------------------------------------------------------------------------- 1 | # Tag Import 2 | 3 | ```md 4 | {{#bookimport ./fixture.css@cool-css }} 5 | ``` 6 | -------------------------------------------------------------------------------- /book/src/test-cases/tag-import/fixture.css: -------------------------------------------------------------------------------- 1 | .this-will-not-be-included { 2 | display: none; 3 | } 4 | 5 | /* @book start cool-css */ 6 | 7 | .this-will-be-included { 8 | display: block; 9 | } 10 | 11 | /* @book end cool-css */ 12 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! mdbook-bookimport is a pre-processor for [mdbook]'s that helps you avoid link rot 2 | //! when importing parts of other files into your mdbook. 3 | //! 4 | //! [mdbook]: https://github.com/rust-lang-nursery/mdBook 5 | 6 | #![deny(missing_docs, warnings)] 7 | 8 | use failure::Fail; 9 | use lazy_static::lazy_static; 10 | use log::*; 11 | use mdbook::book::{Book, Chapter}; 12 | use mdbook::preprocess::{Preprocessor, PreprocessorContext}; 13 | use mdbook::BookItem; 14 | use regex::Regex; 15 | use std::path::{Path, PathBuf}; 16 | 17 | // Originally tried using "\" but ran into issues with mdbook seemingly stripping it. 18 | // Probably because it also uses "\" to escape it's imports 19 | static _ESCAPE_CHAR: &'static str = "/"; 20 | 21 | /// The pre-processor that powers the mdbook-bookimport plugin 22 | pub struct Bookimport; 23 | 24 | impl Preprocessor for Bookimport { 25 | fn name(&self) -> &str { 26 | "mdbook-bookimport" 27 | } 28 | 29 | /// Given a book (usually from stdin) process all of the chapters and replace 30 | /// any #bookimport's with the content that you're importing. 31 | fn run( 32 | &self, 33 | ctx: &PreprocessorContext, 34 | mut book: Book, 35 | ) -> Result { 36 | debug!("Running `run` method in bookimport Preprocessor trait impl"); 37 | 38 | let book_src_dir = ctx.root.join(&ctx.config.book.src); 39 | 40 | for section in book.sections.iter_mut() { 41 | process_chapter(section, &book_src_dir)?; 42 | } 43 | 44 | Ok(book) 45 | } 46 | } 47 | 48 | /// Process a chapter in an mdbook. 49 | /// 50 | /// Namely - replace all #bookimport calls with the content that it was trying to import. 51 | /// 52 | /// If the chapter has subchapters they will also be processed recursively. 53 | fn process_chapter(book_item: &mut BookItem, book_src_dir: &PathBuf) -> mdbook::errors::Result<()> { 54 | if let BookItem::Chapter(ref mut chapter) = book_item { 55 | debug!("Processing chapter {}", chapter.name); 56 | 57 | // The full path within the filesystem to the directory that holds the mdbook's 58 | // SUMMARY.md file 59 | // 60 | // /path/to/.../my-mdbook 61 | let chapter_dir = chapter 62 | .path 63 | .parent() 64 | .map(|dir| book_src_dir.join(dir)) 65 | .expect("All book items have a parent"); 66 | 67 | let mut content = chapter.content.clone(); 68 | 69 | let simports = BookImport::find_unescaped_bookimports(chapter); 70 | 71 | // Iterate backwards through the simports so that we start by replacing the imports 72 | // that are lower in the file first. 73 | // 74 | // This ensures that as we replace simports we aren't throwing off the start and end 75 | // indices of other simports. 76 | for simport in simports.iter().rev() { 77 | let new_content = match simport.read_content_between_tags(&chapter_dir) { 78 | Ok(new_content) => new_content, 79 | Err(err) => panic!("Error reading content for bookimport: {:#?}", err), 80 | }; 81 | 82 | // Replace the #bookimport in the chapter with the contents that we were 83 | // trying to impor. 84 | content = content.replace(simport.full_simport_text, &new_content); 85 | } 86 | 87 | chapter.content = content; 88 | 89 | // Process all of the chapters within this chapter 90 | for sub_item in chapter.sub_items.iter_mut() { 91 | process_chapter(sub_item, book_src_dir)?; 92 | } 93 | } 94 | 95 | Ok(()) 96 | } 97 | 98 | /// # Example 99 | /// 100 | /// If you look at book/src/introduction.md you'll see this book import: 101 | /// 102 | /// ```md,ignore 103 | /// {{#bookimport ../book.toml@book-section }} 104 | /// ``` 105 | /// 106 | /// Which refers to this part of our book/book.toml 107 | /// 108 | /// ```toml,ignore 109 | /// # @book start book-section 110 | /// [preprocessor.bookimport] 111 | /// // ... 112 | /// # @book end book-section 113 | /// ``` 114 | /// 115 | /// The doc comments on the struct fields refer to this bookimport 116 | #[derive(Debug, PartialEq)] 117 | struct BookImport<'a> { 118 | /// The book chapter that this #bookimport was found in 119 | /// 120 | /// introduction.md 121 | host_chapter: &'a Chapter, 122 | /// The filepath relative to the chapter 123 | /// 124 | /// ../book.toml 125 | file: PathBuf, 126 | /// The text of this bookimport in the host_chapter 127 | /// 128 | /// {{ #bookimport some-file.txt@some-tag }} 129 | full_simport_text: &'a str, 130 | /// Tags after the characters after an `@` symbol. When importing from a file 131 | /// Bookimport will pull all text before and after the `@tag` 132 | /// 133 | /// Some(book-section) 134 | tag: &'a str, 135 | /// Where in the chapter's bytes does this bookimport start? 136 | start: usize, 137 | /// Where in the chapter's bytes does this bookimport end? 138 | end: usize, 139 | } 140 | 141 | // Wrapping in lazy_static ensures that our regex is only compiled once 142 | lazy_static! { 143 | /// The regex that finds bookimports such as 144 | /// -> `{{ #bookimport some-file.txt@some-tag }}` 145 | /// 146 | /// It will also find escaped bookimports such as 147 | /// -> `\{{ #bookimport some-file.txt@some-tag }}` 148 | /// 149 | /// We parse both escaped and unescaped so that we can later completely ignore the escaped ones. 150 | static ref SUPERIMPORT_REGEX: Regex = Regex::new( 151 | r"(?x) # (?x) means insignificant whitespace mode 152 | # allows us to put comments and space things out. 153 | 154 | /\{\{\#.*\}\} # escaped import such as `/{{ #bookimport some-file.txt@some-tag }}` 155 | 156 | | # OR 157 | 158 | # Non escaped import -> `{{ #bookimport some-file.txt@some-tag }}` 159 | \{\{\s* # opening braces and whitespace 160 | \#bookimport # #bookimport 161 | \s+ # separating whitespace 162 | (?P[a-zA-Z0-9\s_.\-/\\]+) # some-file.txt 163 | @ # @ symbol that denotes the name of a tag 164 | (?P[a-zA-Z0-9_.\-]+) # some-tag (alphanumeric underscores and dashes) 165 | \s*\}\} # whitespace and closing braces 166 | " 167 | ).unwrap(); 168 | } 169 | 170 | impl<'a> BookImport<'a> { 171 | /// Parse a chapter within an mdbook for bookimport's and return them 172 | fn find_unescaped_bookimports(chapter: &Chapter) -> Vec { 173 | let mut simports = vec![]; 174 | 175 | let matches = SUPERIMPORT_REGEX.captures_iter(chapter.content.as_str()); 176 | 177 | for capture_match in matches { 178 | // {{#bookimport ./fixture.css@cool-css }} 179 | // OR 180 | // #{{#bookimport ./fixture.css@cool-css }} 181 | let full_capture = capture_match.get(0).unwrap(); 182 | 183 | let full_simport_text = &chapter.content[full_capture.start()..full_capture.end()]; 184 | 185 | // NOTE: The backslash means that this import was escaped by the author, so 186 | // we don't want to replace it. 187 | // /{{#bookimport ./fixture.css@cool-css }} 188 | if full_simport_text.starts_with(r"/") { 189 | continue; 190 | } 191 | 192 | let file = capture_match["file"].into(); 193 | let tag = capture_match.get(2).unwrap(); 194 | 195 | let simport = BookImport { 196 | host_chapter: chapter, 197 | file, 198 | full_simport_text, 199 | tag: &chapter.content[tag.start()..tag.end()], 200 | start: full_capture.start(), 201 | end: full_capture.end(), 202 | }; 203 | 204 | simports.push(simport); 205 | } 206 | 207 | simports 208 | } 209 | } 210 | 211 | // TODO: Create TagError variants and add better error handling. 212 | #[derive(Debug, Fail, PartialEq)] 213 | enum TagError { 214 | #[fail(display = "Could not find `@book start {}`", tag)] 215 | #[allow(unused)] // TODO: -> Use this 216 | MissingStartTag { tag: String }, 217 | } 218 | 219 | impl<'a> BookImport<'a> { 220 | /// TODO: Return failure::Error instead if TagError 221 | fn read_content_between_tags(&self, chapter_dir: &PathBuf) -> Result { 222 | debug!( 223 | r#"Reading content in chapter "{}" for bookimport "{:#?}" "#, 224 | self.host_chapter.name, self.full_simport_text 225 | ); 226 | 227 | let path = Path::join(&chapter_dir, &self.file); 228 | 229 | let content = String::from_utf8(::std::fs::read(&path).unwrap()).unwrap(); 230 | 231 | // @book start foo <--- this line is not captured 232 | // ... match all of these 233 | // ... lines between the 234 | // ... start and end tags 235 | // @book end foo <--- this line is not captured 236 | let start_regex = Regex::new(&format!( 237 | r"(?x) # Insignificant whitespace mode (allows for comments) 238 | @book 239 | \s+ # Separating whitespace 240 | start 241 | \s+ # Separating whitespace 242 | {tag} 243 | 244 | .*? # Characters between start import tag and end of line 245 | 246 | [\n\r] # New line right before the start import tag 247 | 248 | (?P # Everything in between the start and end import lines 249 | (.|\n|\r)* 250 | ) 251 | 252 | [\n\r] # New line right before the end import tag 253 | 254 | .*? # Characters between start of end import line and end import tag 255 | 256 | @book 257 | \s+ # Separating whitespace 258 | end 259 | \s+ # Separating whitespace 260 | {tag} 261 | ", 262 | tag = regex::escape(self.tag) 263 | )) 264 | .unwrap(); 265 | 266 | let captures = start_regex.captures(&content).unwrap(); 267 | 268 | let content_between_tags = captures["content_to_import"].to_string(); 269 | 270 | Ok(content_between_tags) 271 | } 272 | } 273 | 274 | #[cfg(test)] 275 | mod tests { 276 | use super::*; 277 | 278 | #[test] 279 | fn parse_simports_from_chapter() { 280 | let tag_import_chapter = make_tag_import_chapter(); 281 | 282 | let simports = BookImport::find_unescaped_bookimports(&tag_import_chapter); 283 | 284 | let expected_simports = vec![BookImport { 285 | host_chapter: &tag_import_chapter, 286 | file: "./fixture.css".into(), 287 | full_simport_text: "{{#bookimport ./fixture.css@cool-css }}", 288 | tag: "cool-css", 289 | start: 20, 290 | end: 59, 291 | }]; 292 | 293 | assert_eq!(simports, expected_simports); 294 | } 295 | 296 | #[test] 297 | fn ignore_escaped_simport() { 298 | let escaped_import_chapter = make_escaped_import_chapter(); 299 | 300 | let simports = BookImport::find_unescaped_bookimports(&escaped_import_chapter); 301 | 302 | assert_eq!(simports.len(), 0); 303 | } 304 | 305 | #[test] 306 | fn content_between_tags() { 307 | let tag_import_chapter = make_tag_import_chapter(); 308 | 309 | let simport = &BookImport::find_unescaped_bookimports(&tag_import_chapter)[0]; 310 | 311 | let chapter_dir = "book/src/test-cases/tag-import"; 312 | let chapter_dir = format!("{}/{}", env!("CARGO_MANIFEST_DIR"), chapter_dir); 313 | 314 | let content_between_tags = simport.read_content_between_tags(&chapter_dir.into()); 315 | 316 | let expected_content = r#" 317 | .this-will-be-included { 318 | display: block; 319 | } 320 | "#; 321 | 322 | assert_eq!(content_between_tags.unwrap(), expected_content); 323 | } 324 | 325 | #[test] 326 | fn replace_chapter() { 327 | let tag_import_chapter = make_tag_import_chapter(); 328 | let mut item = BookItem::Chapter(tag_import_chapter); 329 | 330 | process_chapter(&mut item, &"".into()).unwrap(); 331 | 332 | // Spacing an indentation is intentional 333 | let expected_content = r#"# Tag Import 334 | 335 | ```md 336 | 337 | .this-will-be-included { 338 | display: block; 339 | } 340 | 341 | ``` 342 | "#; 343 | match item { 344 | BookItem::Chapter(tag_import_chapter) => { 345 | assert_eq!(tag_import_chapter.content.as_str(), expected_content); 346 | } 347 | _ => panic!(""), 348 | }; 349 | } 350 | 351 | #[test] 352 | fn replace_escaped_simport() { 353 | let escaped_import_chapter = make_escaped_import_chapter(); 354 | 355 | // Spacing an indentation is intentional. 356 | // We're testing that the 357 | let expected_content = r#"# Escaped Bookimport 358 | 359 | ``` 360 | /{{#bookimport ./ignored.txt@foo-bar}} 361 | ``` 362 | "#; 363 | 364 | let mut item = BookItem::Chapter(escaped_import_chapter); 365 | 366 | process_chapter(&mut item, &"".into()).unwrap(); 367 | 368 | match item { 369 | BookItem::Chapter(escaped_chapter) => { 370 | assert_eq!(escaped_chapter.content.as_str(), expected_content); 371 | } 372 | _ => panic!(""), 373 | }; 374 | } 375 | 376 | // Create a chapter to represent our tag-import test case in the /book 377 | // directory in this repo. 378 | fn make_tag_import_chapter() -> Chapter { 379 | let chapter = "book/src/test-cases/tag-import/README.md"; 380 | 381 | let tag_import_chapter = Chapter::new( 382 | "Tag Import", 383 | include_str!("../book/src/test-cases/tag-import/README.md").to_string(), 384 | &format!("{}/{}", env!("CARGO_MANIFEST_DIR"), chapter), 385 | vec![], 386 | ); 387 | 388 | tag_import_chapter 389 | } 390 | 391 | // Create a chapter to represent our Escaped test case in the /book 392 | // directory in this repo. 393 | fn make_escaped_import_chapter() -> Chapter { 394 | let chapter = "book/src/test-cases/escaped/README.md"; 395 | 396 | let tag_import_chapter = Chapter::new( 397 | "Escaped", 398 | include_str!("../book/src/test-cases/escaped/README.md").to_string(), 399 | &format!("{}/{}", env!("CARGO_MANIFEST_DIR"), chapter), 400 | vec![], 401 | ); 402 | 403 | tag_import_chapter 404 | } 405 | } 406 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | //! mdbook-bookimport is a pre-processor for [mdbook]'s that helps you avoid link rot 2 | //! when importing parts of other files into your mdbook. 3 | //! 4 | //! [mdbook]: https://github.com/rust-lang-nursery/mdBook 5 | 6 | #![deny(missing_docs, warnings)] 7 | 8 | #[macro_use] 9 | extern crate log; 10 | 11 | use env_logger::Builder; 12 | 13 | use chrono::Local; 14 | use log::LevelFilter; 15 | use std::{env, process}; 16 | 17 | use clap::{App, Arg, ArgMatches, SubCommand}; 18 | use mdbook::{ 19 | errors::Error, 20 | preprocess::{CmdPreprocessor, Preprocessor}, 21 | }; 22 | use mdbook_bookimport::Bookimport; 23 | 24 | fn main() { 25 | init_logging(); 26 | 27 | let matches = make_cli().get_matches(); 28 | 29 | let bookimport = Bookimport {}; 30 | 31 | if let Some(sub_args) = matches.subcommand_matches("supports") { 32 | handle_supports(&bookimport, sub_args); 33 | } else { 34 | if let Err(e) = handle_preprocessing(&bookimport) { 35 | error!("{}", e); 36 | process::exit(1); 37 | } 38 | } 39 | } 40 | 41 | // Used by mdbook to determine whether or not our binary can be used as a pre-processor 42 | fn make_cli() -> App<'static, 'static> { 43 | App::new("mdbook-bookimport") 44 | .about("Import code/text from other files into your mdbook - without the link rot.") 45 | .subcommand( 46 | SubCommand::with_name("supports") 47 | .arg(Arg::with_name("renderer").required(true)) 48 | .about("Check whether a renderer is supported by this preprocessor"), 49 | ) 50 | } 51 | 52 | // Used by mdbook to determine whether or not our binary can be used as a pre-processor 53 | fn handle_supports(bookimport: &dyn Preprocessor, sub_args: &ArgMatches) -> ! { 54 | let renderer = sub_args.value_of("renderer").expect("Required argument"); 55 | let supported = bookimport.supports_renderer(&renderer); 56 | 57 | // Signal whether the renderer is supported by exiting with 1 or 0. 58 | if supported { 59 | process::exit(0); 60 | } else { 61 | process::exit(1); 62 | } 63 | } 64 | 65 | // Run our preprocessor to replace #bookimport's in every chapter in an mdbook 66 | fn handle_preprocessing(bookimport: &dyn Preprocessor) -> Result<(), Error> { 67 | let (ctx, book) = CmdPreprocessor::parse_input(::std::io::stdin())?; 68 | 69 | let book_after_bookimport = bookimport.run(&ctx, book)?; 70 | 71 | serde_json::to_writer(::std::io::stdout(), &book_after_bookimport)?; 72 | 73 | Ok(()) 74 | } 75 | 76 | fn init_logging() { 77 | use std::io::Write; 78 | let mut builder = Builder::new(); 79 | 80 | builder.format(|formatter, record| { 81 | writeln!( 82 | formatter, 83 | "{} [{}] ({}): {}", 84 | Local::now().format("%Y-%m-%d %H:%M:%S"), 85 | record.level(), 86 | record.target(), 87 | record.args() 88 | ) 89 | }); 90 | 91 | if let Ok(var) = env::var("RUST_LOG") { 92 | builder.parse_filters(&var); 93 | } else { 94 | // if no RUST_LOG provided, default to logging at the Info level 95 | builder.filter(None, LevelFilter::Info); 96 | // Filter extraneous html5ever not-implemented messages 97 | builder.filter(Some("html5ever"), LevelFilter::Error); 98 | } 99 | 100 | builder.init(); 101 | } 102 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cargo build --all && cargo test --all 4 | --------------------------------------------------------------------------------