Compare commits

..

711 Commits

Author SHA1 Message Date
Samy Pessé 35f0581c17 Bump version to 3.0.0-pre.4 2016-03-07 11:16:43 +01:00
Samy Pessé c79f02fe48 Add sitemap plugin for docs 2016-03-07 11:16:27 +01:00
Samy Pessé ec028a1c0d Add deprecated methods isSubBook and contentPath 2016-03-07 11:16:13 +01:00
Samy Pessé e3155dd13a Update plugin-search@1.2.0 2016-03-07 11:00:16 +01:00
Samy Pessé b61254dda6 Add more deprecated api 2016-03-07 11:00:01 +01:00
Samy Pessé b4bdf97cfe Fix linting errors 2016-03-07 10:40:25 +01:00
Samy Pessé bf98984012 Add link to slack 2016-03-07 10:28:44 +01:00
Samy Pessé 77258cbbc9 Improve intro for doc 2016-03-07 10:27:31 +01:00
Samy Pessé 4150455c3e Improve docs 2016-03-07 10:10:38 +01:00
Samy Pessé 008aacb5c2 Fix log when installing plugins 2016-03-07 09:41:59 +01:00
Samy Pessé d12d6a6a46 Fix deprecated method root for send module 2016-03-07 09:41:05 +01:00
Samy Pessé ef7594b8f7 Remove section about autocover 2016-03-07 09:38:56 +01:00
Soreine 6a73217740 Adds section for covers 2016-03-06 09:08:48 +01:00
Samy Pesse 47c44fca89 Add changelog for master 2016-03-05 22:39:11 +01:00
Samy Pesse 6fa63a5c35 Fix #1172: Fix second argument for ebook generation 2016-03-05 22:37:25 +01:00
Samy Pessé 29533908c2 Merge pull request #1168 from GitbookIO/enhancement/doc
v3 doc review
2016-03-05 15:14:17 +01:00
Soreine 74a1e9dee2 Corrects paths. And reformulate associated FAQ 2016-03-03 16:39:18 +01:00
Soreine b3662e07c1 End of review 2016-03-03 16:39:18 +01:00
Soreine 200e0c58c9 More precise git url ? 2016-03-03 16:39:17 +01:00
Soreine e67286c51d Reviewing, first part 2016-03-03 16:39:17 +01:00
Soreine 603622e337 Update plugin-highlight version to 2.0.0 2016-03-03 16:38:09 +01:00
Samy Pessé 5c2a435a25 Update everything (npm, etc) 2016-03-02 11:22:24 +01:00
Samy Pessé 4afcd722ae Fix page description tests 2016-03-02 11:22:12 +01:00
Samy Pessé 21d6964230 Extend "page" with frontmatter attributes 2016-03-02 11:11:39 +01:00
Samy Pessé 4499ccc501 Explicitly use current version as gitbook version to build 2016-03-02 10:01:32 +01:00
Samy Pessé abbca568d1 Bump version to 3.0.0-pre.3 2016-03-02 09:29:30 +01:00
Samy Pesse 40e49d0ac9 Change json format version to follow major version of gitbook 2016-03-01 22:29:09 +01:00
Samy Pessé 8d9a0a91f0 Add test for plugin installation from github 2016-03-01 16:51:47 +01:00
Samy Pessé 15640dfdf0 Add lint to jsonlint 2016-03-01 16:31:29 +01:00
Samy Pesse 2f5dde5d2f Fix links in documentation 2016-02-29 22:00:55 +01:00
Samy Pesse a9a8a04bca Tweaks in documentation 2016-02-29 21:59:05 +01:00
Samy Pesse c08e5ce62c Improve structure of doc 2016-02-29 21:50:48 +01:00
Samy Pessé ec353e179d Remove .gitbook and add "root" option 2016-02-29 17:35:12 +01:00
Samy Pessé 496f253e69 Don't copy _layouts to output 2016-02-29 10:43:53 +01:00
Samy Pessé e436115a4a Bump version to 3.0.0-pre.2 2016-02-29 09:16:00 +01:00
Samy Pessé 1c61f93b5f Add simple test for exports 2016-02-29 09:14:43 +01:00
Samy Pessé 0494f7d1fd Fix #1165: correctly normalize path in summary to accept unicode 2016-02-28 21:54:03 +01:00
Samy Pessé 4aa66338fc Add init command 2016-02-28 14:47:34 +01:00
Samy Pessé 8cda844ef1 Export output for plugins context 2016-02-28 12:46:47 +01:00
Samy Pesse dde1ef92f0 Add doc for ls-remote 2016-02-27 22:47:42 +01:00
Samy Pesse 999f8b481f Improve setup doc 2016-02-27 22:45:30 +01:00
Samy Pessé 294951f22a Change note in changelog 2016-02-26 10:07:11 +01:00
Samy Pessé 2619737f64 Bump version to 3.0.0-pre.1 2016-02-26 10:06:11 +01:00
Samy Pessé 445a90defb Simplify readme 2016-02-26 10:05:20 +01:00
Samy Pessé d3d64f636c Merge pull request #1109 from GitbookIO/3.0.0
Version 3.0.0
2016-02-26 09:41:26 +01:00
Samy Pessé eef072693b Update theme-default@1.0.0-pre.4 2016-02-26 09:40:58 +01:00
Samy Pessé 43c5f8d340 Don't add glossary to context when non existant 2016-02-26 09:25:11 +01:00
Samy Pessé b344d65302 Fix exec of svgexport on windows 2016-02-25 20:32:08 +01:00
Samy Pessé ce967f35ca Fix error message when svgexport is not installed 2016-02-25 19:21:27 +01:00
Samy Pessé 80718cc783 Fix some path normalization on windows 2016-02-25 19:15:47 +01:00
Samy Pessé 73f22332ec Update theme-default@1.0.0-pre.3 2016-02-25 16:39:25 +01:00
Samy Pessé e963b6b65d Add documentation for front matter 2016-02-25 16:37:40 +01:00
Samy Pessé 327e90e8ec Extract description from page's front matter
Fixes #1079 and #795
2016-02-25 15:43:55 +01:00
Samy Pessé 9253b764fa Don't pass cover to ebook-convert if non existant 2016-02-25 15:12:04 +01:00
Samy Pessé 393aed6270 Improve error msg for ebook generation 2016-02-25 15:09:57 +01:00
Samy Pessé b240d6a8fc Add filter fileExists 2016-02-25 14:50:58 +01:00
Samy Pessé 3cda0643fb Improve command "parse" 2016-02-25 14:45:16 +01:00
Samy Pessé 1ba63675d5 Support "sections" from gitbook 2 as deprecated for page hooks 2016-02-25 14:41:46 +01:00
Samy Pessé 32f52f2d95 Call page hooks during transformation to HTML 2016-02-25 14:26:27 +01:00
Samy Pessé 9215edc0a0 Remove option defaultPlugins and simplify loading 2016-02-25 14:17:31 +01:00
Samy Pessé 25ae21dae3 Call hook "init" during generation 2016-02-25 12:18:40 +01:00
Samy Pessé 94393bef4b Call hooks finish and finish:before 2016-02-25 12:13:31 +01:00
Samy Pessé 4f29183685 Document pdf options 2016-02-25 12:10:58 +01:00
Samy Pessé edecf56dd6 Use hook for configuration 2016-02-25 12:03:33 +01:00
Samy Pessé 08754bc626 Improve the faq 2016-02-25 11:59:45 +01:00
Samy Pessé 702542f408 Remove duplicate between book.* and config.* 2016-02-25 11:50:20 +01:00
Samy Pessé 6990b371a6 Add link to doc about .gitbook in faq 2016-02-25 11:47:41 +01:00
Samy Pessé 8020d9045b Improve header with edit button and version 2016-02-25 11:44:55 +01:00
Samy Pessé 34bb52a051 Improve templating documentation 2016-02-25 11:38:54 +01:00
Samy Pessé a2e0bc267c Improve documentation 2016-02-25 11:15:59 +01:00
Samy Pessé d86a95b5e1 Add json format version to the json output 2016-02-25 10:51:58 +01:00
Samy Pessé 585ed46034 Change "description" to "title" in config schema 2016-02-25 10:24:32 +01:00
Samy Pessé 82a4f80cd2 Use jsonschema to validate configuration 2016-02-25 10:12:46 +01:00
Samy Pessé f47a3968b7 Add tests for multilingual book and json output 2016-02-25 08:59:10 +01:00
Samy Pesse 0b592dd5c6 Add doc about languages 2016-02-24 23:02:00 +01:00
Samy Pesse addf6ade9a Add doc for glossary 2016-02-24 22:51:32 +01:00
Samy Pesse d7d0429169 Add doc section about summary 2016-02-24 22:42:11 +01:00
Samy Pesse 4bf5dc6646 Add section about ignoring files 2016-02-24 22:29:19 +01:00
Samy Pessé 5b20027f2e Use cover file from main book in multilingual book (when no cover is set for language) 2016-02-24 18:24:49 +01:00
Samy Pessé 4499f71dba Improve log when generation is finished 2016-02-24 18:12:23 +01:00
Samy Pessé 81b734c151 Fix generation of ebooks in multilanguages 2016-02-24 18:11:01 +01:00
Samy Pessé 0b4a6b5362 Output folder is an option for FolderOutput 2016-02-24 18:07:17 +01:00
Samy Pessé 3a0636046e Fix binding to context for plugin blocks 2016-02-24 17:20:48 +01:00
Samy Pessé 52eccb29e4 Add property depth to article and pages 2016-02-24 17:19:52 +01:00
Samy Pessé 86e4a935e2 Improve logging 2016-02-24 17:12:38 +01:00
Samy Pessé 1fa952b930 Fix inclusion of block using a simple function 2016-02-24 17:02:34 +01:00
Samy Pessé 78e11bc6be By default escape html in code blocks 2016-02-24 16:53:46 +01:00
Samy Pessé 40cc20e06e Load plugins once 2016-02-24 16:53:33 +01:00
Samy Pessé c223f970ec Rollback to gitbook-markdown@1.0.3 2016-02-24 16:29:12 +01:00
Samy Pessé daa80dc949 Fix conrefs loader with filename starting with / 2016-02-24 14:20:53 +01:00
Samy Pessé 255a78a534 Fix path option for template error 2016-02-24 14:10:37 +01:00
Samy Pessé 6faa469bf5 Fix install command: load config before running install 2016-02-24 14:06:56 +01:00
Samy Pessé eeefac4964 Update gitbook-markdown@1.1.1 2016-02-24 13:57:09 +01:00
Samy Pessé eb4770085a Update gitbook-markdown@1.1.0 2016-02-24 13:53:57 +01:00
Samy Pessé 1ed63ce4f5 Add context for multi-lingual books 2016-02-24 13:52:15 +01:00
Samy Pessé e85ad95bcf Generate multi-lingual index 2016-02-24 13:35:59 +01:00
Samy Pessé bd73c79787 Don't copy assets for each language book, but only for main book 2016-02-24 12:56:26 +01:00
Samy Pessé b244d506bd Correctly setup summary instance when file doesn't exist 2016-02-24 12:45:25 +01:00
Samy Pessé 44f03865c0 Add changelog for .gitbook 2016-02-24 12:14:20 +01:00
Samy Pessé 72dfb4f11d Ignore etst plugins and docs when linting 2016-02-23 15:26:28 +01:00
Samy Pessé 6b0a4f20bf Add documentation for .gitbook 2016-02-23 15:25:50 +01:00
Samy Pessé f052aacee1 Add .gitbook to locate book inside repository 2016-02-23 15:05:32 +01:00
Samy Pesse 13e2ff8035 Adapt test for paths to run on windows 2016-02-22 23:52:38 +01:00
Samy Pesse 199e61e01c Remove pdf file 2016-02-22 23:51:22 +01:00
Samy Pessé 1bf6abf338 Pass options to context of theme 2016-02-22 16:58:47 +01:00
Samy Pessé c7b1d72bf0 Add basic test for ebook generation 2016-02-22 15:46:53 +01:00
Samy Pessé 0b3bdcb219 Add tests for blocks from plugins 2016-02-22 15:39:36 +01:00
Samy Pessé 6653307fda Add tests for context of filters 2016-02-22 15:34:35 +01:00
Samy Pessé 642ba72a1d Load all filters and blocks from plugins in output's template 2016-02-22 14:50:55 +01:00
Samy Pessé 71144db09c Normalize context for plugins 2016-02-22 13:54:52 +01:00
Samy Pessé 395bd62663 Provide "plugins" context to theme templates 2016-02-22 12:31:02 +01:00
Samy Pessé d8fd6430ed Copy plugins resources to website output 2016-02-22 11:15:34 +01:00
Samy Pessé 1e243281c7 Add test for resources listing 2016-02-22 10:36:28 +01:00
Samy Pessé de23494409 Change gitignore to commit tests plugins 2016-02-22 10:20:43 +01:00
Samy Pessé b23d3a9f37 Add test for extension of book's configuration 2016-02-22 10:16:38 +01:00
Samy Pessé de31b90080 Add validation of plugin's config after loading 2016-02-22 10:11:44 +01:00
Samy Pessé ccc585ca1f Add doc for plugins 2016-02-22 08:59:19 +01:00
Samy Pessé 4dbe81cb66 Add base changelog 2016-02-22 08:54:46 +01:00
Samy Pessé d139d1d1bd Add "template.theme" and "template.default" variables 2016-02-21 19:41:38 +01:00
Samy Pessé a186544fad Add defaults filters to website tpl engine 2016-02-21 19:28:20 +01:00
Samy Pessé 7de152539d Fix order of search paths for nunjucks 2016-02-21 19:08:39 +01:00
Samy Pessé 1e486a16bd Update theme-default@1.0.0-pre.2 2016-02-21 18:48:50 +01:00
Samy Pessé 7f9c24eedb Fix test for file.mtime 2016-02-21 18:43:37 +01:00
Samy Pessé 8a3396deba Add releases notes to documentation 2016-02-21 18:38:27 +01:00
Samy Pessé 96d5b37196 Update 1.0.0-pre.1 of theme-default 2016-02-21 18:38:11 +01:00
Samy Pessé 7b2e332f6c Complete ebook command to output one file 2016-02-21 18:33:07 +01:00
Samy Pessé ab541c1653 Fix generation of pdf header/footer 2016-02-21 18:23:59 +01:00
Samy Pessé 5f058f2ceb Disable directoryIndex for ebook generation 2016-02-21 18:08:36 +01:00
Samy Pessé 360381dd9f Fix write of SUMMARY.html in ebook format 2016-02-21 17:48:06 +01:00
Samy Pessé cef4096b39 Add cli commands to build ebooks 2016-02-21 17:24:26 +01:00
Samy Pessé a9c96c1afa Fix resolve of relatives images in assets inliner 2016-02-21 17:23:07 +01:00
Samy Pessé a446deaff3 Complete generator for ebooks 2016-02-21 15:52:04 +01:00
Samy Pessé e5dd987d03 Add i18n filter fro themes 2016-02-21 13:29:17 +01:00
Samy Pessé 51fd8ae08c Simplify .next and .prev for articles 2016-02-21 12:05:31 +01:00
Samy Pessé 884540e565 Fix .next and .prev for summary's articles to use parts 2016-02-21 11:56:14 +01:00
Samy Pessé ca1313e891 Extend configuration with infos from readme 2016-02-21 11:28:55 +01:00
Samy Pessé 8df18746fa Add debug log when copying theme 2016-02-21 11:22:41 +01:00
Samy Pessé 40f829ce54 Add docs for setup gitbook 2016-02-21 11:01:49 +01:00
Samy Pessé e16b3e35f4 Setup summary for documentation 2016-02-21 01:02:38 +01:00
Samy Pessé 2f15e26ffa Fix context for templating and page 2016-02-21 01:02:20 +01:00
Samy Pessé b4cdbc6534 Add custom filters for dates to templating engine 2016-02-21 00:42:11 +01:00
Samy Pessé 0a93ffd76b Ignore node_modules during login 2016-02-21 00:33:10 +01:00
Samy Pessé 98e9848c4a Add title to summary's parts 2016-02-21 00:28:59 +01:00
Samy Pessé 42bb5fccb8 Change glossary to enforce use of h2 2016-02-20 17:39:11 +01:00
Samy Pessé fb921788b9 Fix page.toHTML by using .content directly 2016-02-20 17:35:10 +01:00
Samy Pessé 847c6b9aa2 Fix error in blocks detection with nunjucks 2016-02-20 17:32:32 +01:00
Samy Pessé cafbcd4097 Complete normalization of summary with level and multiples parts 2016-02-20 17:18:18 +01:00
Samy Pessé a22539a91e Add new gitbook-markdown and gitbook-asciidoc 2016-02-20 16:02:51 +01:00
Samy Pesse 89378c3883 Update graceful-fs@4 2016-02-18 20:32:11 +01:00
Samy Pesse f763e1dc42 Lint after travis tests 2016-02-18 19:19:09 +01:00
Samy Pesse ea13e3cec4 Change default theme repository 2016-02-18 19:06:23 +01:00
Samy Pessé 3d3302e547 Add detection of text direction and provide: 'page.dir' 2016-02-18 17:50:10 +01:00
Samy Pessé 95d81d02a1 Fix resolve of images 2016-02-18 17:03:37 +01:00
Samy Pessé 8401a674c3 Add test for navigation in summary 2016-02-18 16:34:11 +01:00
Samy Pessé 3fcf1a7723 Dont fail if summary doesn't exist 2016-02-18 15:23:15 +01:00
Samy Pessé 1a3ee78459 Accept external url in summary 2016-02-18 15:23:01 +01:00
Samy Pessé b99c499d2e Add back serve command 2016-02-18 15:08:34 +01:00
Samy Pessé 709b388dfc Fix path calcul to be coherant 2016-02-18 14:47:53 +01:00
Samy Pessé 6e83240233 Glossary should be output as a normal page 2016-02-18 13:58:10 +01:00
Samy Pessé 202c235c66 Add tests for path utils module 2016-02-18 12:15:53 +01:00
Samy Pessé 576d773fec Correctly map filenames for website output 2016-02-18 12:13:24 +01:00
Samy Pessé 58a930e456 Add "level" to TOCArticle 2016-02-18 11:50:33 +01:00
Samy Pessé 52206ce9d0 Add test for copy of assets in website generator 2016-02-18 10:53:57 +01:00
Samy Pessé 1de9d5683b Copy assets to output (website) 2016-02-18 10:45:50 +01:00
Samy Pessé b66242db98 Add filter resolveAsset to template for website 2016-02-18 10:04:23 +01:00
Samy Pesse 004ac88516 Add method .hook to plugins 2016-02-17 21:43:54 +01:00
Samy Pesse 3d1eac234a Move comment about substack/node-resolve#81 2016-02-17 21:35:25 +01:00
Samy Pesse a78e52812f Remove write operations from virtual fs 2016-02-17 21:29:25 +01:00
Samy Pesse 5993e6c791 Ignore headings for annotations 2016-02-17 21:25:53 +01:00
Samy Pesse 1ec8b7c324 Add glossary as a normal page 2016-02-17 21:25:08 +01:00
Samy Pesse e75002a96d Improve annotation with glossary terms 2016-02-17 21:03:00 +01:00
Samy Pesse a68364d4d7 Add test for location 2016-02-17 21:02:42 +01:00
Samy Pessé 2b5e836a33 Fix and improve tests for links in page 2016-02-17 17:38:39 +01:00
Samy Pessé 9caa9c39e5 Use _layouts folders as base for templates 2016-02-17 17:34:27 +01:00
Samy Pessé 096bdaba7a Fix #537: don't add index.html to links 2016-02-17 17:18:19 +01:00
Samy Pessé d22c1f57e5 Generate index.html instead of README.html 2016-02-17 17:04:23 +01:00
Samy Pessé dac00be7b5 Add some doc about theming 2016-02-17 16:51:21 +01:00
Samy Pessé 4e7cb9b23f Load template engine for website output using theme configuration 2016-02-17 16:20:45 +01:00
Samy Pessé 5fdee2cb5e Add file website output tests 2016-02-17 15:59:27 +01:00
Samy Pessé 1db3f3deab Don't fail if plugin is "empty" 2016-02-17 15:58:35 +01:00
Samy Pessé b2af55ac63 Wrap error when loading plugin 2016-02-17 15:53:37 +01:00
Samy Pessé 40cdc285b6 Don't build context in templating engine 2016-02-17 15:18:49 +01:00
Samy Pessé 46f017e68b Add type to file object in templating context 2016-02-17 15:08:26 +01:00
Samy Pessé 1769ac2c2d Don't output config in json format 2016-02-17 15:08:08 +01:00
Samy Pessé 067bdcda2d Add "config" to templating context 2016-02-17 15:07:56 +01:00
Samy Pessé 3bc1934966 Add faq in documentation 2016-02-17 15:07:19 +01:00
Samy Pessé 6ee9a3a64c Remove old theme 2016-02-17 14:07:15 +01:00
Samy Pessé c0196c97a5 Add context for summary 2016-02-17 13:59:52 +01:00
Samy Pessé 96105d6ba0 Extend templating context (and json output) 2016-02-17 13:39:20 +01:00
Samy Pessé 853ba6079c Correctly clean and ignore output folder 2016-02-17 13:30:45 +01:00
Samy Pessé b6104c64fe Use same json for page context and json builds 2016-02-17 13:12:34 +01:00
Samy Pessé e95678cf3a Add tests for installation of plugins 2016-02-17 12:55:46 +01:00
Samy Pessé e2c21051aa Add method install to plugins manager 2016-02-17 12:02:58 +01:00
Samy Pessé 7c575e1b43 Fix loading of plugins 2016-02-17 11:52:31 +01:00
Samy Pessé c89c253f29 Adapt ebook output 2016-02-17 11:26:36 +01:00
Samy Pessé f54685e216 Change format of conrefs and folder mixins 2016-02-17 11:25:57 +01:00
Samy Pessé 8141bcb3b6 Add command 'parse' for gitbook-cli 2016-02-17 10:11:33 +01:00
Samy Pesse db3d21db49 Start commands for plugins installation 2016-02-16 23:30:08 +01:00
Samy Pesse ca85c0ecf3 Add method to install plugin from npm
Add tests for it
2016-02-16 18:46:16 +01:00
Samy Pesse 702db46f20 Add base for plugin linking/installation 2016-02-16 15:53:12 +01:00
Samy Pesse 327d0bf5c5 Validate plugin after loading 2016-02-16 15:42:24 +01:00
Samy Pesse 2375296e67 Add base _setup for pluginslist 2016-02-15 22:39:26 +01:00
Samy Pesse b4fcd2da14 Plugins should be relative to output 2016-02-15 21:14:25 +01:00
Samy Pesse e3c92cce77 Add name to json and website build
And inherit from conrefsLoader
2016-02-15 16:24:13 +01:00
Samy Pessé 1141d34f07 Add tests for args in blocks 2016-02-15 14:19:30 +01:00
Samy Pessé 354fe12742 Fix addBlock for template engine
Add test for code block
2016-02-15 14:07:26 +01:00
Samy Pessé 1b19c66603 Complete page.previous and page.next variables 2016-02-15 09:55:12 +01:00
Samy Pessé d7077fc7db Add test for page.title variable 2016-02-15 09:44:05 +01:00
Samy Pessé d6bd4a0d67 Add test for file variables in templating 2016-02-14 23:05:37 +01:00
Samy Pessé 8628c87be4 Interpolate template before running it 2016-02-14 22:55:48 +01:00
Samy Pessé fef822145d Move conrefs to a separate mixin 2016-02-14 22:49:55 +01:00
Samy Pessé cfefa7d579 Add .next and .prev to TOCArticle 2016-02-14 19:27:58 +01:00
Samy Pessé def115fe0f Add base for templating documentation 2016-02-14 19:07:04 +01:00
Samy Pessé 01a7c6f4e0 Add help chapter about variables 2016-02-14 17:41:55 +01:00
Samy Pessé 0e86cdeb4a Add code blocks normalization 2016-02-14 15:26:15 +01:00
Samy Pessé a65f888a77 Start moving template and conrefs on Output 2016-02-14 11:10:08 +01:00
Samy Pessé 71059e3ea3 Ignore Summary and Langs in output 2016-02-13 15:51:14 +01:00
Samy Pessé ee3faaad11 Complete assets inliner 2016-02-13 15:28:07 +01:00
Samy Pessé d2aad34935 Improve performance of svg conversion 2016-02-13 15:04:18 +01:00
Samy Pesse d8ed34beba Add method to fetch remote image with AssetsInliner 2016-02-13 13:56:04 +01:00
Samy Pesse 3154d37e41 Add more test for svg 2016-02-13 10:49:56 +01:00
Samy Pesse 272f30af53 Complete test for convertion of svgs 2016-02-13 10:43:22 +01:00
Samy Pesse 4c6717e234 Add conversion of svg to png for assets inliner 2016-02-12 23:57:43 +01:00
Samy Pesse 39b6562d14 Add pipeline to outline svg as png 2016-02-12 21:59:49 +01:00
Samy Pesse 0d966fe197 Separate output in FolderOutput and base 2016-02-12 21:25:43 +01:00
Samy Pesse 82f94b010f Remove concept of generator, to merge it with Output 2016-02-12 20:48:51 +01:00
Samy Pesse 4555c541a8 Replace links to page of summary by html links 2016-02-12 19:20:32 +01:00
Samy Pesse a853a51a0b Complete test for heading IDs 2016-02-12 18:53:00 +01:00
Samy Pesse 756694c029 Page output a simple html string 2016-02-11 22:12:07 +01:00
Samy Pesse 669f3b3984 Add base for normalizing html 2016-02-11 21:44:38 +01:00
Samy Pesse e7eed2abbe Complete conrefs in parsing 2016-02-11 18:18:33 +01:00
Samy Pesse 98a13cf487 Add conrefs loader for nunjucks 2016-02-11 17:30:58 +01:00
Samy Pesse 7f9aa214a4 Cleaner module for managing git refs 2016-02-11 17:10:59 +01:00
Samy Pesse 347a536a4e Add git urls parsing and tests 2016-02-11 16:35:41 +01:00
Samy Pesse 5cf0abaf2b Add documentation for conrefs 2016-02-11 15:36:05 +01:00
Samy Pessé 09c6f025a1 For multilingual book, copy readme from main book 2016-02-11 14:01:52 +01:00
Samy Pessé f47208528b Normalize fs access 2016-02-11 13:58:26 +01:00
Samy Pessé 87d90a65ac Stat file when parsing page 2016-02-11 13:31:19 +01:00
Samy Pessé 02cff8c72c Add base for page parsing 2016-02-11 11:53:32 +01:00
Samy Pessé a67993ac0b Add assertion for should to test existence of file 2016-02-11 11:14:52 +01:00
Samy Pessé e540d25665 Normalize templating error 2016-02-11 10:08:36 +01:00
Samy Pessé 52c4dc49cf Normalize errors 2016-02-11 10:07:15 +01:00
Samy Pessé 44ad70320a Correctly setup folder when outputting 2016-02-11 09:43:36 +01:00
Samy Pessé 2b8e1c0b11 Add configuration for inner docs 2016-02-11 09:35:47 +01:00
Samy Pessé 85a2ce9065 Add base for inner documentation 2016-02-11 09:34:47 +01:00
Samy Pessé a24aa79dbf Add base for templating 2016-01-31 17:01:50 +01:00
Samy Pessé 633de85180 Improve plugin loading to elimate false-negative 2016-01-29 12:28:51 +01:00
Samy Pessé f32d03eb88 Add base for loading plugins 2016-01-29 12:21:57 +01:00
Samy Pessé e83d63c2aa Index page of summary when parsing 2016-01-28 23:42:00 +01:00
Samy Pessé ff30ba62ba Add order for tests 2016-01-28 23:23:56 +01:00
Samy Pessé ea98444dc0 Add parsing of summary and tests 2016-01-28 23:19:39 +01:00
Samy Pessé 328c3a7d51 Correctly create sub-book 2016-01-28 18:42:21 +01:00
Samy Pessé 4b465bedea Fix tests for languages parsing 2016-01-28 18:39:44 +01:00
Samy Pessé 461ef2c68e Add unit tests for langs 2016-01-28 17:35:32 +01:00
Samy Pessé 46efdacd6d Fix book.resolve 2016-01-28 16:29:09 +01:00
Samy Pessé a063cc1a53 Add base for langs parsing 2016-01-28 16:27:29 +01:00
Samy Pessé 36f2f5d52e Add method glossary.find 2016-01-27 22:51:07 +01:00
Samy Pessé ddc99104d4 Add unit tests for glossary parsing 2016-01-27 22:48:23 +01:00
Samy Pessé 8d277e9108 Add parsing of the glossary 2016-01-27 21:56:00 +01:00
Samy Pessé f305d57ab7 Add more classes structures 2016-01-27 10:24:06 +01:00
Samy Pessé 877f2e477b Start rewrite 2016-01-22 21:04:36 +01:00
Samy Pessé c8e2fc0e57 Fix typo in config_default.js 2016-01-21 16:15:14 +01:00
Aaron O'Mullan 4cb9cbb5ae Merge pull request #1097 from egasato/master
Slight changes in Catalan and Spanish translations.
2016-01-15 16:09:43 +01:00
Esaú García Sánchez-Torija 6f3be56223 Slightly changes in the Spanish translation.
I changed LANGS_CHOOSE, SEARCH_TOGGLE, SEARCH_PLACEHOLDER, SHARE_TOGGLE and SHARE_ON properties to be more appropiate (more informal).
2016-01-15 14:07:07 +01:00
Esaú García Sánchez-Torija c638c108d2 Translated font settings.
I translated to Catalan the Spanish font settings I used as template but I forgot to translate previously. I also changed LANGS_CHOOSE, SEARCH_TOGGLE, SEARCH_PLACEHOLDER, SHARE_TOGGLE and SHARE_ON properties to be more appropiate (more informal).
2016-01-15 14:04:58 +01:00
Samy Pessé d8f5aa680d Bump version to 2.6.7 2016-01-13 16:28:09 +01:00
Samy Pessé f2b585e446 Add @egasato as Catalan translator 2016-01-13 16:25:28 +01:00
Samy Pessé 78f91e0037 Merge pull request #1072 from egasato/patch-1
Catalan translation.
2016-01-13 16:24:33 +01:00
Samy Pessé 3f3c156697 Add @turankonan as Turkish translator 2016-01-13 16:24:22 +01:00
Samy Pessé 4627bf5d1f Merge pull request #1075 from turankonan/master
Turkish translation
2016-01-13 16:23:00 +01:00
Samy Pessé 93a144984a Merge pull request #1091 from gitname/gitname-patch-2
Fix typo
2016-01-13 16:22:16 +01:00
Samy Pessé 2d0784440c Fix support for encoded entities in filename 2016-01-13 16:21:52 +01:00
gitname 05a083437f Fix typo 2016-01-09 21:44:30 -08:00
gitname d4b5f59f92 Convert run-on sentence into two sentences 2016-01-09 21:43:49 -08:00
Turan Konan ff53fb6db0 Turkish translation 2016-01-03 22:55:49 +02:00
Esaú García Sánchez-Torija 534b3908cc Catalan translation. 2015-12-30 13:18:43 +01:00
Samy Pessé 7ea2369810 Merge pull request #1066 from hirofumi1987/master
Fixed Japanese translation
2015-12-21 08:40:29 +01:00
hirofumi_i 4d96ec10c1 Fixed Japanese translation 2015-12-21 12:39:19 +09:00
Samy Pesse a37ee3457a Bump version to 2.6.6 2015-12-16 21:02:49 +01:00
Samy Pesse 6969bb9a5c Fix include of css in pdf header/footer 2015-12-16 20:55:06 +01:00
Samy Pessé 4567041456 Bump version to 2.6.5 2015-12-11 14:48:13 +01:00
Samy Pessé 49f09e46da Fix support for local styles 2015-12-11 14:40:20 +01:00
Samy Pessé becd027563 Check style existence on output folder instead of source 2015-12-11 14:31:08 +01:00
Samy Pessé 6eb1605be6 Fix #1041 : fix glossary terms being replaced in script (ex: math) 2015-12-08 15:27:11 +01:00
Samy Pessé 5c16aec096 Use gitbook-markdown-css@1.0.1 2015-12-04 15:43:51 +01:00
Samy Pessé 835e2dc1fb Bump version to 2.6.4 2015-12-02 13:29:04 +01:00
Samy Pessé e2378ab29a Update gitbook-parsers@0.8.9 2015-12-02 13:25:13 +01:00
Samy Pesse 0f1d7eb391 Bump version to 2.6.3 2015-12-02 10:12:49 +01:00
Samy Pesse dd358b8b95 Update gitbook-parsers@0.8.8 2015-12-02 10:11:06 +01:00
Samy Pessé 21cf5fcaf4 Bump version to 2.6.2 2015-11-25 11:56:29 +01:00
Samy Pessé 8c7509759b Update nunjucks@2.2.0 2015-11-25 11:54:19 +01:00
Samy Pessé dc9ac0d0ff Compile js 2015-11-25 11:52:50 +01:00
Samy Pessé 93b401ca9f Add trailing slash to gitbook.state.root, fix value of gitbook.state.bookRoot 2015-11-25 11:49:55 +01:00
Samy Pessé b137d8270a Bump version to 2.6.1 2015-11-25 11:02:15 +01:00
Samy Pessé 6db7757451 Fix gitbook.state.innerLanguage: use camel case 2015-11-25 11:01:17 +01:00
Samy Pessé 43fd42b757 Bump version to 2.6.0 2015-11-25 10:54:09 +01:00
Samy Pessé 5d1c4d2b9f Fix #926: use zh-hans instead of zh-cn and ja instead of jp 2015-11-25 10:52:36 +01:00
Samy Pessé 425acd8bf6 Follow github style: change color of h6 headings 2015-11-25 10:42:36 +01:00
Samy Pessé 414160e0df Merge pull request #1027 from GitbookIO/revert-1020-remove-font-smooth
Revert "Fix small font rendering issue on Macs"
2015-11-25 10:32:28 +01:00
Samy Pessé 117c6aefe8 Revert "Fix small font rendering issue on Macs" 2015-11-25 10:32:17 +01:00
Samy Pessé 13d584d39a Merge pull request #1020 from dylang/remove-font-smooth
Fix small font rendering issue on Macs
2015-11-25 10:28:23 +01:00
Samy Pessé 9bc89c24f5 Fix #1023: close sidebar after clicking a link on mobile 2015-11-25 10:25:58 +01:00
Samy Pessé 5a8c4d5a4e Cleanup lib/generators/json.js 2015-11-25 10:14:34 +01:00
Samy Pessé 98da83a552 Fix urijs dependency on linux 2015-11-25 10:08:24 +01:00
Samy Pessé 5344a30a3b Generate css 2015-11-25 10:05:16 +01:00
Samy Pessé d5d6b3673e Add bookRoot to gitbook.state 2015-11-25 10:05:05 +01:00
Samy Pessé d2a2fe88d1 Update urijs@1.17.0 and tiny-lr 2015-11-25 10:04:44 +01:00
Samy Pesse ced44c86ce Fix #1022: fix bottom margin for lists 2015-11-24 23:38:26 +01:00
Samy Pessé ee402ad444 Merge pull request #1018 from atilacamurca/patch-1
Update README.md
2015-11-19 12:24:42 +01:00
Dylan Greene 3d2155eb66 Make fonts nicer on Macs
Removed the `antialias` setting which tells Chrome to not use native font rendering and instead use something from the late 2010's that isn't subpixel-friendly and looks very blocky. This used to be required when OS X browsers didn't antialias by default because it made fonts look bolder than on Windows. This has since been fixed and we are advised to not use `-webkit-font-smooth`.

https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth
2015-11-17 16:15:33 -05:00
Samy Pessé bd24b03548 Add @buren to AUTHORS 2015-11-16 22:04:41 +01:00
Samy Pessé 5cb55a0f37 Merge pull request #1019 from buren/sv-locale
Add Swedish translation
2015-11-16 22:02:49 +01:00
Jacob Burenstam 163242f80f Add Swedish translation 2015-11-16 22:00:16 +01:00
Átila Camurça Alves 266bfcb8bf Update README.md
There is an extra space in the command line example that enable debug mode.
2015-11-16 16:45:33 -03:00
Samy Pessé d82fa02669 Update plugin-search@1.1.0 2015-11-16 13:09:05 +01:00
Samy Pessé 3a5207a0d2 Merge pull request #1016 from GitbookIO/fix/999
Fix #999: detection of structure should be case incensitive
2015-11-16 10:39:29 +01:00
Samy Pessé e38f3bb884 Improve book.findFile to be case incensitive 2015-11-16 10:31:24 +01:00
Samy Pessé 751cdd9b3b Add test for #999 2015-11-16 10:30:10 +01:00
Samy Pessé 8df6bdca89 Update node version for travis and appveyor tests 2015-11-16 10:18:52 +01:00
Samy Pessé f9df7545ad Merge pull request #1014 from GitbookIO/fix/1013
Fix #1013: prioritize structure defined in book.json
2015-11-16 10:16:52 +01:00
Samy Pessé 9b7a90afef Test first extension of structure itself in book.findFile 2015-11-16 10:06:31 +01:00
Samy Pessé 2ae83b3247 Add failing test for #1013 2015-11-16 09:55:45 +01:00
Samy Pessé 5d907f234e Merge pull request #1005 from mjanda/master
Czech translation
2015-11-07 21:56:28 +01:00
Marek Janda 3a005c4f13 Czech translation 2015-11-07 21:51:27 +01:00
Marek Janda 6c2f50470a Czech translation 2015-11-07 21:00:45 +01:00
Samy Pessé d233783942 Fix bottom margin of blockquote 2015-11-05 11:33:21 +01:00
Samy Pessé 3d9e4c80a2 Bump version to 2.5.2 2015-11-03 09:32:35 +01:00
Samy Pessé a7f49015c1 Fix custom styles for ebook 2015-11-03 09:25:51 +01:00
Samy Pessé 68ed2631dc Correctly show space between toolbar icon and text in buttons 2015-11-02 17:16:43 +01:00
Samy Pessé 2814fea67e Trigger "start" before "page.change" 2015-11-02 16:57:08 +01:00
Samy Pessé 3388be9db6 Update app.js 2015-10-27 23:11:55 +01:00
Samy Pessé 9b89319820 Bump version to 2.5.1 2015-10-27 23:11:31 +01:00
Samy Pessé ad34089df5 Merge changelog for 2.5.0 2015-10-27 23:10:29 +01:00
Samy Pessé 7a4c6bc326 Fix calcul of root in gitbook.state when serving index.html as / 2015-10-27 18:44:04 +01:00
Samy Pessé 6ab386ae35 Bump version to 2.5.0 2015-10-27 13:25:52 +01:00
Samy Pessé 0abbfde912 Add chapterTitle to app build 2015-10-27 12:19:54 +01:00
Samy Pessé 0521defb63 Add 'chapterTitle' to gitbook.state api 2015-10-27 12:18:04 +01:00
Samy Pessé ea4d96610f Compatibility for require of plugins 2015-10-24 21:36:17 +02:00
Samy Pessé 4bc56564b4 Comment gitbook.state api 2015-10-22 16:12:21 +02:00
Samy Pessé 013f7f09da Add gitbook.state.filepath
Fix gitbook.state.root
2015-10-22 16:11:05 +02:00
Samy Pessé f082de1f92 Bump version to 2.5.0-beta.7 2015-10-22 13:52:19 +02:00
Samy Pessé ad39dc8c0c Update app.js 2015-10-22 13:50:05 +02:00
Samy Pessé 481a76319f Provide gitbook.state.root to plugins 2015-10-22 13:49:28 +02:00
Samy Pessé 27a43d5aea Merge pull request #986 from GitbookIO/fix/heading_ids
Normalize ID for headings
2015-10-21 18:05:40 +02:00
Samy Pessé df1d5a0680 Correctly generate id if none found 2015-10-21 17:58:06 +02:00
Samy Pessé 722109faf0 Update gitbook-parsers@0.8.7 2015-10-21 16:22:47 +02:00
Samy Pessé d4dca7736a Update gitbook-parsers@0.8.6 2015-10-21 16:15:56 +02:00
Samy Pessé 4e90becd52 Use Arial as default font 2015-10-21 15:54:45 +02:00
Samy Pessé 26890e94eb Bump version to 2.5.0-beta.6 2015-10-20 18:20:44 +02:00
Samy Pessé 55c83f9a59 Use helvetica by default for pdf 2015-10-20 18:09:51 +02:00
Samy Pessé b837d82878 Fix default style for pdf footer and header 2015-10-20 18:02:23 +02:00
Samy Pessé cbdcdb1e0f Fix #974: correctly handle query in image urls 2015-10-20 17:22:01 +02:00
Samy Pessé 4fea85289e Merge pull request #983 from GitbookIO/fix/982
Fix #982: correctly handle templating in imported content
2015-10-20 17:09:15 +02:00
Samy Pessé ba5f9132c9 Fix #982: fix shortcuts for included templates 2015-10-20 17:08:44 +02:00
Samy Pessé 991681daa2 Add failing test for #982 2015-10-20 16:38:48 +02:00
Samy Pessé 2faf53e16b Bump version to 2.5.0-beta.5 2015-10-16 13:48:27 +02:00
Samy Pessé 5430ed99de Update gitbook-parsers@0.8.5 2015-10-16 13:47:09 +02:00
Samy Pessé fef4dfd05e Fix position of sidebar toggle button 2015-10-14 13:35:03 +02:00
Samy Pessé 05943db3b5 Bump version to 2.5.0-beta.4 2015-10-14 13:16:49 +02:00
Samy Pessé 682fabd1ef Fix position of glossary icon relative to sidebar toggler 2015-10-14 13:15:36 +02:00
Samy Pessé ee8ccc6d7e Fix legacy properties book.options.input, ... 2015-10-14 12:31:37 +02:00
Samy Pessé 8ee0bcac2a Bump version to 2.5.0-beta.3 2015-10-14 11:54:58 +02:00
Samy Pessé 0c4ad74788 Fix resolve of plugins for prereleases 2015-10-14 11:54:12 +02:00
Samy Pessé 7d944e4f1f Fix instruction for local developement 2015-10-14 11:48:27 +02:00
Samy Pessé 67b2394c16 Bump version to 2.5.0-beta.2 2015-10-14 11:39:23 +02:00
Samy Pessé 269d08a35f Correctly handle pre-version for plugins checks 2015-10-13 15:50:54 +02:00
Samy Pessé f626e83e48 Bump version to 2.5.0-beta.1 2015-10-13 15:21:20 +02:00
Samy Pessé 8ba18cd587 Merge pull request #979 from GitbookIO/feature/plugins_config
Improvements for plugin configurations
2015-10-13 15:14:26 +02:00
Samy Pessé 54c12fea89 Set default config for all plugins 2015-10-13 15:05:46 +02:00
Samy Pessé afb5ce71ce Update gitbook-plugin-sharing@1.0.1 2015-10-13 14:56:59 +02:00
Samy Pessé 6fef6acf10 Correctly apply defaults config to pluginsConfig 2015-10-13 14:55:39 +02:00
Samy Pessé a27411401b Update gitbook-plugin-fontsettings@1.0.2 2015-10-13 14:48:09 +02:00
Samy Pessé 3718fc319b Fix error in accessing plugins config 2015-10-13 14:47:33 +02:00
Samy Pessé c6c9463f8c Update gitbook-plugin-search@1.0.2 2015-10-13 14:38:54 +02:00
Samy Pessé b410685318 Update gitbook-plugin-search@1.0.1 2015-10-13 14:34:29 +02:00
Samy Pessé b742b29259 Add tests for plugins config validation 2015-10-13 14:31:11 +02:00
Samy Pessé df5d27ab61 Use jsonschema to valid and default plugins config 2015-10-13 13:56:46 +02:00
Samy Pessé 2870155c0b Fix js error 2015-10-12 10:45:13 +02:00
Samy Pessé 9ba1075f48 Add hook "config" to transform configuration before generation 2015-10-12 10:43:14 +02:00
Samy Pessé 4ae5b2e050 Merge pull request #959 from GitbookIO/improvements/ebooks
Improvements for ebooks
2015-10-08 20:58:57 +02:00
Samy Pessé 4369bd8f5e Fix copy of assets and js path in gulpfile 2015-10-06 14:23:10 +02:00
Samy Pessé 321b24a7b9 Don't copy assets for ebook to website bundle 2015-10-06 14:21:02 +02:00
Samy Pessé 22e0c1fb54 Fix css being used for pdf footer and header 2015-10-06 13:35:04 +02:00
Samy Pessé ba65e3c020 Adapt tests 2015-10-06 13:26:32 +02:00
Samy Pessé c19ab952e3 Only add page count on pdf/epub 2015-10-06 13:20:20 +02:00
Samy Pessé ecc29087b5 Fix summary page counter for epub low resolution 2015-10-06 13:10:51 +02:00
Samy Pessé 87e056de64 Change markdown -> markup in less mixins 2015-10-06 13:05:32 +02:00
Samy Pessé 761200529f Adapt glossary and summary for pdf/epub to new markup style 2015-10-06 13:03:52 +02:00
Samy Pessé 770351916e Cleaner markup css 2015-10-06 12:45:25 +02:00
Samy Pessé 4b7d957b47 Use black links in mobi files 2015-10-06 10:38:09 +02:00
Samy Pessé a1c03c18a5 Improve support of glossary page in pdf 2015-10-06 10:00:49 +02:00
Samy Pesse 5d376b054f Handle correctly rtl for toc in ebooks 2015-10-06 09:47:41 +02:00
Samy Pesse 277d13c2bb Center title for table of content 2015-10-06 09:47:25 +02:00
Samy Pesse 4a9389d80a Improve display of table of contents for ebooks 2015-10-06 09:47:15 +02:00
Samy Pesse 33593c13ae Inline css for footer/header templates 2015-10-06 09:47:04 +02:00
Samy Pesse eef82c18c2 Remove bottom border on h1 and h2 2015-10-06 09:45:31 +02:00
Samy Pessé 7363580095 Fix glossary page using a "section" instead of a "div" 2015-10-06 09:45:22 +02:00
Samy Pessé 23a46b0597 Remove margin on first header of a page (ebook)
Avoid breaking in code blocks
2015-10-06 09:45:06 +02:00
Samy Pessé 51c79f294c Add css to footer/header for pdf 2015-10-06 09:44:54 +02:00
Samy Pessé ce1e0e1873 Merge pull request #964 from GitbookIO/features/plugin_api
Better APIs for Plugins
2015-10-06 09:42:49 +02:00
Samy Pessé c2775b3b63 Export jQuery for plugins compatibility 2015-10-06 09:37:01 +02:00
Samy Pessé bcb224d1cb Add more node.js versions to travis-ci 2015-10-05 23:06:46 +02:00
Samy Pessé 8bc5f22866 Add search plugin to dependencies 2015-10-05 17:22:47 +02:00
Samy Pessé c3f2ef02c4 Adapt tests for new default plugins 2015-10-05 17:16:37 +02:00
Samy Pessé 08e2c90d9d Don't fail when can't write to localstorage 2015-10-05 17:11:55 +02:00
Samy Pessé d2bb2ba454 Remove style for search 2015-10-05 17:07:25 +02:00
Samy Pessé ba912318cd Tweak some details for browserify compatibility 2015-10-05 16:49:37 +02:00
Samy Pessé 3d1f057373 Switch to gulp/browserify 2015-10-05 16:47:19 +02:00
Samy Pessé 0679807517 Define specific action for toggling summary 2015-10-05 16:02:03 +02:00
Samy Pessé 7f0e4803e2 Start removing search and lunr from core 2015-10-05 15:55:39 +02:00
Samy Pessé fa76029a17 Adapt tests for new default plugins 2015-10-05 14:24:55 +02:00
Samy Pessé 376c68957f Remove sharing 2015-10-05 13:53:19 +02:00
Samy Pessé 222ec8d4b9 Correctly reset buttons when page changed 2015-10-05 12:13:54 +02:00
Samy Pessé 90715c1944 Remove fontsettings from core and add plugin as default 2015-10-05 12:07:19 +02:00
Samy Pessé 801e1b6059 Add api to extend toolbar 2015-10-05 12:07:02 +02:00
Samy Pessé 14bb659b75 Update lodash for client side code 2015-10-05 10:43:21 +02:00
Samy Pessé eab3c50288 Add sharing plugin as default 2015-10-05 10:32:43 +02:00
Samy Pessé 74396e7240 Add method book.formatString 2015-10-05 10:07:04 +02:00
Samy Pessé 6c2539e886 Move Book.init in another file 2015-10-05 09:54:40 +02:00
Samy Pessé aba25d8521 Add eslint instead of jshint 2015-10-05 09:54:28 +02:00
Samy Pessé f0c97756de Bump version to 2.4.3 2015-10-01 14:07:32 +02:00
Samy Pessé f14c57d4c2 Merge pull request #955 from mstade/patch-1
Change nunjucks dependency to v2.1.0
2015-10-01 12:03:21 +02:00
Marcus Stade b6f60cc8ad Change nunjucks dependency to v2.1.0
Looks like mozilla/nunjucks#504 was merged and released in v2.1.0, so this changes `package.json` to no longer depend on a specific commit. Incidentally, this also solves a problem where corporate firewalls blocks npm from pulling in straight from github repos.
2015-10-01 12:01:52 +02:00
Samy Pessé 170516d343 Add ukranian translation 2015-09-28 21:01:28 +02:00
Samy Pessé c931e91bef Fix #952: add configuration for index maximum size 2015-09-28 20:54:45 +02:00
Samy Pessé db9151ae36 Update gitbook-parsers@0.8.3 2015-09-28 20:40:02 +02:00
Samy Pessé f2d86b6d69 Add slack button in readme 2015-09-23 12:19:04 +02:00
Samy Pessé 534cdd091b Add link to slack community channel 2015-09-23 12:16:22 +02:00
Samy Pessé fdf4a48638 Bump version to 2.4.2 2015-09-22 23:30:42 +02:00
Samy Pessé 58a3c5634e Improve installation of plugins to not install default ones 2015-09-22 23:25:15 +02:00
Samy Pessé f0ddb6e89f Merge branch 'fix/inline_code_html' 2015-09-22 22:46:19 +02:00
Samy Pessé 2b408db7cb Update gitbook-plugin-highlight@1.0.3 2015-09-22 22:45:55 +02:00
Samy Pessé 4e4bd23e2b Handle html param from code block output 2015-09-22 22:41:13 +02:00
Samy Pessé 62d0eb606e Add test for inline code block with html tags 2015-09-22 22:36:35 +02:00
Samy Pessé 0e9beeae14 Fix #941: limit size of lunr index 2015-09-22 12:36:18 +02:00
Samy Pessé 5e4dbdee24 Disable auto code highlighting (language should be specified) 2015-09-21 16:19:42 +02:00
Samy Pessé 9435dae6cd Fix #939: don't check gitbook version for sub-books (checked for parent) 2015-09-21 09:41:29 +02:00
Samy Pessé 813210bf47 Throw correct error in configuration 2015-09-20 23:27:39 +02:00
Samy Pessé c372dfc544 Bump version to 2.4.1 2015-09-19 00:32:43 +02:00
Samy Pessé ac77200683 Fix disabling a default plugin 2015-09-19 00:31:32 +02:00
Samy Pessé f5afbc90a4 Add more tests for blocks args/kwargs 2015-09-17 11:21:55 +02:00
Samy Pessé b24760c819 Bump version to 2.4.0 2015-09-15 14:32:11 +02:00
Samy Pessé 6732957e42 Merge pull request #930 from GitbookIO/jshint
Add config for jshint and fix lint errors
2015-09-15 14:21:27 +02:00
Samy Pessé 1fd0006859 Lint all tests 2015-09-15 14:20:32 +02:00
Samy Pessé 5a205346e3 Jshint all files 2015-09-15 13:57:21 +02:00
Samy Pessé e193004659 Fix passing context to block functions
Add test for it
2015-09-15 13:36:02 +02:00
Samy Pessé fe3a9c33d0 Improve code style for book.js and index.js 2015-09-15 13:16:26 +02:00
Samy Pessé d83116b88f Add jshint configuration 2015-09-15 13:16:06 +02:00
Samy Pessé 5f56098ae7 Fix stupid error that passed tests because "context" was global 2015-09-15 12:38:13 +02:00
Samy Pessé 0f935f4372 Merge pull request #806 from aschempp/aria-roles
Aria roles for accessibility
2015-09-15 12:29:12 +02:00
Samy Pessé df5c5a8c01 Merge pull request #919 from gaearon/fix-cmd-click
Don't react when user wants to open a link in a new tab
2015-09-15 12:28:32 +02:00
Samy Pessé 57a0c3bad8 Merge pull request #929 from GitbookIO/feature/improve_resolve
Improve paths resolving for conrefs
2015-09-15 12:27:07 +02:00
Samy Pessé 2a52326a45 Improve conrefs to handle all absolute file paths correctly
Add test for it
2015-09-15 12:22:54 +02:00
Samy Pessé 87e4ee1eeb Handle absolute file correctly for conrefs
Add test for absolute file for conrefs
2015-09-15 11:48:18 +02:00
Samy Pessé 45833eea9a Add test for navigation
Update mocha and should
2015-09-15 11:31:50 +02:00
Samy Pessé baf10e9b15 Improve book.resolve to ensure file is in the book
Adapt tests to plugin-highlight
2015-09-15 11:09:08 +02:00
Samy Pessé 463a947df1 Change text for editor 2015-09-15 09:47:34 +02:00
Samy Pessé cceebb4fd9 Merge branch 'improve/template-blocks' 2015-09-15 09:37:43 +02:00
Samy Pessé afd5465a61 Merge pull request #928 from GitbookIO/feature/highlight_block
Code highlighting extended by plugins
2015-09-14 18:26:26 +02:00
Samy Pesse fe604733de Change name of highlight test plugin 2015-09-14 12:05:51 +02:00
Samy Pesse da22f9f39f Update css without highlight.js
Add highlight as default plugin to be loaded
2015-09-14 11:57:54 +02:00
Samy Pesse 284ebbf75d Add highlight as default plugin 2015-09-14 11:47:56 +02:00
Samy Pesse 2c08ccad87 Pass language as kwargs to code block
Improve tests for extending code highlighting
2015-09-14 11:41:01 +02:00
Samy Pesse fa4e234bab Add base test for extending code highlighting 2015-09-14 11:28:14 +02:00
Samy Pesse 35c4179ca1 Use block code for highlight pre/code
Cleanup correctly predefined blocks
2015-09-14 11:21:16 +02:00
Dan Abramov c14ba7ce34 Don't react when user wants to open a link in a new tab
Fixes #846
2015-09-12 21:31:40 +03:00
Samy Pesse 601ce3add3 Add default blocks (html and code) 2015-09-12 19:25:01 +02:00
Samy Pesse 08ff39fd0b Remove highlight.js dependency 2015-09-12 19:23:07 +02:00
Samy Pesse 82a6ee3875 Add test for replacing highlighting 2015-09-12 18:21:35 +02:00
Samy Pessé 3bf592f870 Bump version to 2.3.3 2015-09-10 11:26:15 +02:00
Samy Pessé 241e205717 Merge pull request #912 from GitbookIO/fix/538
Fix 538: duplicate entries without paths are ignored
2015-09-10 09:59:45 +02:00
Samy Pessé fb2720ea8d Update gitbook-parsers@0.8.2 2015-09-10 09:57:04 +02:00
Samy Pessé 14853befda Add test for init with deep summary 2015-09-10 09:56:18 +02:00
Samy Pessé e7f2803d11 Bump version to 2.3.2 2015-09-09 09:30:53 +02:00
Samy Pessé 320015dd8f Fix #910: fix stupid error with semver api 2015-09-09 09:27:08 +02:00
Samy Pessé 471c124a98 Merge pull request #908 from GitbookIO/fix/asciidoc_blocks
Fix blocks in asciidoc
2015-09-09 00:01:43 +02:00
Samy Pesse aa44a109c6 Use position indicator that doesn't conflict with asciidoc 2015-09-08 23:57:40 +02:00
Samy Pesse 41e5ca8422 Add test for blocks without parsing 2015-09-08 23:55:30 +02:00
Samy Pessé 53af8b2bb6 Bump version to 2.3.1 2015-09-08 16:33:22 +02:00
Samy Pessé bd885b135f Merge pull request #904 from kuaipao/fix-mobi-font-color
use black font on mobi
2015-09-08 09:16:43 +02:00
kuaipao 62a6dde81a use black font on mobi 2015-09-08 04:02:48 +08:00
Samy Pesse 14b72b344f Log modified file in watcher 2015-09-06 21:13:18 +02:00
Samy Pesse ac03668063 Update chokidar@1.0.5 2015-09-06 21:11:49 +02:00
Samy Pesse 2512e176c9 Fix #893: korean iso code is "ko" not "kr" 2015-09-06 21:01:39 +02:00
Samy Pesse b613393866 Update highlight.js@8.8.0 2015-09-06 19:04:09 +02:00
Samy Pessé 607a6e95de Update gitbook-parsers@0.8.1 2015-09-05 19:00:42 +02:00
Samy Pessé 871f574ff7 Fix #761: fix syntax highlighting for asciidoc 2015-09-05 17:28:01 +02:00
Samy Pessé 377e470b15 Add warning for file outside spine 2015-09-04 19:12:27 +02:00
Samy Pessé e0a3f0cea5 Add warning for too strict gitbook version 2015-09-04 18:58:16 +02:00
Samy Pessé 66727b2736 Update gitbook-parsers@0.8.0 2015-09-04 18:33:45 +02:00
Samy Pessé 8215ad977f Merge pull request #898 from deminoth/master
Korean translation fixed
2015-09-04 08:36:19 +02:00
SangYeob Bono Yu a611dffbdf Add my name 2015-09-04 10:29:59 +09:00
SangYeob Bono Yu 39f378d8cf Korean translation fixed 2015-09-04 10:22:24 +09:00
Samy Pessé f00da58153 Update appveyor button 2015-09-01 17:52:27 +02:00
Samy Pessé 09b038b16d Bump version to 2.3.0 2015-09-01 17:44:53 +02:00
Samy Pessé cf601d97ad Improve error handling for failed image download 2015-09-01 17:38:33 +02:00
Samy Pessé 80edad53d4 Update nunjucks to fix raw and loader 2015-09-01 17:25:43 +02:00
Samy Pessé a972b32769 Update nunjucks@2.0.0 2015-08-28 08:45:28 +02:00
Samy Pessé efcaae3e60 Add author for hebrew 2015-08-27 19:07:31 +02:00
Samy Pessé e0ee591638 Merge pull request #877 from a-moses/hebrew
hebrew support theme
2015-08-27 19:06:26 +02:00
Samy Pessé 310a6d909f Add method 'get' to config object (helper for plugins) 2015-08-27 15:26:12 +02:00
Samy Pessé cefd8fc50f Don't fail if hook returns nothing for "page" and "page:before" 2015-08-27 15:04:28 +02:00
Samy Pessé a4422593f2 Add back page:before and page as non-deprecated 2015-08-26 11:16:02 +02:00
Samy Pessé e2c5d22756 Merge pull request #844 from xcv58/master
Fix #843 ignore _book in watch.js
2015-08-26 11:05:43 +02:00
Samy Pessé 84385d9dc3 Merge pull request #881 from mortonfox/patch-1
Fix Plugins link.
2015-08-26 11:01:28 +02:00
Morton Fox 6cfa4c8ab7 Fix Plugins link. 2015-08-25 23:35:15 -04:00
a-moses c76ccc53e1 Update he.json 2015-08-23 09:59:14 +03:00
a-moses d48eafb1a2 hebrew support theme
full Hebrew support for GITBOOK (with rtl )

* Sans and Serif may still in original name fonts
2015-08-23 09:53:25 +03:00
Aaron O'Mullan 302d9b4b91 Merge pull request #849 from GitbookIO/improve/remove-webfonts
Use system fonts instead of webfonts
2015-08-13 19:19:35 +02:00
Samy Pessé a091a7f68b Update gitbook-parsers@0.7.7 2015-08-09 15:45:04 +02:00
Aaron O'Mullan 53621f6de3 Use system fonts instead of webfonts 2015-08-08 17:35:05 +02:00
Samy Pessé 288b965db3 Merge pull request #847 from GitbookIO/fix/flicker
Improve header merge on page change
2015-08-07 16:55:42 +02:00
Aaron O'Mullan 578c9dcfc6 Improve header merge on page change
Prevents flickering (style reset)

Fixes #782, #838, #840
2015-08-07 16:46:23 +02:00
xcv58 64de17b248 ignore _book in watch.js 2015-08-04 00:50:31 -04:00
Aaron O'Mullan d699dff872 Use Book.resolve when possible
For added consistency
2015-07-31 15:08:56 +02:00
Samy Pesse 501843d624 Bump version to 2.2.0 2015-07-28 15:28:38 -07:00
Samy Pesse 508ce4283e Fix #819: codes must always be ltr 2015-07-28 15:25:12 -07:00
Samy Pessé 4aa8e66549 Merge pull request #813 from MrMaksimize/pdf-options
Allowing for custom chapter-mark and page-break in PDF.
2015-07-01 18:00:31 -04:00
Maksim Pecherskiy 917a6f70d8 Allowing for custom chapter-mark and page-break in PDF. 2015-06-30 19:48:51 -07:00
Samy Pesse 2f5e53da55 Update highlight.js@8.6.0 2015-06-29 10:02:35 -04:00
Samy Pesse c3cdefc90a Simpler template for summary 2015-06-29 09:58:23 -04:00
Samy Pesse 9c580e4989 Fix #802: make book.json accessible as "config." in templating 2015-06-19 16:28:46 +02:00
Andreas Schempp dbc75f7352 Add role and html5 markup for the main navigation 2015-06-18 20:29:11 +02:00
Andreas Schempp db841a8578 Added basic ARIA roles for screenreaders 2015-06-18 20:23:12 +02:00
Samy Pessé 50c902c4e4 Merge pull request #805 from GitbookIO/fix/804
Fix #804
2015-06-18 11:16:32 +02:00
Samy Pesse 84b6e0bde6 Add test for kwargs 2015-06-18 11:15:44 +02:00
Samy Pesse abc29c3fba Fix #804: correctly extract kwargs from blocks 2015-06-18 11:11:47 +02:00
Samy Pesse 8356c534f5 Add failing tests for block's arguments 2015-06-18 11:09:02 +02:00
Samy Pessé 78ff2687b4 Merge pull request #797 from nghong/vi-locale
Adding Vietnamese locale support
2015-06-13 11:15:00 +02:00
Hong Nguyen 9b6586fb36 Add translator name to AUTHORS.md 2015-06-13 16:13:34 +07:00
Hong Nguyen ea133219d0 Minor fix 2015-06-13 16:08:21 +07:00
Hong Nguyen c9b5d81a3c Add Vietnamese locale support 2015-06-13 15:42:49 +07:00
Samy Pessé d895c63211 Bump version to 2.1.0 2015-06-02 14:52:11 +02:00
Samy Pessé 8c86da67ca Update gitbook-parsers@0.7.6 2015-06-02 14:47:21 +02:00
Samy Pessé a9a230dfc3 Merge pull request #781 from GitbookIO/fix/775
Fix #775: add optional print.css style
2015-06-02 11:00:22 +02:00
Samy Pessé 6d53e52771 Handle empty string for styles configuration 2015-06-02 11:00:15 +02:00
Samy Pessé 52e10b7cfe Remove default print.css when styles/print.css is present 2015-06-02 10:23:31 +02:00
Samy Pessé addac85696 Add test for custom print style 2015-06-02 10:18:44 +02:00
Samy Pessé 13fb949d68 Merge pull request #774 from wilhelmmatilainen/patch-1
Styling should go to <head>, not to <body>
2015-05-30 18:11:15 +02:00
Wilhelm f1b593cfbd Styling should go to <head>, not to <body>
https://developers.google.com/speed/pagespeed/module/filter-css-to-head
2015-05-29 15:42:40 +03:00
Samy Pesse f998e2dec9 Bump version to 2.0.4 2015-05-28 18:07:20 +02:00
Samy Pesse 2c0bd53a91 Fix i18n used in multilingual book 2015-05-28 17:06:09 +02:00
Samy Pesse 6dd7f6162f Add title to languages chooser
Related to #757
2015-05-28 16:14:03 +02:00
Samy Pesse 475b0bb2b3 Adapt to nunjucks 1.3.x 2015-05-28 15:59:14 +02:00
Samy Pesse e6343935e3 Update nunjucks to fix raw tags 2015-05-28 15:50:46 +02:00
Samy Pessé 946883fd4c Merge pull request #772 from GitbookIO/feature/glossary_order
Fix #768: sort glossary, start with longest matchs
2015-05-28 15:21:03 +02:00
Samy Pessé b1b7e3148b Merge pull request #743 from chudaol/master
Added vk sharing button.
2015-05-28 14:54:03 +02:00
Samy Pesse 32203f6438 Sort glossary before applying it on pages 2015-05-28 14:49:53 +02:00
Samy Pesse f2d3c5d2ed Add test for #768 2015-05-28 14:38:21 +02:00
Samy Pessé 7e2f0ed4bc Merge pull request #758 from aschempp/hotfix/x-ua-compatible
Fix the X-UA-Compatible meta tag
2015-05-28 14:18:19 +02:00
Samy Pessé a877acf905 Merge pull request #759 from aschempp/hotfix/stylesheets
Move style sheets to the <head> section
2015-05-28 14:17:39 +02:00
Samy Pesse ac756ddf7e Bump version to 2.0.3 2015-05-27 21:11:58 +02:00
Samy Pesse 36e2236e6b Fix #765: in init handle correctly empty entries
Add tests for it, fix #769
2015-05-27 21:05:36 +02:00
Samy Pesse 72df665520 Update gitbook-parsers@0.7.5 2015-05-27 19:11:50 +02:00
Samy Pessé 07785528a5 Merge pull request #767 from wilhelmmatilainen/patch-1
Don't create panic by telling about false overwrite
2015-05-27 13:17:05 +02:00
Wilhelm bb579dd581 Don't create panic by telling about false overwrite 2015-05-27 14:13:02 +03:00
Samy Pessé a7d3064340 Change license to valid SPDX code 2015-05-26 16:10:11 +02:00
Andreas Schempp 1a60778248 Move style sheets to the <head> section
see https://github.com/GitbookIO/gitbook/issues/756
2015-05-23 09:14:26 +02:00
Andreas Schempp cda4bb5bda Fix the X-UA-Compatible meta tag
see https://github.com/GitbookIO/gitbook/issues/755
2015-05-23 09:06:58 +02:00
Olga Filipova 7543781046 Added vk sharing button. 2015-05-12 22:30:09 +02:00
Samy Pessé 82f3ffad06 Merge pull request #730 from creynders/patch-1
Fix typo in warning in `lib/plugin`
2015-05-04 14:47:56 +02:00
creynders dc4d2a1731 Fix typo in warning in lib/plugin 2015-05-04 13:16:47 +02:00
Samy Pessé 2523925915 Bump version to 2.0.2 2015-05-02 12:39:05 +02:00
Samy Pesse d5bbd8475c Fix #721: use links.join instead of path.join for links in page 2015-04-23 12:58:24 -05:00
Samy Pesse 54d195268a Add test relative links (related to #721) 2015-04-23 12:05:04 -05:00
Samy Pesse a0deb9509f Merge branch 'awrelll-master' 2015-04-20 07:53:16 -05:00
Samy Pesse b0b1433594 Fix authors list merge 2015-04-20 07:52:12 -05:00
Samy Pessé 17a2c0a37c Merge pull request #706 from savikko/patch-1
Added Finnish author
2015-04-14 18:56:31 -05:00
Samy Pessé fd68ea1cc2 Merge pull request #705 from savikko/master
Added Finnish
2015-04-14 18:56:21 -05:00
Tommi Savikko 784874c776 Added Finnish author 2015-04-14 22:39:23 +03:00
Thomas Clayton f45c6d3466 Added Finnish 2015-04-14 21:50:46 +03:00
Samy Pessé 98af70902f Merge pull request #701 from anthonyfok/patch-1
Fix typo in lib/book.js: lanuages → languages
2015-04-10 20:50:35 -05:00
Anthony Fok 41a67b5c4c Fix typo in lib/book.js: lanuages → languages 2015-04-10 07:41:12 -06:00
Samy Pessé 83ee903af4 Merge pull request #700 from paulmillr/master
Switch from gaze to chokidar.
2015-04-10 10:39:13 +02:00
Samy Pessé e591b0e485 Merge pull request #696 from sindresorhus/escaperegex-module
use the `escape-string-regexp` module
2015-04-10 10:37:53 +02:00
Paul Miller bcc9a34742 Switch from gaze to chokidar. 2015-04-10 06:09:04 +03:00
Sindre Sorhus 6b56c7de7f use the escape-string-regexp module
no point in hardcoding this.

https://github.com/sindresorhus/escape-string-regexp
2015-04-08 18:24:26 +07:00
Iancu Aurel 7b42719699 korean and japanese added 2015-04-07 17:34:40 +03:00
awrelll 64b8343f67 korean support added 2015-04-07 17:32:33 +03:00
awrelll fcc5089fa6 japan support added 2015-04-07 17:26:45 +03:00
Samy Pessé 334f782aa8 Merge pull request #693 from awrelll/patch-1
Romanian author added
2015-04-07 16:21:56 +02:00
Samy Pessé 1776f2bf77 Merge pull request #691 from awrelll/master
support for romanian language
2015-04-07 16:21:34 +02:00
Iancu Aurel e259412f79 Romanian author added 2015-04-07 17:21:05 +03:00
awrelll 999a02f110 support for romanian language 2015-04-07 17:12:41 +03:00
Samy Pessé 604d0fba65 Update nunjucks@1.3.0 2015-04-03 22:31:55 +02:00
Samy Pessé 0e8f7b870b Bump version to 2.0.1 2015-04-02 19:41:14 +02:00
Samy Pessé 1eebc9a46e Normalize structure parsing error 2015-04-02 19:21:39 +02:00
Samy Pessé 0a94c80c44 Normalize template errors 2015-04-02 18:59:56 +02:00
Samy Pessé c70bb2fbd8 Update gitbook-parsers@0.7.4 2015-04-02 18:31:49 +02:00
Samy Pessé 12c06b384f Don't fail if config doesn't exists 2015-04-02 09:43:48 +02:00
Samy Pessé 82a58e7ac3 Invalidate configuration cache when reloading 2015-04-02 09:38:57 +02:00
Samy Pessé dcb56ef433 Merge pull request #683 from GitbookIO/fix/i18n
Fix i18n in json format
2015-04-01 22:23:23 +02:00
Samy Pessé 8da91de514 Don't update translations 2015-04-01 22:21:13 +02:00
Samy Pessé 4b20685562 Use i18n node module for template translation 2015-04-01 22:17:12 +02:00
Samy Pessé fff7c5cc3a Add back support for options.originalInput
Related to rtCamp/gitbook-plugin-edit-link#2
2015-03-30 16:50:26 +02:00
Samy Pessé 3065742b73 Separate book.contentLink and book.contentPath 2015-03-28 15:54:34 +01:00
Samy Pessé ffd69ad1f2 Add test for summary paths
Related to #674
2015-03-28 15:28:28 +01:00
Samy Pessé 9004011479 Merge pull request #673 from lszeremeta/master
Polish (pl) added in theme/i18n
2015-03-28 14:54:50 +01:00
Łukasz Szeremeta 1046bb4133 Add @lszeremeta to translators 2015-03-28 14:48:16 +01:00
Łukasz Szeremeta 5578505213 Polish (pl) added in theme/i18n 2015-03-27 22:03:28 +01:00
Samy Pessé a61f56662a Bump version to 2.0.0 2015-03-25 10:43:58 +01:00
Samy Pessé f42e48be03 Fix scroll reset on small resolutions (mobile & tablet) 2015-03-24 23:59:03 +01:00
Samy Pessé f640e101ba Fix scroling position when preparing page 2015-03-24 23:52:41 +01:00
Samy Pessé b7da276ae0 Fix title for introduction (with i18n) 2015-03-24 23:49:12 +01:00
Samy Pessé bf7c0989f5 Update gitbook-parsers@0.7.2 2015-03-24 23:35:17 +01:00
Samy Pessé 65fdbe7f55 Simplify examples of commands 2015-03-24 23:19:00 +01:00
Samy Pessé c9af209a93 Merge pull request #667 from GitbookIO/better-testing
Better Unit Tests
2015-03-24 23:14:17 +01:00
Samy Pessé 48ab44a776 Add tests for conrefs 2015-03-24 18:22:44 +01:00
Samy Pessé b2e684af8f Add test for templating context 2015-03-24 17:34:47 +01:00
Samy Pessé b38a2c11a4 Add tests for plugins 2015-03-24 17:31:15 +01:00
Samy Pessé c31acef47a Add tests for images in ebook 2015-03-24 16:26:19 +01:00
Samy Pessé e9a573e18a Add test for default description from readme 2015-03-24 14:57:29 +01:00
Samy Pessé c07ddc77f7 Add tests for links 2015-03-24 14:52:24 +01:00
Samy Pessé 303fc992d4 Add test for git url parsing 2015-03-24 14:44:07 +01:00
Samy Pessé 4b7797f61b Add basic tests for multilingual books 2015-03-24 14:16:03 +01:00
Samy Pessé f775d41933 Add base tests for ebook generation 2015-03-24 13:52:29 +01:00
Samy Pessé 7722e7bdfa Update gitbook-parsers@0.7.1 2015-03-24 13:33:56 +01:00
Samy Pessé 346c05f0de Add tests for configuration parsing 2015-03-24 13:24:20 +01:00
Samy Pessé 73c69923b3 Add test for summary parsing
Update gitbook-parsers
2015-03-24 13:11:29 +01:00
Samy Pessé afbca4bdf5 Improve tests for glossary 2015-03-24 11:54:03 +01:00
Samy Pessé b61371942b Add test for glossary replacements 2015-03-24 11:27:37 +01:00
Samy Pessé 61c07e8876 Add test for glossary parsing 2015-03-24 10:24:49 +01:00
Samy Pessé d317741144 Add basic test for multilingual book 2015-03-24 09:36:51 +01:00
Samy Pessé 275739a778 Add basic test for website generation 2015-03-24 08:49:39 +01:00
Samy Pessé cb3a43ed8a Add string representation for books 2015-03-24 08:49:22 +01:00
Samy Pessé ec8d1d8fc9 Improve test for json format 2015-03-23 23:48:46 +01:00
Samy Pessé 868a3186dd Add assertion to test that a file exists 2015-03-23 23:32:07 +01:00
Samy Pessé 17b546181c Fix cleanup after tests 2015-03-23 23:23:25 +01:00
Samy Pessé 2d1aa15af8 New cleaner helper for testing 2015-03-23 23:18:15 +01:00
Samy Pessé 63ee94ff89 Ignore codeblocks when replacing glossary terms 2015-03-23 11:00:50 +01:00
Samy Pessé 7d9dc08a38 Highlight codeblocks in gitbook instead than the parsers 2015-03-23 10:31:48 +01:00
Samy Pessé a836bdedb4 Bump version to 2.0.0-beta.5 2015-03-17 11:23:35 +01:00
Samy Pessé 15ebae8cb1 Fix #641: fix progress order in json format 2015-03-17 11:22:56 +01:00
Samy Pessé 315556310f Bump version to 2.0.0-beta.4 2015-03-17 10:48:25 +01:00
Samy Pessé 9c0b26304b Merge branch master 2015-03-17 10:46:17 +01:00
Samy Pessé acdaea9f6c Fix #649: add option "author" in book.json to set meta author in html 2015-03-17 10:38:56 +01:00
Samy Pessé e481deb5bb Merge pull request #650 from wcandillon/patch-2
Update default generator
2015-03-14 16:00:09 -07:00
William Candillon 6d3ac6074c 💄 Update default generator 2015-03-14 15:45:15 -07:00
Samy Pessé 5e611bde48 Merge pull request #648 from wcandillon/patch-1
Bump to lodash 3.5.0
2015-03-14 15:25:39 -07:00
Samy Pessé 9448562156 Add editorconfig and normalize indent 2015-03-14 23:23:28 +01:00
William Candillon e7e8fe4d08 ⬆️ Bump to lodash 3.5.0 2015-03-14 11:35:28 -07:00
Samy Pessé 8320484b88 Fix #647: Fix links normalization (content and hash) 2015-03-13 23:59:37 +01:00
Samy Pessé 0e243e6f23 Bump version to 2.0.0-beta.3 2015-03-12 21:23:25 +01:00
Samy Pessé 5cd25b0d21 Update gitbook-parsers@0.5.4 2015-03-12 21:20:51 +01:00
Samy Pessé 3218ee7455 Fix tests to adapt to changes in parsers 2015-03-11 22:05:58 +01:00
Samy Pessé 0552007b8a Bump version to 2.0.0-beta.2 2015-03-11 22:03:54 +01:00
Samy Pessé 50bc89d9d9 Fix define of introduction from summary 2015-03-11 22:02:46 +01:00
Samy Pessé 743a88f53a Fix typo in bin message 2015-03-11 11:40:56 +01:00
Samy Pessé ee92c6dd99 Add changelog for 2.0.0-beta.1 2015-03-11 11:23:48 +01:00
Samy Pessé b6c54c17d1 Bump version to 2.0.0-beta.1 2015-03-11 11:17:56 +01:00
Samy Pessé 992ef1ab74 Use latest commit from nunjucks windows fix branch 2015-03-11 11:17:43 +01:00
Samy Pessé 960848ba34 Ensure inline svgs have xml header 2015-03-11 09:38:18 +01:00
Samy Pessé d9aca7a9df Fix #639: update nunjucks to support windows 2015-03-11 00:57:07 +01:00
Samy Pessé 05a0de2d86 Remove require of old dependency "shell-escape" 2015-03-11 00:50:48 +01:00
Samy Pessé 19e4f498cf Fix inline svg extraction on windows 2015-03-10 16:45:22 -07:00
Samy Pessé 3055139297 Fix run of svgexport on windows 2015-03-10 16:31:43 -07:00
Samy Pessé 3d6b099dea Fix links normalization on windows 2015-03-10 22:44:54 +01:00
Samy Pessé dd970e33b8 Remove --no-exit option from mocha tests runner 2015-03-10 21:31:43 +01:00
Samy Pessé 59ba479465 Test option --no-exit for mocha tests 2015-03-10 16:14:04 +01:00
Samy Pessé 54c9ecf3c2 Use mocha from node_modules/.bin 2015-03-10 15:44:39 +01:00
Samy Pessé 8308ae69a2 Remove command export from "npm test" 2015-03-10 15:01:51 +01:00
Samy Pessé bd6c3287ed Add badge for windows testing 2015-03-10 14:58:23 +01:00
Samy Pessé 24fc36deb1 Add appveyor.yml for windows testing
Related to #639
2015-03-10 14:52:09 +01:00
Samy Pessé 2f44b61cec Merge pull request #638 from wapmorgan/patch-1
Update README.md
2015-03-09 21:13:29 +01:00
wapmorgan 45ee503db1 Update README.md
Fix link
2015-03-10 00:12:53 +04:00
Samy Pessé dc826da99b Update README.md 2015-03-09 10:58:11 +01:00
Samy Pessé 3ea659d582 Improve readme presentation 2015-03-09 10:57:23 +01:00
Samy Pessé 34fc2831e0 Merge branch 'version/2.0' 2015-03-09 10:43:12 +01:00
Samy Pessé 1bf68a5aa0 Merge branch 'master' into version/2.0
Conflicts:
	README.md
2015-03-09 10:42:42 +01:00
Samy Pessé d72c397f23 Update gitbook-parsers@0.5.2 2015-03-08 23:09:50 +01:00
Samy Pessé 2c69525148 Add GitBook as book producer in ebook-convert 2015-03-08 22:53:18 +01:00
Samy Pessé ee3a0ba801 Fix #633: update markdown parser to fix codeblocks
Sort glossary and fix #634
2015-03-08 22:53:18 +01:00
Samy Pessé 7a4179a2a2 Merge pull request #631 from MHM5000/version/2.0
[i18n] - fa: Persian/Farsi
2015-03-07 18:48:05 +01:00
Mohammad Hossein Mojtahedi 1d0083c5f4 added @mhm5000 in translators 2015-03-07 18:22:40 +03:30
Mohammad Hossein Mojtahedi 33a6111a30 [i18n] - fa: Persian/Farsi 2015-03-07 16:48:44 +03:30
Samy Pessé a5d7a87e31 Enable rtl in ebooks 2015-03-06 22:45:53 +01:00
Samy Pessé c7f7c5b5ab Base translation for Arabic (with rtl support) 2015-03-06 22:32:45 +01:00
Samy Pessé 55a7b99b4d Fix #227: Add base rtl support for website 2015-03-06 22:32:25 +01:00
Samy Pessé 8bfba604b3 Update gitbook-parsers@0.5.0 and include page.prepare
Fix #625: escape code blocks in markdown
2015-03-06 16:54:46 +01:00
Samy Pessé 2a5fa1c5fb Fix #629: add generator name in template context 2015-03-06 14:34:55 +01:00
Samy Pessé a3e95feb26 Add instructions to use version from git 2015-03-06 13:58:23 +01:00
Samy Pessé 145b00f590 Fix #628: preserve pure anchor links and hash in relative links 2015-03-06 10:25:06 +01:00
Samy Pessé 5f2785f0a8 Escape svgexport args
Fixes shakiba/svgexport#5 and #624
2015-03-05 10:06:45 +01:00
Samy Pessé 412529c548 Merge pull request #621 from nasirkhan/version/2.0
Bengali (bn) added in theme/i18n
2015-02-27 17:48:07 +01:00
nasirkhan 547ec6ade8 bn language added 2015-02-27 22:29:10 +06:00
nasirkhan eac513cfa3 Merge remote-tracking branch 'upstream/version/2.0' into version/2.0 2015-02-27 22:16:11 +06:00
Aaron O'Mullan 5ec8a1f18c Add en.json
Fixes #620
2015-02-27 16:02:31 +01:00
Samy Pessé c923a7e01a Fix transformation of README.md links in index.html 2015-02-26 01:14:27 +01:00
Samy Pessé 366e6ed105 Bump version to 2.0.0-alpha.9 2015-02-24 13:57:20 +01:00
Samy Pessé 52078eb666 Use latest nunjucks from mozilla/nunjucks 2015-02-24 13:54:08 +01:00
Samy Pessé d9ddbff443 Fix links in sidebar 2015-02-24 13:51:10 +01:00
Samy Pessé 01b160f9a1 Fix normalization of html link (README to index) 2015-02-21 13:40:38 +01:00
Samy Pessé 23fcb817a4 Fix html snippets escaping 2015-02-20 20:52:07 +01:00
Samy Pessé f531a3f984 Update nunjucks-autoescape 2015-02-20 12:24:33 +01:00
Samy Pessé c777023e9f Add introduction to changelog 2015-02-17 14:18:49 +01:00
Samy Pessé 62c99759c1 Bump version to 2.0.0-alpha.8 2015-02-14 16:43:19 +01:00
Samy Pessé 6951c21d19 Update gitbook-parsers@0.4.1 2015-02-14 16:26:16 +01:00
Samy Pessé 3a8289483e Improve language detection from book.json 2015-02-14 15:34:19 +01:00
Samy Pessé 4079de9587 Fix #608: fix chapter name for glossary 2015-02-14 15:29:41 +01:00
Samy Pessé b86d171082 Escape description in title attr of glossary link
Related to #609
2015-02-14 11:53:30 +01:00
Samy Pessé 959b272e65 Fix #609: don't escape html in glossary 2015-02-14 11:52:33 +01:00
Samy Pessé 684440e2d1 Fix generation of multilingual book as ebook 2015-02-14 11:49:42 +01:00
Samy Pessé 4740cd3b06 Merge pull request #605 from GitbookIO/update/lodash
Update lodash to 3.x.x
2015-02-13 08:18:45 +01:00
Samy Pessé b3131d99d2 Update lodash@3.2.0 2015-02-13 08:16:28 +01:00
Samy Pessé b0fd2a67ea Fix test with post in blocks 2015-02-13 08:09:28 +01:00
Samy Pessé 7c83869869 Limit concurrent blocks processed 2015-02-13 00:04:27 +01:00
Samy Pessé 57d5c23eaf Accept post function from block to post process content 2015-02-12 23:36:22 +01:00
Samy Pessé 8d92b74e61 Fix page normalization with empty links or images 2015-02-12 18:43:06 +01:00
Samy Pessé 4e2cda99cc Complete changelog for 2.0.0-alpha.7 2015-02-12 16:40:50 +01:00
Samy Pessé 12a7a4c4cf Fix test for lodash 3.1.0 (from git) 2015-02-11 17:53:46 +01:00
Samy Pessé e1594cde2c Remove doc about custom styles 2015-01-19 13:14:52 +01:00
262 changed files with 9168 additions and 9592 deletions
+10
View File
@@ -0,0 +1,10 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
+2
View File
@@ -0,0 +1,2 @@
docs/**/*
test/node_modules/**/*
+19
View File
@@ -0,0 +1,19 @@
{
"rules": {
"indent": [ 2, 4 ],
"quotes": [ 2, "single" ],
"linebreak-style": [ 2, "unix" ],
"semi": [ 2, "always" ],
"no-unused-vars": [ 2, {
"vars": "all",
"args": "none"
} ],
"spaced-comment": [ 2, "always" ]
},
"env": {
"node": true,
"mocha": true,
"browser": true
},
"extends": "eslint:recommended"
}
+8 -4
View File
@@ -22,10 +22,14 @@ build/Release
# Dependency directory
# Deployed apps should consider commenting this line out:
# see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git
node_modules
theme/javascript/vendors
theme/vendors
/node_modules
# vim swapfile
*.swp
# Output of documentation
_book
book.pdf
book.epub
book.mobi
+6 -3
View File
@@ -1,7 +1,10 @@
sudo: false
language: node_js
node_js:
- "0.11"
- "0.10"
- "stable"
- "4.1"
- "0.12"
before_install:
- npm install svgexport -g
- npm install svgexport -g
after_success:
- npm run lint
+36 -9
View File
@@ -21,20 +21,47 @@ Translators
------------
- German
- Winnie (@winniehell)
- Winnie (@winniehell)
- Italian
- Giulio Bonanome (@gbonanome)
- Giulio Bonanome (@gbonanome)
- Russian
- Andrey Akinshin (@AndreyAkinshin)
- Andrey Akinshin (@AndreyAkinshin)
- Norwegian
- Knut Melvær (@kmelve)
- Knut Melvær (@kmelve)
- Persian (Farsi)
- Mohammad Hossein Mojtahedi (@mhm5000)
- Polish
- Łukasz Szeremeta (@lszeremeta)
- Portuguese
- Ryan O'Mullan (@RyanOM)
- Ryan O'Mullan (@RyanOM)
- Spanish
- Ryan O'Mullan (@RyanOM)
- Ryan O'Mullan (@RyanOM)
- Simplifiled Chinese
- Hu Hao (@howiehu)
- Hu Hao (@howiehu)
- Traditional Chinese
- Hu Hao (@howiehu)
- Hu Hao (@howiehu)
- French
- Samy Pessé (@SamyPesse)
- Samy Pessé (@SamyPesse)
- Romanian
- Iancu Aurel (@awrelll)
- Finnish
- Tommi Savikko (@savikko)
- Japanese
- Iancu Aurel (@awrelll)
- Korean
- Iancu Aurel (@awrelll)
- SangYeob Yu (@deminoth)
- Vietnamese
- Hong Nguyen (@nghong)
- Hebrew
- @a-moses
- Ukrainian
- @Karnaukhov
- Czech
- @mjanda
- Swedish
- Jacob Burenstam (@buren)
- Turkish
- Turan Konan (@turankonan)
- Catalan
- Esaú García Sánchez-Torija (@egasato)
+209
View File
@@ -1,4 +1,213 @@
# Release notes
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## 3.0.0 (pre)
- Summary can contain external links and anchors (Fix [#776](https://github.com/GitbookIO/gitbook/issues/776))
- Summary can contain differents entitled sections
- Glossary is generated as a normal page
- Headings are no longer annotated with glossary terms
- Themes are now published as a plugin, with ability to extend it from the book source
- `links.sidebar` configuration is no longer supported, use summary sections instead
- `pdf.headerTemplate` and `pdf.footerTemplate` have been replaced by a template in theme/book: `_layout/ebook/pdf_header.html` and `_layout/ebook/pdf_footer.html`
- Markdown parser is now using CommonMark
- Root folder for the book can be specified in a `.gitbook` file
- Multi-lingual books share assets folder
- YAML front matter is parsed and can extend page's properties
- Fix `uk` translation
## 2.6.7
- Fix bug with filenames including spaces
- Add Turkish and Catalan translations
## 2.6.6
- Fix custom CSS that are generated by plugins for PDF output
## 2.6.5
- Fix support for plugins generating custom stylesheets (`styles-less` and `styles-sass`)
- Fix glossary terms being replaced in script (ex: math)
## 2.6.4
- Fix regression introduced by `2.6.3` of single HTML tags in markdown
## 2.6.3
- Fix parsing bug with inline HTML in Markdown
## 2.6.2
- Fix `gitbook.state.bookRoot`, `gitbook.state.root` now has a trailing slash
- Update nunjucks to 2.2.0
## 2.6.1
- Use CamelCase for `gitbook.state.innerLanguage`
## 2.6.0
- Close sidebar after clicking a link on mobile
- Add root for multilingual books: `gitbook.state.bookRoot`
- Fix color of h6 headings
- Fix bottom margin of lists and blockquotes
- Add Swedish translation (`sv`)
- Add Czech translation (`cs`)
- Fix locale names for `zh-hans` and `jp`
- Update plugin `search` to fix crashes
- Aceept case-incensitive structure files (README, GLOSSARY, etc)
## 2.5.2
- Fix custom stylesheets for ebook generation
- Trigger event `start` before `page.change`
## 2.5.1
- Fix calcul of `gitbook.state.root` when serving HTML index as `/`
## 2.5.0
- Font settings, sharing and search are externalized as default plugins
- Plugins can define a configuration schema in the manifest, this schema will be used to validate configuration during build
- New Node.js API for plugin: `book.formatString(type, content)`
- New client side API for website plugins: `gitbook.toolbar.createButton(opts)`
- Better header/footer for PDF, CSS wil be inlined to easily style the header/footer
- Cleaner table of contents for ebooks
- Support for RTL in ebook's table of contents
- Better colors for mobi (links and code blocks)
- Fix installation of plugins when using a pre-release
- Fix support for pre-releases
- Update asciidoc parser to remove git dependency
- Fix templating in imported content
- Fix querystring in image urls
- Normalize heading IDs like GitHub
- Use Arial as default font for PDFs
- Add `root`, `chapterTitle` and `filepath` to `gitbook.state` JS API
## 2.4.3
- Add ukrainian translation (`uk`)
- Add `book.json` configuration for maximum size of search index
- Improve reliability of summary parser
## 2.4.2
- Default plugins should not be installed by `gitbook install`
- Limit search index size to avoid crash during generation
- Fix code highlighting for html without language specified
- Fix warning message for gitbook version when building a multilingual book
## 2.4.1
- Fix disabling of default plugins, ex: `-highlight`
## 2.4.0
- Fix page being updated when user wants to open a link in a new tab
- Plugins can now replaced default code highlighter
- Add semantic information for screen readers (web version)
- Content references accept absolute paths, resolved to book folder
- Improve overall reliability
## 2.3.3
- Fix bug in SUMMARY parsing preventing multiple entries without filenames
## 2.3.2
- Fix blocks (like maths) in Asciidoc
- Fix error when checking gitbook version
## 2.3.1
- Fix black font color for ebooks (mobi, pdf and epub)
- Fix ISO code for korean language
- Fix korean translation
- Fix syntax highlighting for asciidoc
- Fix inline html escaping in markdown
- Add warning for file outside SUMMARY
- Force SUMMARY entries to be unique by filename
## 2.3.0
- Fix nunjucks issue with multiple `{% raw %}` blocks
- Fix crash when git conref failed
- Fix crash when failed to download remote image (better error message)
- Fix flicking effect when changing page (big UX improvement)
- Add Hebrew translation (`he`)
- Add utility method `book.config.get` for plugins
- Hooks `page:before` and `page` are no longer deprecated
- Remove webfonts to make website lighter
- Make glossary's order case insensitive
## 2.2.0
- Fix direction in code blocks (always LTR)
- Add options `chapterMark` and `pageBreaksBefore` for PDF
- Update code highlighting library
- `book.json` accessible as `config` in templating syntax
- Add Vietnamese translation (`vi`)
## 2.1.0
- Fix error in calcul of `levels` in table of contents, error introduced a few versions ago
- Add optional `styles/print.css` to replace `print.css` used in ebook
## 2.0.4
- Fix `{% raw %}`, got confused with "fake" variable declarations
- Fix title of language chooser
- Fix the X-UA-Compatible meta tag
- Move style sheets to the <head> section
## 2.0.3
- Fix `gitbook init` for SUMMARY with empty entries
- Fix escaping of code blocks in markdown
## 2.0.2
- Fix relative links in windows
- Improve watcher in serve command (switch to chokidar)
- Add Romanian translation (`ro`)
- Add Finish translation (`fi`)
- Add Japanese translation (`jp`)
- Add Korean translation (`kr`)
## 2.0.1
- Improve error logging (display file, line and column)
- Add back support for `options.originalInput`
- Don't process math in markdown parser (delegated to `mathjax` plugin)
- Fix some cases of code blocks escaping
- Fix i18n for introduction title in json format
- Fix reload when book configuration is updated
- Fix backslashes in url when building on windows
## 2.0.0
- Fix page title of introduction
- Ignore codeblocks when replacing glossary terms
- Improve Unit Tests
- Fix scrolling position in website when preparing page
## 2.0.0-beta.5
- Fix progress order in json format
## 2.0.0-beta.4
- Fix default generator for use programmatically
- Add option "author" for html meta tags
- Fix links normalization (content and hash)
## 2.0.0-beta.3
- Fix odd cases with code blocks escaping
## 2.0.0-beta.2
- Fix definition of entry point title using SUMMARY.md
## 2.0.0-beta.1
- Fix windows incompatibility
- Add support for rtl (enabled by default for `ar` and `fa`)
- Escape code blocks in markdown parser
- Add Persian/Farsi translation (`fa`)
- Add Arabic translation (`ar`)
- Add Bengali translation (`bn`)
- Provide generator name in template context
## 2.0.0-alpha.9
- Fix links in sidebar
- Fix normalization of html link (README to index)
- Fix html snippets escaping
## 2.0.0-alpha.8
- Improve locale detection for i18n
- Fix chapter name for Glossary in pdf
- Don't escape html in glossary items
- Fix generation of multilingual book as ebook
- Add "post" block attribute to post-process
## 2.0.0-alpha.7
- Fix display of glossary in ebook formats
- Add default footer and header to pdf
- Fix generation of json format compatible with 1.x.x
- Add Simplifiled Chinese and Traditional Chinese translations
## 2.0.0-alpha.6
- Add es and pt translations
-96
View File
@@ -1,96 +0,0 @@
module.exports = function (grunt) {
var path = require("path");
// Load NPM tasks
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks("grunt-bower-install-simple");
// Init GRUNT configuraton
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
'bower-install-simple': {
options: {
color: true,
production: false,
directory: "theme/vendors"
}
},
less: {
development: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: {
"theme/assets/style.css": "theme/stylesheets/website.less",
"theme/assets/print.css": "theme/stylesheets/ebook.less"
}
}
},
requirejs: {
compile: {
options: {
name: "gitbook",
baseUrl: "theme/javascript/",
out: "theme/assets/app.js",
preserveLicenseComments: false,
optimize: "uglify",
include: ["requireLib"],
paths: {
"jQuery": '../vendors/jquery/dist/jquery',
"lodash": '../vendors/lodash/dist/lodash',
"requireLib": '../vendors/requirejs/require',
"Mousetrap": '../vendors/mousetrap/mousetrap',
"lunr": '../vendors/lunr.js/lunr',
"URIjs": '../vendors/URIjs/src/',
"ace": '../vendors/ace-builds/src-noconflict/'
},
shim: {
'jQuery': {
exports: '$'
},
'lodash': {
exports: '_'
},
'Mousetrap': {
exports: 'Mousetrap'
},
'lunr': {
exports: 'lunr'
}
}
}
}
},
copy: {
vendors: {
files: [
{
expand: true,
cwd: 'theme/vendors/fontawesome/fonts/',
src: ['**'],
dest: 'theme/assets/fonts/fontawesome/',
filter: 'isFile'
}
]
}
}
});
grunt.registerTask("bower-install", [ "bower-install-simple" ]);
// Build
grunt.registerTask('build', [
'bower-install',
'less',
'requirejs',
'copy:vendors'
]);
grunt.registerTask('default', [
'build'
]);
};
+29 -189
View File
@@ -1,211 +1,51 @@
GitBook
=======
:warning: This branch contains the version 2.0.
[![Build Status](https://travis-ci.org/GitbookIO/gitbook.png?branch=master)](https://travis-ci.org/GitbookIO/gitbook)
[![NPM version](https://badge.fury.io/js/gitbook.svg)](http://badge.fury.io/js/gitbook)
[![Linux Build Status](https://travis-ci.org/GitbookIO/gitbook.png?branch=master)](https://travis-ci.org/GitbookIO/gitbook)
[![Windows Build status](https://ci.appveyor.com/api/projects/status/63nlflxcwmb2pue6?svg=true)](https://ci.appveyor.com/project/GitBook/gitbook)
[![Slack Status](https://slack.gitbook.com/badge.svg)](https://slack.gitbook.com)
GitBook is a command line tool (and Node.js library) for building beautiful books using GitHub/Git and Markdown (or AsciiDoc). Here is an example: [Learn Javascript](https://www.gitbook.com/book/GitBookIO/javascript). You can publish and host book easily online using [gitbook.com](https://www.gitbook.com), a web-editor is [also available](https://www.gitbook.com/editor). You can follow [@GitBookIO](https://twitter.com/GitBookIO) on Twitter. Complete documentation is available at [help.gitbook.io](http://help.gitbook.io/).
GitBook is a command line tool (and Node.js library) for building beautiful books using GitHub/Git and Markdown (or AsciiDoc). Here is an example: [Learn Javascript](https://www.gitbook.com/book/GitBookIO/javascript).
You can publish and host books easily online using [gitbook.com](https://www.gitbook.com). A desktop editor is [also available](https://www.gitbook.com/editor).
Check out the [GitBook Community Slack Channel](https://slack.gitbook.com), Stay updated by following [@GitBookIO](https://twitter.com/GitBookIO) on Twitter or [GitBook](https://www.facebook.com/gitbookcom) on Facebook.
Complete documentation is available at [help.gitbook.com](http://help.gitbook.com/).
![Image](https://raw.github.com/GitbookIO/gitbook/master/preview.png)
## How to use it:
## Getting started
GitBook can be installed from **NPM** using:
GitBook can be used either on your computer for building local books or on GitBook.com for hosting them. To get started, check out [the installation instructions in the documentation](docs/setup.md).
```
$ npm install gitbook-cli -g
```
## Usage examples
Create the directories and files for a book from its [SUMMARY.md](https://github.com/GitbookIO/gitbook#book-format) file (if existing) using
GitBook can be used to create book, public documentation, enterprise manual, thesis, research papers, etc.
```
$ gitbook init
```
You can find a [list of real-world examples](docs/examples.md) in the documentation.
You can serve a repository as a book using:
## Help and Support
```
$ gitbook serve ./repository
```
Or simply build the static website using:
```
$ gitbook build ./repository ./outputFolder
```
We're always happy to help out with your books or any other questions you might have. You can ask a question on the following contact form at [gitbook.com/contact](https://www.gitbook.com/contact) or signal an issue on [GitHub](https://github.com/GitbookIO/gitbook).
## Features
* [Output as a website or ebook (pdf, epub, mobi)](#output-formats)
* [Multi-Languages](#multi-languages)
* [Glossary](#glossary)
* [Cover](#cover)
* [AsciiDoc Support](#asciidoc)
* [Variables and Templating](#variables-and-templating)
* [Content References](#content-references)
* [Plugins](#plugins)
* Interractive reader website:
* Search
* Font Settings (Serif, Sans Serif)
* Themes: white, sepia, night
## Output Formats
GitBook can generate your book in the following formats:
* **Static Website**: This is the default format. It generates a complete interactive static website that can be, for example, hosted on GitHub Pages.
* **eBook**: You need to have [ebook-convert](http://manual.calibre-ebook.com/cli/ebook-convert.html) installed. You can specify the eBook filename as the second argument, otherwise `book` will be used.
* Generate a **PDF** using: `gitbook pdf ./myrepo ./mybook.pdf`
* Generate a **ePub** using: `gitbook epub ./myrepo ./mybook.epub`
* Generate a **MOBI** using: `gitbook mobi ./myrepo ./mybook.mobi`
* **JSON**: This format is used for debugging or extracting metadata from a book. Generate this format using: ```gitbook build ./myrepo --format=json```.
## Book Format
A book is a Git repository containing at least 2 files: `README.md` and `SUMMARY.md`.
#### README.md
Typically, this should be the introduction for your book. It will be automatically added to the final summary.
#### SUMMARY.md
The `SUMMARY.md` defines your book's structure. It should contain a list of chapters, linking to their respective pages.
Example:
```markdown
# Summary
This is the summary of my book.
* [section 1](section1/README.md)
* [example 1](section1/example1.md)
* [example 2](section1/example2.md)
* [section 2](section2/README.md)
* [example 1](section2/example1.md)
```
Files that are not included in `SUMMARY.md` will not be processed by `gitbook`.
#### Multi-Languages
GitBook supports building books written in multiple languages. Each language should be a sub-directory following the normal GitBook format, and a file named `LANGS.md` should be present at the root of the repository with the following format:
```markdown
* [English](en/)
* [French](fr/)
* [Español](es/)
```
You can see a complete example with the [Learn Git](https://github.com/GitbookIO/git) book.
#### Glossary
Allows you to specify terms and their respective definitions to be displayed in the glossary. Based on those terms, `gitbook` will automatically build an index and highlight those terms in pages.
The `GLOSSARY.md` format is very simple :
```markdown
# term
Definition for this term
# Another term
With it's definition, this can contain bold text and all other kinds of inline markup ...
```
#### Variables and Templating
A set of variables can be defined in the `book.json`:
```js
{
"variables": {
"host": "mybook.com"
}
}
```
These variables can be used in the markdown files:
```
The host is {{ book.host }}
```
You can also use condition with these variables:
```
{% if book.host == "mybook.com" %}
{% else %}
{% endif %}
```
Variables of `book.json` are available in the `book` namespace. You can also access informations about the `file` itself and the `gitbook` version:
```
My file is {{ file.path }}
Modified at {{ file.mtime }}
Book built with GitBook {{ gitbook.version }}
```
#### Content References
You can use "content references," or conrefs, when writing books or documentation using GitBook.
Include a file from the same book:
```
{% include "./test.md" %}
```
or from a git repository (with a specific revision):
```
{% include "git+https://github.com/GitbookIO/documentation.git/README.md#1.0.1" %}
```
Includes can be used with variables (see [Variables and Templating](#variables-and-templating)):
```
{% include book.ref_doc_readme %}
```
#### Ignoring files & folders
GitBook will read the `.gitignore`, `.bookignore` and `.ignore` files to get a list of files and folders to skip. (The format inside those files follows the same convention as `.gitignore`).
Best practices for the `.gitignore` is to ignore build files from **node.js** (`node_modules`, ...) and build files from GitBook: `_book`, `*.epub`, `*.mobi` and `*.pdf` ([Download GitBook.gitignore](https://github.com/github/gitignore/blob/master/GitBook.gitignore)).
#### Cover
A cover image can be set by creating a file: **/cover.jpg**.
The best resolution is **1800x2360**. The generation of the cover can be done automatically using the plugin [autocover](https://github.com/GitbookIO/plugin-autocover).
A small version of the cover can also be set by creating a file: **/cover_small.jpg**.
#### AsciiDoc
Since version 2.0.0, AsciiDoc can be used instead of Markdown, simply replace the `.md` by the `.adoc` extension. Chapters in the summary are detected from an ordered list in the `SUMMARY.adoc`.
* [Output as a website or ebook (pdf, epub, mobi)](http://help.gitbook.com/format/output.html)
* [Multi-Languages](http://help.gitbook.com/format/languages.html)
* [Glossary](http://help.gitbook.com/format/glossary.html)
* [Cover](http://help.gitbook.com/format/cover.html)
* [AsciiDoc Support](http://help.gitbook.com/format/asciidoc.html)
* [Variables and Templating](http://help.gitbook.com/format/templating.html)
* [Content References](http://help.gitbook.com/format/conrefs.html)
* [Plugins](http://help.gitbook.com/format/plugins.html)
* [Beautiful default theme](https://github.com/GitbookIO/theme-default)
## Publish your book
The platform [GitBook.com](https://www.gitbook.com/) is like an "Heroku for books": you can create a book on it (public, paid, or private) and update it using **git push**.
The platform [GitBook.com](https://www.gitbook.com/) is like an "Heroku for books": you can create a book on it (public, or private) and update it using **git push**.
## Plugins
## Licensing
Plugins can be used to extend your book's functionality. Read [GitbookIO/plugin](https://github.com/GitbookIO/plugin) for more information about how to build a plugin for GitBook.
Plugins needed to build a book can be installed using: `gitbook install ./`. You can find plugins at [plugins.gitbook.com](plugins.gitbook.com).
## Debugging
You can use the options `--log=debug` and `--debug` to get better error messages (with stack trace). For example:
```
$ gitbook build ./ -- log=debug --debug
```
GitBook is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text.
+29
View File
@@ -0,0 +1,29 @@
# Fix line endings in Windows. (runs before repo cloning)
init:
- git config --global core.autocrlf input
# Test against these versions of Node.js.
environment:
matrix:
- nodejs_version: "0.12"
- nodejs_version: "4.1"
# Install scripts. (runs after repo cloning)
install:
# Get the latest stable version of Node.js or io.js
- ps: Install-Product node $env:nodejs_version
# install svgexport
- npm install svgexport -g
# install modules
- npm install
# Post-install test scripts.
test_script:
# Output useful info for debugging.
- node --version
- npm --version
# run tests
- npm test
# Don't actually build.
build: off
+4 -3
View File
@@ -1,7 +1,8 @@
#! /usr/bin/env node
/* eslint-disable no-console */
var color = require('bash-color');
console.log(color.red("You need to install 'gitbook-cli' to have access to the gitbook command anywhere on your system."));
console.log(color.red("If you've installe this package globally, you need to uninstall it."));
console.log(color.red(">> Run 'npm uninstall -g gitbook' then 'npm install -g gitbook-cli'"));
console.log(color.red('You need to install "gitbook-cli" to have access to the gitbook command anywhere on your system.'));
console.log(color.red('If you\'ve installed this package globally, you need to uninstall it.'));
console.log(color.red('>> Run "npm uninstall -g gitbook" then "npm install -g gitbook-cli"'));
+24
View File
@@ -0,0 +1,24 @@
var pkg = require('./package.json');
module.exports = {
// Documentation for GitBook is stored under "docs"
root: './docs',
title: 'GitBook Documentation',
// Enforce use of GitBook v3
gitbook: pkg.version,
// Use the "official" theme
plugins: ['theme-official', 'sitemap'],
theme: 'official',
variables: {
version: pkg.version
},
pluginsConfig: {
sitemap: {
hostname: 'https://docs.gitbook.com'
}
}
};
-13
View File
@@ -1,13 +0,0 @@
{
"name": "GitBook",
"version": "1.0.0",
"dependencies": {
"jquery": "2.1.1",
"lodash": "2.4.1",
"requirejs": "2.1.11",
"URIjs": "1.13.1",
"mousetrap": "1.4.6",
"lunr.js": "0.5.2",
"fontawesome": "4.1.0"
}
}
+26
View File
@@ -0,0 +1,26 @@
# GitBook Format Documentation
This document aims to be a comprehensive guide to GitBook. It contains the full documentation for version **{{ book.version }}**. Help for GitBook.com specific questions can be found at [help.gitbook.com](https://help.gitbook.com).
### What is GitBook?
GitBook is a command line tool (and Node.js library) for building beautiful books using GitHub/Git and Markdown (or AsciiDoc). . This documentation has been generated using GitBook.
GitBook can output your content as a website ([customizable](themes/README.md) and [extensibles](plugins/README.md)) or as an ebook (PDF, ePub or Mobi).
[GitBook.com](https://www.gitbook.com) is the online platform to create and host books built using the GitBook format. It offers hosting, collaboration features and an [easy-to-use editor](https://www.gitbook.com/editor).
### Help and Support
We're always happy to help out with your books or any other questions you might have. You can ask a question on the following contact form at [gitbook.com/contact](https://www.gitbook.com/contact) or signal an issue on [GitHub](https://github.com/GitbookIO/gitbook).
Check out the [GitBook Community Slack Channel](https://slack.gitbook.com), Stay updated by following [@GitBookIO](https://twitter.com/GitBookIO) on Twitter or [GitBook](https://www.facebook.com/gitbookcom) on Facebook.
### FAQ
Some questions are frequently asked. If you have a problem you should [check this out](faq.md) first.
### Contribute to this documentation
You can contribute to improve this documentation on [GitHub](https://github.com/GitbookIO/gitbook) by signaling issues or proposing changes.
+34
View File
@@ -0,0 +1,34 @@
# Summary
### Getting Started
* [About this documentation](README.md)
* [Installation and Setup](setup.md)
### Your Content
* [Directory structure](structure.md)
* [Pages and Summary](pages.md)
* [Configuration](config.md)
* [Glossary](lexicon.md)
* [Multi-Lingual](languages.md)
* [AsciiDoc](asciidoc.md)
### Customization
* [Cover](cover.md)
* [Templating](templating/README.md)
* [Content References](templating/conrefs.md)
* [Variables](templating/variables.md)
* [Plugins](plugins/README.md)
* [Create a plugin](plugins/create.md)
* [Test your plugin](plugins/testing.md)
* [Theming](themes/README.md)
--
* [FAQ](faq.md)
* [Examples](examples.md)
* [Release notes](https://github.com/GitbookIO/gitbook/blob/master/CHANGES.md)
+26
View File
@@ -0,0 +1,26 @@
{% extends template.theme %}
{% block header_nav %}
<a href="https://github.com/GitbookIO/gitbook/blob/master/docs/{{ file.path }}" target="_blank" class="btn btn-link pull-right hidden-xs">
<i class="octicon octicon-mark-github"></i> Edit on GitHub
</a>
<a href="{{ "faq.md"|resolveFile }}" class="btn btn-link pull-right hidden-xs">
F.A.Q
</a>
<a href="https://github.com/GitbookIO/gitbook/blob/master/CHANGES.md" target="_blank" class="btn btn-link pull-right hidden-xs">
{{ book.version }}
</a>
{% endblock %}
{% block page %}
{{ super() }}
<hr>
<div class="btn-group btn-group-justified">
{% if page.previous and page.previous.path %}
<a class="btn" href="{{ page.previous.path|resolveFile }}"><b>Previous:</b> {{ page.previous.title }}</a>
{% endif %}
{% if page.next and page.next.path %}
<a class="btn" href="{{ page.next.path|resolveFile }}"><b>Next:</b> {{ page.next.title }}</a>
{% endif %}
</div>
{% endblock %}
+65
View File
@@ -0,0 +1,65 @@
# AsciiDoc
Since version `2.0.0`, GitBook can also accept AsciiDoc as an input format.
Please refer to the [AsciiDoc Syntax Quick Reference](http://asciidoctor.org/docs/asciidoc-syntax-quick-reference/) for more informations about the format.
Just like for markdown, GitBook is using some special files to extract structures: `README.adoc`, `SUMMARY.adoc`, `LANGS.adoc` and `GLOSSARY.adoc`.
### README.adoc
This is the main entry of your book: the introduction. This file is **required**.
### SUMMARY.adoc
This file defines the list of chapters and subchapters. Just like in Markdown, the `SUMMARY.adoc`'s format is simply a list of links, the name of the link is used as the chapter's name, and the target is a path to that chapter's file.
Subchapters are defined simply by adding a nested list to a parent chapter.
```asciidoc
= Summary
. link:chapter-1/README.adoc[Chapter 1]
.. link:chapter-1/ARTICLE1.adoc[Article 1]
.. link:chapter-1/ARTICLE2.adoc[Article 2]
... link:chapter-1/ARTICLE-1-2-1.adoc[Article 1.2.1]
. link:chapter-2/README.adoc[Chapter 2]
. link:chapter-3/README.adoc[Chapter 3]
. link:chapter-4/README.adoc[Chapter 4]
.. Unfinished article
. Unfinished Chapter
```
### LANGS.adoc
For [Multi-Languages](./languages.md) books, this file is used to define the different supported languages and translations.
This file is following the same syntax as the `SUMMARY.adoc`:
```asciidoc
= Languages
. link:en/[English]
. link:fr/[French]
```
### GLOSSARY.adoc
This file is used to define terms. [See the glossary section](./lexicon.md).
```asciidoc
= Glossary
== Magic
Sufficiently advanced technology, beyond the understanding of the
observer producing a sense of wonder.
== PHP
A popular web programming language, used by many large websites such
as Facebook. Rasmus Lerdorf originally created PHP in 1994 to power
his personal homepage (PHP originally stood for "Personal Home Page"
but now stands for "PHP: Hypertext Preprocessor"). ```
+48
View File
@@ -0,0 +1,48 @@
# Configuration
GitBook allows you to customize your book using a flexible configuration. These options are specified in a `book.json` file. For authors unfamiliar with the JSON syntax, you can validate the syntax using tools such as [JSONlint](http://jsonlint.com).
### General Settings
| Variable | Description |
| -------- | ----------- |
| `root` | Path to the root folder containing all the book's files, except `book.json`|
| `title` | Title of your book, default value is extracted from the README. On GitBook.com this field is pre-filled. |
| `description` | Description of your book, default value is extracted from the README. On GitBook.com this field is pre-filled. |
| `author` | Name of the author. On GitBook.com this field is pre-filled. |
| `isbn` | ISBN of the book |
| `language` | [ISO code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) of the book's language, default value is `en` |
| `direction` | Text's direction. Can be `rtl` or `ltr`, the default value depends on the value of `language` |
| `gitbook` | Version of GitBook that should be used. Uses the [SemVer](http://semver.org) specification and accepts conditions like `">= 3.0.0"` |
### Plugins
Plugins and their configurations are specified in the `book.json`. See [the plugins section](plugins/README.md) for more details.
| Variable | Description |
| -------- | ----------- |
| `plugins` | List of plugins to load |
| `pluginsConfig` |Configuration for plugins |
### Theme
Since version 3.0.0, GitBook can use themes. See [the theming section](themes/README.md) for more details.
| Variable | Description |
| -------- | ----------- |
| `theme` | The theme to use for the book |
### PDF Options
PDF Output can be customized using a set of options in the `book.json`:
| Variable | Description |
| -------- | ----------- |
| `pdf.pageNumbers` | Add page numbers to the bottom of every page (default is `true`) |
| `pdf.fontSize` | Base font size (default is `12`) |
| `pdf.fontFamily` | Base font family (default is `Arial`) |
| `pdf.paperSize` | Paper size, options are `'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'legal', 'letter'` (default is `a4`) |
| `pdf.margin.top` | Top margin (default is `56`) |
| `pdf.margin.bottom` | Bottom margin (default is `56`) |
| `pdf.margin.right` | Right margin (default is `62`) |
| `pdf.margin.left` | Left margin (default is `62`) |
+21
View File
@@ -0,0 +1,21 @@
# Cover
Covers are used for all the ebook formats, and to make books more elegant on GitBook.com.
To provide a cover, place a **cover.jpg** file at the root directory of your book. Adding a **cover_small.jpg** will specify a smaller version of the cover. The cover should be a **JPEG** file.
### Best Sizes
| | Big | Small |
|:-------------------:|:-----------:|:-----------------:|
| **File** | `cover.jpg` | `cover_small.jpg` |
| **Size(in pixels)** | 1800x2360 | 200x262 |
### Guidelines
A good cover respects the following guidelines:
* No border
* Clearly visible book title
* Any important text should be visible in the small version
+27
View File
@@ -0,0 +1,27 @@
---
description: Real world examples of content published using GitBook.
---
# Examples
More than 50,000 books have been published on [GitBook.com](https://www.gitbook.com/explore).
### Books
- [Front-end Handbook](https://www.gitbook.com/book/frontendmasters/front-end-handbook/details) by [Cody Lindley](http://codylindley.com)
- [How to make an Operating System](https://www.gitbook.com/book/samypesse/how-to-create-an-operating-system/details) by [@SamyPesse](https://github.com/SamyPesse)
- [Building Web Apps with Go](https://www.gitbook.com/book/codegangsta/building-web-apps-with-go/details) by [@codegangsta](https://github.com/codegangsta)
- [Django Girls Tutorial](http://tutorial.djangogirls.org/en/index.html) by [Django Girls](https://djangogirls.org)
- [Linux Inside](https://www.gitbook.com/book/0xax/linux-insides/details) by [0xAX](https://twitter.com/0xAX)
- [Learn Javascript](https://www.gitbook.com/book/gitbookio/javascript/details) by [GitBook](https://twitter.com/GitbookIO)
### Research Papers
- [TowCenter Collection](https://www.gitbook.com/@towcenter) by [Columbia Journalism School](http://www.journalism.columbia.edu/)
- [Block Relaxation Algorithms in Statistics](https://www.gitbook.com/@jandeleeuw) by Jan de Leeuw
### Documentation
- [DuckDuckHack Documentation](http://docs.duckduckhack.com) by [DuckDuckGo](https://duckduckgo.com/about)
- This documentation
+33
View File
@@ -0,0 +1,33 @@
# GitBook FAQ
#### How can I host/publish my book?
Books can easily be published and hosted on [GitBook.com](https://www.gitbook.com). But GitBook output can be hosted on any static file hosting solution.
#### What can I use to edit my content?
Any text editor should work! But we advise using the [GitBook Editor](https://www.gitbook.com/editor). [GitBook.com](https://www.gitbook.com) also provides a web version of this editor.
---
#### Should I use an `.html` or `.md` extensions in my links?
You should always use paths and the `.md` extensions when linking to your files, GitBook will automatically replace these paths by the appropriate link when the pointing file is referenced in the Table of Contents.
#### Can I create a GitBook in a sub-directory of my repository?
Yes, GitBooks can be created in [sub-directories](structure.md#subdirectory). GitBook.com and the CLI also looks by default in a serie of [folders](structure.md).
---
#### Does GitBook support Math equations?
GitBook supports math equations and TeX thanks to plugins. There are currently 2 official plugins to display math: [mathjax](https://plugins.gitbook.com/plugin/mathjax) and [katex](https://plugins.gitbook.com/plugin/katex).
#### Can I customize/theme the output?
Yes, both the website and ebook outputs can be customized using [themes](themes/README.md).
#### Can I add interactive content (videos, etc)?
GitBook is very [extensible](plugins/README.md). You can use [existing plugins](https://plugins.gitbook.com) or create your own!
+17
View File
@@ -0,0 +1,17 @@
# Multi-Languages
GitBook supports building books written in multiple languages. Each language should be a sub-directory following the normal GitBook format, and a file named `LANGS.md` should be present at the root of the repository with the following format:
```markdown
# Languages
* [English](en/)
* [French](fr/)
* [Español](es/)
```
### Configuration for each language
When a language book (ex: `en`) has a `book.json`, its configuration will extend the main configuration.
The only exception is plugins, plugins are specified globally, and language specific plugins cannot be specified.
+14
View File
@@ -0,0 +1,14 @@
# Glossary
Allows you to specify terms and their respective definitions to be displayed as annotations. Based on those terms, GitBook will automatically build an index and highlight those terms in pages.
The `GLOSSARY.md` format is very simple :
```markdown
# Term
Definition for this term
# Another term
With it's definition, this can contain bold text
and all other kinds of inline markup ...
```
+80
View File
@@ -0,0 +1,80 @@
# Pages and Summary
### Summary
GitBook uses a `SUMMARY.md` file to define the structure of chapters and subchapters of the book. The `SUMMARY.md` file is used to generate the book's table of contents.
The format of `SUMMARY.md` is just a list of links. The link's title is used as the chapter's title, and the link's target is a path to that chapter's file.
Adding a nested list to a parent chapter will create subchapters.
##### Simple example
```markdown
# Summary
* [Part I](part1/README.md)
* [Writing is nice](part1/writing.md)
* [GitBook is nice](part1/gitbook.md)
* [Part II](part2/README.md)
* [We love feedback](part2/feedback_please.md)
* [Better tools for authors](part2/better_tools.md)
```
Each chapter has a dedicated page (`part#/README.md`) and is split into subchapters.
##### Example with subchapters split into parts
```markdown
# Summary
### Part I
* [Writing is nice](part1/writing.md)
* [GitBook is nice](part1/gitbook.md)
### Part II
* [We love feedback](part2/feedback_please.md)
* [Better tools for authors](part2/better_tools.md)
```
Here, parts are just groups of chapters and do not have dedicated pages, but will show in the navigation for example.
### Pages
#### Markdown syntax
Most of the files for GitBook use the Markdown syntax by default. GitBook infers your pages's structure from it. The syntax used is similar to the [GitHub Flavored Markdown syntax](https://guides.github.com/features/mastering-markdown/). One can also opt for the [AsciiDoc syntax](asciidoc.md).
##### Example of a chapter file
``` markdown
# Title of the chapter
This is a great introduction.
## Section 1
Markdown will dictates _most_ of your **book's structure**
## Section 2
...
```
#### Front Matter
Pages can contain an optional front matter. It can be used to define the page's description. The front matter must be the first thing in the file and must take the form of valid YAML set between triple-dashed lines. Here is a basic example:
```yaml
---
description: This is a short description of my page
---
# The content of my page
...
```
The front matter can define variables of your own, they will be added to the [page variable](templating/variables.md) so you can use them in your templating.
+28
View File
@@ -0,0 +1,28 @@
# Plugins
Plugins are the best way to extend GitBook functionalities (ebook and website). There exist plugins to do a lot of things: bring math formulas display support, track visits using Google Analytic, etc.
### How to find plugins?
Plugins can be easily searched on [plugins.gitbook.com](https://plugins.gitbook.com).
### How to install a plugin?
Once you find a plugin that you want to install, you need to add it to your `book.json`:
```
{
"plugins": ["myPlugin", "anotherPlugin"]
}
```
You can also specify a specific version using: `"myPlugin@0.3.1"`. By default GitBook will resolve the latest version of the plugin compatbile with the current GitBook version.
### GitBook.com
Plugins are automatically installed on [GitBook.com](https://www.gitbook.com). Locally, run `gitbook install` to install and prepare all plugins for your books.
### Configuring plugins
Plugins specific configurations are stored in `pluginsConfig`. You have to refer to the documentation of the plugin itself for details about the available options.
+63
View File
@@ -0,0 +1,63 @@
# Create and publish a plugin
A GitBook plugin is a node package published on NPM that follow a defined convention.
## Structure
#### package.json
The `package.json` is a manifest format for describing **Node.js modules**. GitBook plugins are built on top of Node modules. It declares dependencies, version, ownership, and other information required to run a plugin in GitBook. This document describes the schema in detail.
```
{
"name": "gitbook-plugin-mytest",
"version": "0.0.1",
"description": "This is my first GitBook plugin",
"engines": {
"gitbook": ">1.x.x"
}
}
```
You can learn more about `package.json` from the [NPM documentation](https://docs.npmjs.com/files/package.json).
The **package name** must begin with `gitbook-plugin-` and the **package engines** should contains `gitbook`.
#### index.js
The `index.js` is main entry point of your plugin runtime:
```js
module.exports = {
// Map of hooks
hooks: {},
// Map of new blocks
blocks: {},
// Map of new filters
filters: {}
};
```
## Publish your plugin
GitBook plugins can be published on [NPM](https://www.npmjs.com).
To publish a new plugin, you need to create an account on [npmjs.com](https://www.npmjs.com) then publish it from the command line:
```
$ npm publish
```
## Private plugins
Private plugins can be hosted on GitHub and included using `git` urls:
```
{
"plugins": [
"myplugin@git+https://github.com/MyCompany/mygitbookplugin.git#1.0.0"
]
}
```
+22
View File
@@ -0,0 +1,22 @@
# Testing your plugin
### Testing your plugin locally
Testing your plugin on your book before plushing it is possible using [npm link](https://docs.npmjs.com/cli/link).
In the plugin's folder, run:
```
$ npm link
```
The nin your book's folder:
```
$ npm link gitbook-plugin-<plugin's name>
```
### Unit testing on Travis
[gitbook-tester](https://github.com/todvora/gitbook-tester) makes it easy to write **Node.js/Mocha** unit tests for your plugins. Using [Travis.org](https://travis.org), tests can be run on each commits/tags.
+69
View File
@@ -0,0 +1,69 @@
# Setup and Installation of GitBook
Getting GitBook installed and ready-to-go should only take a few minutes.
### GitBook.com
[GitBook.com](https://www.gitbook.com) is an easy to use solution to write, publish and host books. It is the easiest solution for publishing your content and collaborating on it.
It integrates well with the [GitBook Editor](https://www.gitbook.com/editor).
### Local Installation
##### Requirements
Installing GitBook is easy and straightforward. Your system just needs to meet these two requirements:
* NodeJS (v4.0.0 and above are adviced)
* Windows, Linux, Unix, or Mac OS X
##### Install with NPM
The best way to install GitBook is via **NPM**. At the terminal prompt, simply run the following command to install GitBook:
```
$ npm install gitbook-cli -g
```
`gitbook-cli` is an utility to install and use multiple versions of GitBook on the same system. It will automatically install the required version of GitBook to build a book.
##### Create a book
GitBook can setup a boilerplate book:
```
$ gitbook init
```
If you wish to create the book into a new directory, you can do so by running `gitbook init ./directory`
Preview and serve your book using:
```
$ gitbook serve
```
Or build the static website using:
```
$ gitbook build
```
##### Install pre-releases
`gitbook-cli` makes it easy to download and install other versions of GitBook to test with your book:
```
$ gitbook fetch beta
```
Use `gitbook ls-remote` to list remote versions available for install.
##### Debugging
You can use the options `--log=debug` and `--debug` to get better error messages (with stack trace). For example:
```
$ gitbook build ./ --log=debug --debug
```
+66
View File
@@ -0,0 +1,66 @@
# Directory Structure
GitBook uses a simple directory structure. All Markdown/Asciidoc files listed in the [SUMMARY](pages.md) will be transformed as HTML. Multi-Lingual books have a slightly [different structure](languages.md).
A basic GitBook usually looks something like this:
```
.
├── book.json
├── README.md
├── SUMMARY.md
├── chapter-1/
| ├── README.md
| └── something.md
└── chapter-2/
├── README.md
└── something.md
```
An overview of what each of these does:
| File | Description |
| -------- | ----------- |
| `book.json` | Stores [configuration](config.md) data (__optional__) |
| `README.md` | Preface / Introduction for your book (**required**) |
| `SUMMARY.md` | Table of Contents (See [Pages](pages.md)) (__optional__) |
| `GLOSSARY.md` | Lexicon / List of terms to annotate (See [Glossary](lexicon.md)) (__optional__) |
### Static files and Images
A static file is a file that is not listed in the `SUMMARY.md`. All static files, unless [ignored](#ignore), are copied to the output.
### Ignoring files & folders {#ignore}
GitBook will read the `.gitignore`, `.bookignore` and `.ignore` files to get a list of files and folders to skip.
The format inside those files, follows the same convention as `.gitignore`:
```
# This is a comment
# Ignore the file test.md
test.md
# Ignore everything in the directory "bin"
bin/*
```
### Project integration with subdirectory {#subdirectory}
For software projects, you can use a subdirectory (like `docs/`) to store the book for the project's documentation. You can configure the [`root` option](config.md) to indicate the folder where GitBook can find the book's files:
```
.
├── book.json
└── docs/
├── README.md
└── SUMMARY.md
```
With `book.json` containing:
```
{
"root": "./docs"
}
```
+89
View File
@@ -0,0 +1,89 @@
# Templating
GitBook uses the [Nunjucks templating language](https://mozilla.github.io/nunjucks/) to process pages and theme's templates.
The Nunjucks syntax is very similar to **Jinja2** or **Liquid**. Its syntax uses surrounding braces `{ }` to mark content that needs to be processed.
### Variables
A variable looks up a value from the template context. If you wanted to simply display a variable, you would use the `{{ variable }}` syntax. For example :
```twig
My name is {{ name }}, nice to meet you
```
This looks up username from the context and displays it. Variable names can have dots in them which lookup properties, just like JavaScript. You can also use the square bracket syntax.
```twig
{{ foo.bar }}
{{ foo["bar"] }}
```
If a value is undefined, nothing is displayed. The following all output nothing if foo is undefined: `{{ foo }}`, `{{ foo.bar }}`, `{{ foo.bar.baz }}`.
GitBook provides a set of [predefined variables](variables.md) from the context.
### Filters
Filters are essentially functions that can be applied to variables. They are called with a pipe operator (`|`) and can take arguments.
```twig
{{ foo | title }}
{{ foo | join(",") }}
{{ foo | replace("foo", "bar") | capitalize }}
```
The third example shows how you can chain filters. It would display "Bar", by first replacing "foo" with "bar" and then capitalizing it.
### Tags
##### if
`if` tests a condition and lets you selectively display content. It behaves exactly as JavaScript's `if` behaves.
```twig
{% if variable %}
It is true
{% endif %}
```
If variable is defined and evaluates to true, "It is true" will be displayed. Otherwise, nothing will be.
You can specify alternate conditions with `elif` and `else`:
```twig
{% if hungry %}
I am hungry
{% elif tired %}
I am tired
{% else %}
I am good!
{% endif %}
```
##### for
`for` iterates over arrays and dictionaries.
```twig
# Chapters about GitBook
{% for article in glossary.terms['gitbook'].articles %}
* [{{ article.title }}]({{ article.path }})
{% endfor %}
```
##### set
`set` lets you create/modify a variable.
```twig
{% set softwareVersion = "1.0.0" %}
Current version is {{ softwareVersion }}.
[Download it](website.com/download/{{ softwareVersion }})
```
##### include and block
Inclusion and inheritance is detailled in the [Content References](conrefs.md) section.
+55
View File
@@ -0,0 +1,55 @@
# Content References
Content referencing (conref) is a convenient mechanism to reuse content from other files or books.
### Importing local files
Importing an other file's content is easy using the `include` tag:
```
{% include "./test.md" %}
```
### Importing file from another book
GitBook can also resolve the include path by using git:
```
{% include "git+https://github.com/GitbookIO/documentation.git/README.md#0.0.1" %}
```
The format of git url is:
```
git+https://user@hostname/owner/project.git/file#commit-ish
```
The real git url part should finish with `.git`, the filename to import is extracted after the `.git` till the fragment of the url.
The `commit-ish` can be any tag, sha, or branch which can be supplied as an argument to `git checkout`. The default is `master`.
### Inheritance
Template inheritance is a way to make it easy to reuse templates. When writing a template, you can define "blocks" that child templates can override. The inheritance chain can be as long as you like.
`block` defines a section on the template and identifies it with a name. Base templates can specify blocks and child templates can override them with new content.
```
{% extends "./mypage.md" %}
{% block pageContent %}
# This is my page content
{% endblock %}
```
In the file `mypage.md`, you should specify the blocks that can be extended:
```
{% block pageContent %}
This is the default content
{% endblock %}
# License
{% import "./LICENSE" %}
```
+64
View File
@@ -0,0 +1,64 @@
# Variables
The following is a reference of the available data during book's parsing and theme generation.
### Global Variables
| Variable | Description |
| -------- | ----------- |
| `book` | Book-wide information + configuration settings from `book.json`. See below for details. |
| `gitbook` | GitBook specific information |
| `page` | Current page specific information |
| `file` | File associated with the current page specific information |
| `summary` | Information about the table of contents |
| `languages` | List of languages for multi-lingual books |
| `config` | Dump of the `book.json` |
### Book Variables
| Variable | Description |
| -------- | ----------- |
| `book.[CONFIGURATION_DATA]` | All the `variables` set via the `book.json` are available through the book variable. |
| `book.language` | Current language for a multilingual book |
### GitBook Variables
| Variable | Description |
| -------- | ----------- |
| `gitbook.time` | The current time (when you run the `gitbook` command) . |
| `gitbook.version` | Version of GitBook used to generate the book |
### File Variables
| Variable | Description |
| -------- | ----------- |
| `file.path` | The path to the raw page |
| `file.mtime` | Modified Time. Last time the file was modified |
| `file.type` | The name of the parser used to compile this file (ex: `markdown`, `asciidoc`, etc) |
#### Page Variables
| Variable | Description |
| -------- | ----------- |
| `page.title` | Title of the page |
| `page.previous` | Previous page in the Table of Contents (can be `null`) |
| `page.next` | Next page in the Table of Contents (can be `null`) |
| `page.dir` | Text direction, based on configuration or detected from content (`rtl` or `ltr`) |
#### Table of Contents Variables
| Variable | Description |
| -------- | ----------- |
| `summary.parts` | List of sections in the Table of Contents |
The whole table of contents (`SUMMARY.md`) can be accessed:
`summary.parts[0].articles[0].title` will return the title of the first article.
#### Multi-lingual book Variable
| Variable | Description |
| -------- | ----------- |
| `languages.list` | List of languages for this book |
Languages are defined by `{ id: 'en', title: 'English' }`.
+26
View File
@@ -0,0 +1,26 @@
# Theming
Since version 3.0.0, GitBook can be easily themed. Books are using by default the [theme-default](https://github.com/GitbookIO/theme-default).
The theme to use is specified in the [book's configuration](config.md) using key `theme`.
> **Caution**: Custom theming can block some plugins from working correctly.
### Structure of a theme
A theme is a folder containing templates and assets. All the templates are optionnal, since theme are always extending the default theme.
| Folder | Description |
| -------- | ----------- |
| `_layouts` | Main folder containing all the templates |
| `_layouts/website/page.html` | Template for a normal page |
| `_layouts/ebook/page.html` | Template for a normal page during ebook generation (PDF< ePub, Mobi) |
### Extend/Customize theme in a book
Authors can extend the templates of a theme directly from the book source (without creating an external theme). Templates will be resolved in the `_layouts` folder of the book first, then in
### Publish a theme
Themes are published as plugins ([see related docs](../plugins/README.md)) with a `theme-` prefix. For example the theme `awesome` will be loaded from the `theme-awesome` plugin, and then from the `gitbook-plugin-theme-awesome` NPM package.
+69
View File
@@ -0,0 +1,69 @@
var _ = require('lodash');
function BackboneFile(book) {
if (!(this instanceof BackboneFile)) return new BackboneFile(book);
this.book = book;
this.log = this.book.log;
// Filename in the book
this.path = '';
this.parser;
_.bindAll(this);
}
// Type of the backbone file
BackboneFile.prototype.type = '';
// Parse a backbone file
BackboneFile.prototype.parse = function() {
// To be implemented by each child
};
// Handle case where file doesn't exists
BackboneFile.prototype.parseNotFound = function() {
};
// Return true if backbone file exists
BackboneFile.prototype.exists = function() {
return Boolean(this.path);
};
// Locate a backbone file, could be .md, .asciidoc, etc
BackboneFile.prototype.locate = function() {
var that = this;
var filename = this.book.config.getStructure(this.type, true);
this.log.debug.ln('locating', this.type, ':', filename);
return this.book.findParsableFile(filename)
.then(function(result) {
if (!result) return;
that.path = result.path;
that.parser = result.parser;
});
};
// Read and parse the file
BackboneFile.prototype.load = function() {
var that = this;
this.log.debug.ln('loading', this.type, ':', that.path);
return this.locate()
.then(function() {
if (!that.path) return that.parseNotFound();
that.log.debug.ln(that.type, 'located at', that.path);
return that.book.readFile(that.path)
// Parse it
.then(function(content) {
return that.parse(content);
});
});
};
module.exports = BackboneFile;
+99
View File
@@ -0,0 +1,99 @@
var _ = require('lodash');
var util = require('util');
var BackboneFile = require('./file');
// Normalize a glossary entry name into a unique id
function nameToId(name) {
return name.toLowerCase()
.replace(/[\/\\\?\%\*\:\;\|\"\'\\<\\>\#\$\(\)\!\.\@]/g, '')
.replace(/ /g, '_')
.trim();
}
/*
A glossary entry is represented by a name and a short description
An unique id for the entry is generated using its name
*/
function GlossaryEntry(name, description) {
if (!(this instanceof GlossaryEntry)) return new GlossaryEntry(name, description);
this.name = name;
this.description = description;
Object.defineProperty(this, 'id', {
get: _.bind(this.getId, this)
});
}
// Normalizes a glossary entry's name to create an ID
GlossaryEntry.prototype.getId = function() {
return nameToId(this.name);
};
/*
A glossary is a list of entries stored in a GLOSSARY.md file
*/
function Glossary() {
BackboneFile.apply(this, arguments);
this.entries = [];
}
util.inherits(Glossary, BackboneFile);
Glossary.prototype.type = 'glossary';
// Get templating context
Glossary.prototype.getContext = function() {
if (!this.path) return {};
return {
glossary: {
path: this.path
}
};
};
// Parse the readme content
Glossary.prototype.parse = function(content) {
var that = this;
return this.parser.glossary(content)
.then(function(entries) {
that.entries = _.map(entries, function(entry) {
return new GlossaryEntry(entry.name, entry.description);
});
});
};
// Return an entry by its id
Glossary.prototype.get = function(id) {
return _.find(this.entries, {
id: id
});
};
// Find an entry by its name
Glossary.prototype.find = function(name) {
return this.get(nameToId(name));
};
// Return false if glossary has entries (and exists)
Glossary.prototype.isEmpty = function(id) {
return _.size(this.entries) === 0;
};
// Convert the glossary to a list of annotations
Glossary.prototype.annotations = function() {
return _.map(this.entries, function(entry) {
return {
id: entry.id,
name: entry.name,
description: entry.description,
href: '/' + this.path + '#' + entry.id
};
}, this);
};
module.exports = Glossary;
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
Readme: require('./readme'),
Summary: require('./summary'),
Glossary: require('./glossary'),
Langs: require('./langs')
};
+81
View File
@@ -0,0 +1,81 @@
var _ = require('lodash');
var path = require('path');
var util = require('util');
var BackboneFile = require('./file');
function Language(title, folder) {
var that = this;
this.title = title;
this.folder = folder;
Object.defineProperty(this, 'id', {
get: function() {
return path.basename(that.folder);
}
});
}
/*
A Langs is a list of languages stored in a LANGS.md file
*/
function Langs() {
BackboneFile.apply(this, arguments);
this.languages = [];
}
util.inherits(Langs, BackboneFile);
Langs.prototype.type = 'langs';
// Parse the readme content
Langs.prototype.parse = function(content) {
var that = this;
return this.parser.langs(content)
.then(function(langs) {
that.languages = _.map(langs, function(entry) {
return new Language(entry.title, entry.path);
});
});
};
// Return the list of languages
Langs.prototype.list = function() {
return this.languages;
};
// Return default/main language for the book
Langs.prototype.getDefault = function() {
return _.first(this.languages);
};
// Return true if a language is the default one
// "lang" cam be a string (id) or a Language entry
Langs.prototype.isDefault = function(lang) {
lang = lang.id || lang;
return (this.cound() > 0 && this.getDefault().id == lang);
};
// Return the count of languages
Langs.prototype.count = function() {
return _.size(this.languages);
};
// Return templating context for the languages list
Langs.prototype.getContext = function() {
if (this.count() == 0) return {};
return {
languages: {
list: _.map(this.languages, function(lang) {
return {
id: lang.id,
title: lang.title
};
})
}
};
};
module.exports = Langs;
+26
View File
@@ -0,0 +1,26 @@
var util = require('util');
var BackboneFile = require('./file');
function Readme() {
BackboneFile.apply(this, arguments);
this.title;
this.description;
}
util.inherits(Readme, BackboneFile);
Readme.prototype.type = 'readme';
// Parse the readme content
Readme.prototype.parse = function(content) {
var that = this;
return this.parser.readme(content)
.then(function(out) {
that.title = out.title;
that.description = out.description;
});
};
module.exports = Readme;
+348
View File
@@ -0,0 +1,348 @@
var _ = require('lodash');
var util = require('util');
var location = require('../utils/location');
var error = require('../utils/error');
var BackboneFile = require('./file');
/*
An article represent an entry in the Summary.
It's defined by a title, a reference, and children articles,
the reference (ref) can be a filename + anchor or an external file (optional)
*/
function TOCArticle(def, parent) {
// Title
this.title = def.title;
// Parent TOCPart or TOCArticle
this.parent = parent;
// As string indicating the overall position
// ex: '1.0.0'
this.level;
this._next;
this._prev;
// When README has been automatically added
this.isAutoIntro = def.isAutoIntro;
this.isIntroduction = def.isIntroduction;
this.validate();
// Path can be a relative path or an url, or nothing
this.ref = def.path;
if (this.ref && !this.isExternal()) {
var parts = this.ref.split('#');
this.path = (parts.length > 1? parts.slice(0, -1).join('#') : this.ref);
this.anchor = (parts.length > 1? '#' + _.last(parts) : null);
// Normalize path to remove ('./', etc)
this.path = location.normalize(this.path);
}
this.articles = _.map(def.articles || [], function(article) {
if (article instanceof TOCArticle) return article;
return new TOCArticle(article, this);
}, this);
}
// Validate the article
TOCArticle.prototype.validate = function() {
if (!this.title) {
throw error.ParsingError(new Error('SUMMARY entries should have an non-empty title'));
}
};
// Iterate over all articles in this articles
TOCArticle.prototype.walk = function(iter, base) {
base = base || this.level;
_.each(this.articles, function(article, i) {
var level = levelId(base, i);
if (iter(article, level) === false) {
return false;
}
article.walk(iter, level);
});
};
// Return templating context for an article
TOCArticle.prototype.getContext = function() {
return {
level: this.level,
title: this.title,
depth: this.depth(),
path: this.isExternal()? undefined : this.path,
anchor: this.isExternal()? undefined : this.anchor,
url: this.isExternal()? this.ref : undefined
};
};
// Return true if is pointing to a file
TOCArticle.prototype.hasLocation = function() {
return Boolean(this.path);
};
// Return true if is pointing to an external location
TOCArticle.prototype.isExternal = function() {
return location.isExternal(this.ref);
};
// Return true if this article is the introduction
TOCArticle.prototype.isIntro = function() {
return Boolean(this.isIntroduction);
};
// Return true if has children
TOCArticle.prototype.hasChildren = function() {
return this.articles.length > 0;
};
// Return true if has an article as parent
TOCArticle.prototype.hasParent = function() {
return !(this.parent instanceof TOCPart);
};
// Return depth of this article
TOCArticle.prototype.depth = function() {
return this.level.split('.').length;
};
// Return next article in the TOC
TOCArticle.prototype.next = function() {
return this._next;
};
// Return previous article in the TOC
TOCArticle.prototype.prev = function() {
return this._prev;
};
// Map over all articles
TOCArticle.prototype.map = function(iter) {
return _.map(this.articles, iter);
};
/*
A part of a ToC is a composed of a tree of articles and an optiona title
*/
function TOCPart(part, parent) {
if (!(this instanceof TOCPart)) return new TOCPart(part, parent);
TOCArticle.apply(this, arguments);
}
util.inherits(TOCPart, TOCArticle);
// Validate the part
TOCPart.prototype.validate = function() { };
// Return a sibling (next or prev) of this part
TOCPart.prototype.sibling = function(direction) {
var parts = this.parent.parts;
var pos = _.findIndex(parts, this);
if (parts[pos + direction]) {
return parts[pos + direction];
}
return null;
};
// Iterate over all entries of the part
TOCPart.prototype.walk = function(iter, base) {
var articles = this.articles;
if (articles.length == 0) return;
// Has introduction?
if (articles[0].isIntro()) {
if (iter(articles[0], '0') === false) {
return;
}
articles = articles.slice(1);
}
_.each(articles, function(article, i) {
var level = levelId(base, i);
if (iter(article, level) === false) {
return false;
}
article.walk(iter, level);
});
};
// Return templating context for a part
TOCPart.prototype.getContext = function(onArticle) {
onArticle = onArticle || function(article) {
return article.getContext();
};
return {
title: this.title,
articles: this.map(onArticle)
};
};
/*
A summary is composed of a list of parts, each composed wit a tree of articles.
*/
function Summary() {
BackboneFile.apply(this, arguments);
this.parts = [];
this._length = 0;
}
util.inherits(Summary, BackboneFile);
Summary.prototype.type = 'summary';
// Prepare summary when non existant
Summary.prototype.parseNotFound = function() {
this.update([]);
};
// Parse the summary content
Summary.prototype.parse = function(content) {
var that = this;
return this.parser.summary(content)
.then(function(summary) {
that.update(summary.parts);
});
};
// Return templating context for the summary
Summary.prototype.getContext = function() {
function onArticle(article) {
var result = article.getContext();
if (article.hasChildren()) {
result.articles = article.map(onArticle);
}
return result;
}
return {
summary: {
parts: _.map(this.parts, function(part) {
return part.getContext(onArticle);
})
}
};
};
// Iterate over all entries of the summary
// iter is called with an TOCArticle
Summary.prototype.walk = function(iter) {
var hasMultipleParts = this.parts.length > 1;
_.each(this.parts, function(part, i) {
part.walk(iter, hasMultipleParts? levelId('', i) : null);
});
};
// Find a specific article using a filter
Summary.prototype.find = function(filter) {
var result;
this.walk(function(article) {
if (filter(article)) {
result = article;
return false;
}
});
return result;
};
// Flatten the list of articles
Summary.prototype.flatten = function() {
var result = [];
this.walk(function(article) {
result.push(article);
});
return result;
};
// Return the first TOCArticle for a specific page (or path)
Summary.prototype.getArticle = function(page) {
if (!_.isString(page)) page = page.path;
return this.find(function(article) {
return article.path == page;
});
};
// Return the first TOCArticle for a specific level
Summary.prototype.getArticleByLevel = function(lvl) {
return this.find(function(article) {
return article.level == lvl;
});
};
// Return the count of articles in the summary
Summary.prototype.count = function() {
return this._length;
};
// Prepare the summary
Summary.prototype.update = function(parts) {
var that = this;
that.parts = _.map(parts, function(part) {
return new TOCPart(part, that);
});
// Create first part if none
if (that.parts.length == 0) {
that.parts.push(new TOCPart({}, that));
}
// Add README as first entry
var firstArticle = that.parts[0].articles[0];
if (!firstArticle || firstArticle.path != that.book.readme.path) {
that.parts[0].articles.unshift(new TOCArticle({
title: 'Introduction',
path: that.book.readme.path,
isAutoIntro: true
}, that.parts[0]));
}
that.parts[0].articles[0].isIntroduction = true;
// Update the count and indexing of "level"
var prev = undefined;
that._length = 0;
that.walk(function(article, level) {
// Index level
article.level = level;
// Chain articles
article._prev = prev;
if (prev) prev._next = article;
prev = article;
that._length += 1;
});
};
// Return a level string from a base level and an index
function levelId(base, i) {
i = i + 1;
return (base? [base || '', i] : [i]).join('.');
}
module.exports = Summary;
+350 -741
View File
File diff suppressed because it is too large Load Diff
+140
View File
@@ -0,0 +1,140 @@
var _ = require('lodash');
var path = require('path');
var Book = require('../book');
var NodeFS = require('../fs/node');
var Logger = require('../utils/logger');
var Promise = require('../utils/promise');
var fs = require('../utils/fs');
var JSONOutput = require('../output/json');
var WebsiteOutput = require('../output/website');
var EBookOutput = require('../output/ebook');
var nodeFS = new NodeFS();
var LOG_OPTION = {
name: 'log',
description: 'Minimum log level to display',
values: _.chain(Logger.LEVELS)
.keys()
.map(function(s) {
return s.toLowerCase();
})
.value(),
defaults: 'info'
};
var FORMAT_OPTION = {
name: 'format',
description: 'Format to build to',
values: ['website', 'json', 'ebook'],
defaults: 'website'
};
var FORMATS = {
json: JSONOutput,
website: WebsiteOutput,
ebook: EBookOutput
};
// Commands which is processing a book
// the root of the book is the first argument (or current directory)
function bookCmd(fn) {
return function(args, kwargs) {
var input = path.resolve(args[0] || process.cwd());
var book = new Book({
fs: nodeFS,
root: input,
logLevel: kwargs.log
});
return fn(book, args.slice(1), kwargs);
};
}
// Commands which is working on a Output instance
function outputCmd(fn) {
return bookCmd(function(book, args, kwargs) {
var Out = FORMATS[kwargs.format];
var outputFolder = undefined;
// Set output folder
if (args[0]) {
outputFolder = path.resolve(process.cwd(), args[0]);
}
return fn(new Out(book, {
root: outputFolder
}), args);
});
}
// Command to generate an ebook
function ebookCmd(format) {
return {
name: format + ' [book] [output] [file]',
description: 'generates ebook '+format,
options: [
LOG_OPTION
],
exec: bookCmd(function(book, args, kwargs) {
return fs.tmpDir()
.then(function(dir) {
var ext = '.'+format;
var outputFile = path.resolve(process.cwd(), args[0] || ('book' + ext));
var output = new EBookOutput(book, {
root: dir,
format: format
});
return output.book.parse()
.then(function() {
return output.generate();
})
// Copy the ebook files
.then(function() {
if (output.book.isMultilingual()) {
return Promise.serie(output.book.langs.list(), function(lang) {
var _outputFile = path.join(
path.dirname(outputFile),
path.basename(outputFile, ext) + '_' + lang.id + ext
);
return fs.copy(
path.resolve(dir, lang.id, 'index' + ext),
_outputFile
);
})
.thenResolve(output.book.langs.count());
} else {
return fs.copy(
path.resolve(dir, 'index' + ext),
outputFile
).thenResolve(1);
}
})
.then(function(n) {
output.book.log.info.ok(n+' file(s) generated');
output.book.log.info('cleaning up... ');
return output.book.log.info.promise(fs.rmDir(dir));
});
});
})
};
}
module.exports = {
nodeFS: nodeFS,
bookCmd: bookCmd,
outputCmd: outputCmd,
ebookCmd: ebookCmd,
options: {
log: LOG_OPTION,
format: FORMAT_OPTION
},
FORMATS: FORMATS
};
+199
View File
@@ -0,0 +1,199 @@
/* eslint-disable no-console */
var _ = require('lodash');
var path = require('path');
var tinylr = require('tiny-lr');
var Promise = require('../utils/promise');
var PluginsManager = require('../plugins');
var Book = require('../book');
var helper = require('./helper');
var Server = require('./server');
var watch = require('./watch');
module.exports = {
commands: [
{
name: 'init [book]',
description: 'setup and create files for chapters',
options: [
helper.options.log
],
exec: function(args) {
var input = path.resolve(args[0] || process.cwd());
return Book.init(helper.nodeFS, input);
}
},
{
name: 'parse [book]',
description: 'parse and returns debug information for a book',
options: [
helper.options.log
],
exec: helper.bookCmd(function(book) {
return book.parse()
.then(function() {
book.log.info.ln('Book located in:', book.root);
book.log.info.ln('');
if (book.config.exists()) book.log.info.ln('Configuration:', book.config.path);
if (book.isMultilingual()) {
book.log.info.ln('Multilingual book detected:', book.langs.path);
} else {
book.log.info.ln('Readme:', book.readme.path);
book.log.info.ln('Summary:', book.summary.path);
if (book.glossary.exists()) book.log.info.ln('Glossary:', book.glossary.path);
book.log.info.ln('Pages:');
_.each(book.pages, function(page) {
book.log.info.ln('\t-', page.path);
});
}
});
})
},
{
name: 'install [book]',
description: 'install all plugins dependencies',
options: [
helper.options.log
],
exec: helper.bookCmd(function(book, args) {
var plugins = new PluginsManager(book);
return book.config.load()
.then(function() {
return plugins.install();
});
})
},
{
name: 'build [book] [output]',
description: 'build a book',
options: [
helper.options.log,
helper.options.format
],
exec: helper.outputCmd(function(output, args, kwargs) {
return output.book.parse()
.then(function() {
return output.generate();
});
})
},
helper.ebookCmd('pdf'),
helper.ebookCmd('epub'),
helper.ebookCmd('mobi'),
{
name: 'serve [book]',
description: 'Build then serve a book from a directory',
options: [
{
name: 'port',
description: 'Port for server to listen on',
defaults: 4000
},
{
name: 'lrport',
description: 'Port for livereload server to listen on',
defaults: 35729
},
{
name: 'watch',
description: 'Enable/disable file watcher',
defaults: true
},
helper.options.format,
helper.options.log
],
exec: function(args, kwargs) {
var input = path.resolve(args[0] || process.cwd());
var server = new Server();
// Init livereload server
var lrServer = tinylr({});
var port = kwargs.port;
var lrPath;
var generate = function() {
// Stop server if running
if (server.isRunning()) console.log('Stopping server');
return server.stop()
// Generate the book
.then(function() {
var book = new Book({
fs: helper.nodeFS,
root: input,
logLevel: kwargs.log
});
return book.parse()
.then(function() {
// Add livereload plugin
book.config.set('plugins',
book.config.get('plugins')
.concat([
{ name: 'livereload' }
])
);
var Out = helper.FORMATS[kwargs.format];
var output = new Out(book);
return output.generate()
.thenResolve(output);
});
})
// Start server and watch changes
.then(function(output) {
console.log();
console.log('Starting server ...');
return server.start(output.root(), port)
.then(function() {
console.log('Serving book on http://localhost:'+port);
if (lrPath) {
// trigger livereload
lrServer.changed({
body: {
files: [lrPath]
}
});
}
if (!kwargs.watch) return;
return watch(output.book.root)
.then(function(filepath) {
// set livereload path
lrPath = filepath;
console.log('Restart after change in file', filepath);
console.log('');
return generate();
});
});
});
};
return Promise.nfcall(lrServer.listen.bind(lrServer), kwargs.lrport)
.then(function() {
console.log('Live reload server started on port:', kwargs.lrport);
console.log('Press CTRL+C to quit ...');
console.log('');
return generate();
});
}
}
]
};
+13 -13
View File
@@ -1,12 +1,11 @@
var Q = require('q');
var _ = require('lodash');
var events = require('events');
var http = require('http');
var send = require('send');
var util = require('util');
var url = require('url');
var Promise = require('../utils/promise');
var Server = function() {
this.running = null;
this.dir = null;
@@ -17,18 +16,18 @@ util.inherits(Server, events.EventEmitter);
// Return true if the server is running
Server.prototype.isRunning = function() {
return this.running != null;
return !!this.running;
};
// Stop the server
Server.prototype.stop = function() {
var that = this;
if (!this.isRunning()) return Q();
if (!this.isRunning()) return Promise();
var d = Q.defer();
var d = Promise.defer();
this.running.close(function(err) {
that.running = null;
that.emit("state", false);
that.emit('state', false);
if (err) d.reject(err);
else d.resolve();
@@ -42,13 +41,13 @@ Server.prototype.stop = function() {
};
Server.prototype.start = function(dir, port) {
var that = this, pre = Q();
var that = this, pre = Promise();
port = port || 8004;
if (that.isRunning()) pre = this.stop();
return pre
.then(function() {
var d = Q.defer();
var d = Promise.defer();
that.running = http.createServer(function(req, res){
// Render error
@@ -65,8 +64,9 @@ Server.prototype.start = function(dir, port) {
}
// Send file
send(req, url.parse(req.url).pathname)
.root(dir)
send(req, url.parse(req.url).pathname, {
root: dir
})
.on('error', error)
.on('directory', redirect)
.pipe(res);
@@ -85,12 +85,12 @@ Server.prototype.start = function(dir, port) {
that.port = port;
that.dir = dir;
that.emit("state", true);
that.emit('state', true);
d.resolve();
});
return d.promise;
});
}
};
module.exports = Server;
+42
View File
@@ -0,0 +1,42 @@
var _ = require('lodash');
var path = require('path');
var chokidar = require('chokidar');
var Promise = require('../utils/promise');
var parsers = require('../parsers');
// Watch a folder and resolve promise once a file is modified
function watch(dir) {
var d = Promise.defer();
dir = path.resolve(dir);
var toWatch = [
'book.json', 'book.js'
];
// Watch all parsable files
_.each(parsers.extensions, function(ext) {
toWatch.push('**/*'+ext);
});
var watcher = chokidar.watch(toWatch, {
cwd: dir,
ignored: '_book/**',
ignoreInitial: true
});
watcher.once('all', function(e, filepath) {
watcher.close();
d.resolve(filepath);
});
watcher.once('error', function(err) {
watcher.close();
d.reject(err);
});
return d.promise;
}
module.exports = watch;
+132
View File
@@ -0,0 +1,132 @@
var _ = require('lodash');
var semver = require('semver');
var gitbook = require('../gitbook');
var Promise = require('../utils/promise');
var validator = require('./validator');
var plugins = require('./plugins');
// Config files to tested (sorted)
var CONFIG_FILES = [
'book.js',
'book.json'
];
/*
Config is an interface for the book's configuration stored in "book.json" (or "book.js")
*/
function Config(book, baseConfig) {
this.book = book;
this.fs = book.fs;
this.log = book.log;
this.path = '';
this.baseConfig = baseConfig || {};
this.replace({});
}
// Load configuration of the book
// and verify that the configuration is satisfying
Config.prototype.load = function() {
var that = this;
var isLanguageBook = this.book.isLanguageBook();
// Try all potential configuration file
return Promise.some(CONFIG_FILES, function(filename) {
that.log.debug.ln('try loading configuration from', filename);
return that.fs.loadAsObject(that.book.resolve(filename))
.then(function(_config) {
that.log.debug.ln('configuration loaded from', filename);
that.path = filename;
return that.replace(_config);
})
.fail(function(err) {
if (err.code != 'MODULE_NOT_FOUND') throw(err);
else return Promise(false);
});
})
.then(function() {
if (!isLanguageBook) {
if (!gitbook.satisfies(that.options.gitbook)) {
throw new Error('GitBook version doesn\'t satisfy version required by the book: '+that.options.gitbook);
}
if (that.options.gitbook != '*' && !semver.satisfies(semver.inc(gitbook.version, 'patch'), that.options.gitbook)) {
that.log.warn.ln('gitbook version specified in your book.json might be too strict for future patches, \''+(_.first(gitbook.version.split('.'))+'.x.x')+'\' is more adequate');
}
that.options.plugins = plugins.toList(that.options.plugins);
} else {
// Multilingual book should inherits the plugins list from parent
that.options.plugins = that.book.parent.config.get('plugins');
}
that.options.gitbook = gitbook.version;
});
};
// Replace the whole configuration
Config.prototype.replace = function(options) {
var that = this;
// Extend base config
options = _.defaults(_.cloneDeep(options), this.baseConfig);
// Validate the config
this.options = validator.validate(options);
// options.input == book.root
Object.defineProperty(this.options, 'input', {
get: function () {
return that.book.root;
}
});
// options.originalInput == book.parent.root
Object.defineProperty(this.options, 'originalInput', {
get: function () {
return that.book.parent? that.book.parent.root : undefined;
}
});
};
// Return true if book has a configuration file
Config.prototype.exists = function() {
return Boolean(this.path);
};
// Return path to a structure file
// Strip the extension by default
Config.prototype.getStructure = function(name, dontStripExt) {
var filename = this.options.structure[name];
if (dontStripExt) return filename;
filename = filename.split('.').slice(0, -1).join('.');
return filename;
};
// Return a configuration using a key and a default value
Config.prototype.get = function(key, def) {
return _.get(this.options, key, def);
};
// Update a configuration
Config.prototype.set = function(key, value) {
return _.set(this.options, key, value);
};
// Return a dump of the configuration
Config.prototype.dump = function() {
return _.cloneDeep(this.options);
};
// Return templating context
Config.prototype.getContext = function() {
return {
config: this.book.config.dump()
};
};
module.exports = Config;
+67
View File
@@ -0,0 +1,67 @@
var _ = require('lodash');
// Default plugins added to each books
var DEFAULT_PLUGINS = ['highlight', 'search', 'sharing', 'fontsettings', 'theme-default'];
// Return true if a plugin is a default plugin
function isDefaultPlugin(name, version) {
return _.contains(DEFAULT_PLUGINS, name);
}
// Normalize a list of plugins to use
function normalizePluginsList(plugins) {
// Normalize list to an array
plugins = _.isString(plugins) ? plugins.split(',') : (plugins || []);
// Remove empty parts
plugins = _.compact(plugins);
// Divide as {name, version} to handle format like 'myplugin@1.0.0'
plugins = _.map(plugins, function(plugin) {
if (plugin.name) return plugin;
var parts = plugin.split('@');
var name = parts[0];
var version = parts[1];
return {
'name': name,
'version': version // optional
};
});
// List plugins to remove
var toremove = _.chain(plugins)
.filter(function(plugin) {
return plugin.name.length > 0 && plugin.name[0] == '-';
})
.map(function(plugin) {
return plugin.name.slice(1);
})
.value();
// Merge with defaults
_.each(DEFAULT_PLUGINS, function(plugin) {
if (_.find(plugins, { name: plugin })) {
return;
}
plugins.push({
'name': plugin
});
});
// Remove plugin that start with '-'
plugins = _.filter(plugins, function(plugin) {
return !_.contains(toremove, plugin.name) && !(plugin.name.length > 0 && plugin.name[0] == '-');
});
// Remove duplicates
plugins = _.uniq(plugins, 'name');
return plugins;
}
module.exports = {
isDefaultPlugin: isDefaultPlugin,
toList: normalizePluginsList
};
+188
View File
@@ -0,0 +1,188 @@
module.exports = {
'$schema': 'http://json-schema.org/schema#',
'id': 'https://gitbook.com/schemas/book.json',
'title': 'GitBook Configuration',
'type': 'object',
'properties': {
'root': {
'type': 'string',
'title': 'Path fro the root folder containing the book\'s content'
},
'title': {
'type': 'string',
'title': 'Title of the book, default is extracted from README'
},
'isbn': {
'type': 'string',
'title': 'ISBN for published book'
},
'author': {
'type': 'string',
'title': 'Name of the author'
},
'gitbook': {
'type': 'string',
'default': '*',
'title': 'GitBook version to match'
},
'direction': {
'type': 'string',
'enum': ['ltr', 'rtl'],
'title': 'Direction of texts, default is detected in the pages'
},
'theme': {
'type': 'string',
'default': 'default',
'title': 'Name of the theme plugin to use'
},
'variables': {
'type': 'object',
'title': 'Templating context variables'
},
'plugins': {
'oneOf': [
{ '$ref': '#/definitions/pluginsArray' },
{ '$ref': '#/definitions/pluginsString' }
],
'default': []
},
'pluginsConfig': {
'type': 'object',
'title': 'Configuration for plugins'
},
'structure': {
'type': 'object',
'properties': {
'langs': {
'default': 'LANGS.md',
'type': 'string',
'title': 'File to use as languages index',
'pattern': '^[0-9a-zA-Z ... ]+$'
},
'readme': {
'default': 'README.md',
'type': 'string',
'title': 'File to use as preface',
'pattern': '^[0-9a-zA-Z ... ]+$'
},
'glossary': {
'default': 'GLOSSARY.md',
'type': 'string',
'title': 'File to use as glossary index',
'pattern': '^[0-9a-zA-Z ... ]+$'
},
'summary': {
'default': 'SUMMARY.md',
'type': 'string',
'title': 'File to use as table of contents',
'pattern': '^[0-9a-zA-Z ... ]+$'
}
},
'additionalProperties': false
},
'pdf': {
'type': 'object',
'title': 'PDF specific configurations',
'properties': {
'pageNumbers': {
'type': 'boolean',
'default': true,
'title': 'Add page numbers to the bottom of every page'
},
'fontSize': {
'type': 'integer',
'minimum': 8,
'maximum': 30,
'default': 12,
'title': 'Font size for the PDF output'
},
'fontFamily': {
'type': 'string',
'default': 'Arial',
'title': 'Font family for the PDF output'
},
'paperSize': {
'type': 'string',
'enum': ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'legal', 'letter'],
'default': 'a4',
'title': 'Paper size for the PDF'
},
'chapterMark': {
'type': 'string',
'enum': ['pagebreak', 'rule', 'both', 'none'],
'default': 'pagebreak',
'title': 'How to mark detected chapters'
},
'pageBreaksBefore': {
'type': 'string',
'default': '/',
'title': 'An XPath expression. Page breaks are inserted before the specified elements. To disable use the expression: "/"'
},
'margin': {
'type': 'object',
'properties': {
'right': {
'type': 'integer',
'title': 'Right Margin',
'minimum': 0,
'maximum': 100,
'default': 62
},
'left': {
'type': 'integer',
'title': 'Left Margin',
'minimum': 0,
'maximum': 100,
'default': 62
},
'top': {
'type': 'integer',
'title': 'Top Margin',
'minimum': 0,
'maximum': 100,
'default': 56
},
'bottom': {
'type': 'integer',
'title': 'Bottom Margin',
'minimum': 0,
'maximum': 100,
'default': 56
}
}
}
}
}
},
'required': [],
'definitions': {
'pluginsArray': {
'type': 'array',
'items': {
'oneOf': [
{ '$ref': '#/definitions/pluginObject' },
{ '$ref': '#/definitions/pluginString' }
]
}
},
'pluginsString': {
'type': 'string'
},
'pluginString': {
'type': 'string'
},
'pluginObject': {
'type': 'object',
'properties': {
'name': {
'type': 'string'
},
'version': {
'type': 'string'
}
},
'additionalProperties': false,
'required': ['name']
}
}
};
+28
View File
@@ -0,0 +1,28 @@
var jsonschema = require('jsonschema');
var jsonSchemaDefaults = require('json-schema-defaults');
var mergeDefaults = require('merge-defaults');
var schema = require('./schema');
var error = require('../utils/error');
// Validate a book.json content
// And return a mix with the default value
function validate(bookJson) {
var v = new jsonschema.Validator();
var result = v.validate(bookJson, schema, {
propertyName: 'config'
});
// Throw error
if (result.errors.length > 0) {
throw new error.ConfigurationError(new Error(result.errors[0].stack));
}
// Insert default values
var defaults = jsonSchemaDefaults(schema);
return mergeDefaults(bookJson, defaults);
}
module.exports = {
validate: validate
};
-235
View File
@@ -1,235 +0,0 @@
var _ = require("lodash");
var Q = require("q");
var path = require("path");
var semver = require('semver');
var pkg = require('../package.json');
var fs = require("./utils/fs");
var i18n = require("./utils/i18n");
// Default plugins added to each books
var defaultsPlugins = [];
// Normalize a list of plugins to use
function normalizePluginsList(plugins) {
// Normalize list to an array
plugins = _.isString(plugins) ? plugins.split(",") : (plugins || []);
// Remove empty parts
plugins = _.compact(plugins);
// Divide as {name, version} to handle format like "myplugin@1.0.0"
plugins = _.map(plugins, function(plugin) {
if (plugin.name) return plugin;
var parts = plugin.split("@");
return {
'name': parts[0],
'version': parts[1] // optional
}
});
// List plugins to remove
var toremove = _.chain(plugins)
.filter(function(plugin) {
return plugin.name.length > 0 && plugin.name[0] == "-";
})
.map(function(plugin) {
return plugin.name.slice(1);
})
.value();
// Merge with defaults
plugins = _.chain(plugins)
.concat(_.map(defaultsPlugins, function(plugin) {
return { 'name': plugin }
}))
.uniq()
.value();
// Build final list
plugins = _.filter(plugins, function(plugin) {
return !_.contains(toremove, plugin.name) && !(plugin.name.length > 0 && plugin.name[0] == "-");
});
return plugins;
}
// Normalize a list of plugin name to use
function normalizePluginsNames(plugins) {
return _.pluck(normalizePluginsList(plugins), "name");
};
var Configuration = function(book, options) {
var that = this;
this.book = book;
this.options = _.cloneDeep(Configuration.DEFAULT);
this.options = _.merge(this.options, options || {});
// options.input == book.root
Object.defineProperty(this.options, "input", {
get: function () {
return that.book.root;
}
});
};
// Read and parse the configuration
Configuration.prototype.load = function() {
var that = this;
return Q()
.then(function() {
try {
var _config = require(path.resolve(that.book.root, that.options.configFile));
that.options = _.merge(
that.options,
_.omit(_config, 'configFile', 'defaultsPlugins', 'generator', 'extension')
);
}
catch(err) {
if (err instanceof SyntaxError) return Q.reject(err);
return Q();
}
})
.then(function() {
that.options.output = path.resolve(that.options.output || path.join(that.book.root, "_book"));
that.options.plugins = normalizePluginsList(that.options.plugins);
that.options.defaultsPlugins = normalizePluginsList(that.options.defaultsPlugins || "");
that.options.plugins = _.union(that.options.plugins, that.options.defaultsPlugins);
that.options.plugins = _.uniq(that.options.plugins, "name");
if (!semver.satisfies(pkg.version, that.options.gitbook)) {
throw "GitBook version doesn't satisfy version required by the book: "+that.options.gitbook;
}
if (that.options.gitbook == "*") {
that.book.log.warn.ln("you should specify a gitbook version to use in your book.json, for example: "+(_.first(pkg.version.split("."))+".x.x"));
}
that.options.gitbook = pkg.version;
});
};
// Extend the configuration
Configuration.prototype.extend = function(options) {
_.extend(this.options, options);
};
// Get structure file
Configuration.prototype.getStructure = function(name) {
return this.options.structure[name].split(".").slice(0, -1).join(".");
};
// Return normalized language
Configuration.prototype.normalizeLanguage = function() {
return i18n.normalizeLanguage(this.options.language);
};
// Default configuration
Configuration.DEFAULT = {
// Options that can't be extend
"configFile": "book",
"generator": "site",
"extension": null,
// Book metadats (somes are extracted from the README by default)
"title": null,
"description": null,
"isbn": null,
"language": "en",
// version of gitbook to use
"gitbook": "*",
// Structure
"structure": {
"langs": "LANGS.md",
"readme": "README.md",
"glossary": "GLOSSARY.md",
"summary": "SUMMARY.md"
},
// CSS Styles
"styles": {
"website": "styles/website.css",
"ebook": "styles/ebook.css",
"pdf": "styles/pdf.css",
"mobi": "styles/mobi.css",
"epub": "styles/epub.css"
},
// Plugins list, can contain "-name" for removing default plugins
"plugins": [],
// Global configuration for plugins
"pluginsConfig": {
"fontSettings": {
"theme": null, //"sepia", "night" or "white",
"family": "sans",// "serif" or "sans",
"size": 2 // 1 - 4
}
},
// Variables for templating
"variables": {},
// Set another theme with your own layout
// It's recommended to use plugins or add more options for default theme, though
// See https://github.com/GitbookIO/gitbook/issues/209
"theme": path.resolve(__dirname, '../theme'),
// Links in template (null: default, false: remove, string: new value)
"links": {
// Custom links at top of sidebar
"sidebar": {
//"Custom link name": "https://customlink.com"
},
// Sharing links
"sharing": {
"google": null,
"facebook": null,
"twitter": null,
"weibo": null,
"all": null
}
},
// Options for PDF generation
"pdf": {
// Add toc at the end of the file
"toc": true,
// Add page numbers to the bottom of every page
"pageNumbers": false,
// Font size for the file content
"fontSize": 12,
// Paper size for the pdf
// Choices are [ua0, ua1, ua2, ua3, ua4, ua5, ua6, ub0, ub1, ub2, ub3, ub4, ub5, ub6, ulegal, uletter]
"paperSize": "a4",
// Margin (in pts)
// Note: 72 pts equals 1 inch
"margin": {
"right": 62,
"left": 62,
"top": 56,
"bottom": 56
},
//Header HTML template. Available variables: _PAGENUM_, _TITLE_, _AUTHOR_ and _SECTION_.
"headerTemplate": "",
//Footer HTML template. Available variables: _PAGENUM_, _TITLE_, _AUTHOR_ and _SECTION_.
"footerTemplate": ""
}
};
module.exports= Configuration;
+106
View File
@@ -0,0 +1,106 @@
var _ = require('lodash');
var path = require('path');
var Promise = require('../utils/promise');
/*
A filesystem is an interface to read files
GitBook can works with a virtual filesystem, for example in the browser.
*/
// .readdir return files/folder as a list of string, folder ending with '/'
function pathIsFolder(filename) {
return _.last(filename) == '/' || _.last(filename) == '\\';
}
function FS() {
}
// Check if a file exists, run a Promise(true) if that's the case, Promise(false) otherwise
FS.prototype.exists = function(filename) {
// To implement for each fs
};
// Read a file and returns a promise with the content as a buffer
FS.prototype.read = function(filename) {
// To implement for each fs
};
// Read stat infos about a file
FS.prototype.stat = function(filename) {
// To implement for each fs
};
// List files/directories in a directory
FS.prototype.readdir = function(folder) {
// To implement for each fs
};
// These methods don't require to be redefined, by default it uses .exists, .read, .write, .list
// For optmization, it can be redefined:
// List files in a directory
FS.prototype.listFiles = function(folder) {
return this.readdir(folder)
.then(function(files) {
return _.reject(files, pathIsFolder);
});
};
// List all files in the fs
FS.prototype.listAllFiles = function(folder) {
var that = this;
return this.readdir(folder)
.then(function(files) {
return _.reduce(files, function(prev, file) {
return prev.then(function(output) {
var isDirectory = pathIsFolder(file);
if (!isDirectory) {
output.push(file);
return output;
} else {
return that.listAllFiles(path.join(folder, file))
.then(function(files) {
return output.concat(_.map(files, function(_file) {
return path.join(file, _file);
}));
});
}
});
}, Promise([]));
});
};
// Read a file as a string (utf-8)
FS.prototype.readAsString = function(filename) {
return this.read(filename)
.then(function(buf) {
return buf.toString('utf-8');
});
};
// Find a file in a folder (case incensitive)
// Return the real filename
FS.prototype.findFile = function findFile(root, filename) {
return this.listFiles(root)
.then(function(files) {
return _.find(files, function(file) {
return (file.toLowerCase() == filename.toLowerCase());
});
});
};
// Load a JSON file
// By default, fs only supports JSON
FS.prototype.loadAsObject = function(filename) {
return this.readAsString(filename)
.then(function(str) {
return JSON.parse(str);
});
};
module.exports = FS;
+66
View File
@@ -0,0 +1,66 @@
var _ = require('lodash');
var util = require('util');
var path = require('path');
var fs = require('../utils/fs');
var Promise = require('../utils/promise');
var BaseFS = require('./');
function NodeFS() {
BaseFS.call(this);
}
util.inherits(NodeFS, BaseFS);
// Check if a file exists, run a Promise(true) if that's the case, Promise(false) otherwise
NodeFS.prototype.exists = function(filename) {
return fs.exists(filename);
};
// Read a file and returns a promise with the content as a buffer
NodeFS.prototype.read = function(filename) {
return fs.readFile(filename);
};
// Read stat infos about a file
NodeFS.prototype.stat = function(filename) {
return fs.stat(filename);
};
// List files in a directory
NodeFS.prototype.readdir = function(folder) {
return fs.readdir(folder)
.then(function(files) {
return _.chain(files)
.map(function(file) {
if (file == '.' || file == '..') return;
var stat = fs.statSync(path.join(folder, file));
if (stat.isDirectory()) file = file + path.sep;
return file;
})
.compact()
.value();
});
};
// Load a JSON/JS file
NodeFS.prototype.loadAsObject = function(filename) {
return Promise()
.then(function() {
var jsFile;
try {
jsFile = require.resolve(filename);
// Invalidate node.js cache for livreloading
delete require.cache[jsFile];
return require(jsFile);
}
catch(err) {
return Promise.reject(err);
}
});
};
module.exports = NodeFS;
-78
View File
@@ -1,78 +0,0 @@
var _ = require("lodash");
var path = require("path");
var Q = require("q");
var fs = require("./utils/fs");
var Plugin = require("./plugin");
var BaseGenerator = function(book) {
this.book = book;
Object.defineProperty(this, "options", {
get: function () {
return this.book.options;
}
});
_.bindAll(this);
};
BaseGenerator.prototype.callHook = function(name, data) {
return this.book.plugins.hook(name, data);
};
// Prepare the genertor
BaseGenerator.prototype.prepare = function() {
var that = this;
return that.callHook("init");
};
// Write a parsed file to the output
BaseGenerator.prototype.convertFile = function(input) {
return Q.reject(new Error("Could not convert "+input));
};
// Copy file to the output (non parsable)
BaseGenerator.prototype.transferFile = function(input) {
return fs.copy(
path.join(this.book.root, input),
path.join(this.options.output, input)
);
};
// Copy a folder to the output
BaseGenerator.prototype.transferFolder = function(input) {
return fs.mkdirp(
path.join(this.book.options.output, input)
);
};
// Copy the cover picture
BaseGenerator.prototype.copyCover = function() {
var that = this;
return Q.all([
fs.copy(path.join(that.book.root, "cover.jpg"), path.join(that.options.output, "cover.jpg")),
fs.copy(path.join(that.book.root, "cover_small.jpg"), path.join(that.options.output, "cover_small.jpg"))
])
.fail(function() {
// If orignaly from multi-lang, try copy from parent
if (!that.book.isSubBook()) return;
return Q.all([
fs.copy(path.join(that.book.parentRoot(), "cover.jpg"), path.join(that.options.output, "cover.jpg")),
fs.copy(path.join(that.book.parentRoot(), "cover_small.jpg"), path.join(that.options.output, "cover_small.jpg"))
]);
})
.fail(function(err) {
return Q();
});
};
// At teh end of the generation
BaseGenerator.prototype.finish = function() {
return Q.reject(new Error("Could not finish generation"));
};
module.exports = BaseGenerator;
-132
View File
@@ -1,132 +0,0 @@
var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;
var fs = require("../utils/fs");
var stringUtils = require("../utils/string");
var BaseGenerator = require("./website");
var Generator = function(book, format) {
BaseGenerator.apply(this, arguments);
// eBook format
this.ebookFormat = format;
// Resources namespace
this.namespace = "ebook";
// Styles to use
this.styles = _.compact(["ebook", this.ebookFormat]);
// Convert images (svg -> png)
this.convertImages = true;
};
util.inherits(Generator, BaseGenerator);
Generator.prototype.prepareTemplates = function() {
this.templates["page"] = this.book.plugins.template("ebook:page") || path.resolve(this.options.theme, 'templates/ebook/page.html');
this.templates["summary"] = this.book.plugins.template("ebook:summary") || path.resolve(this.options.theme, 'templates/ebook/summary.html');
this.templates["glossary"] = this.book.plugins.template("ebook:glossary") || path.resolve(this.options.theme, 'templates/ebook/glossary.html');
return Q();
};
// Generate table of contents
Generator.prototype.writeSummary = function() {
var that = this;
that.book.log.info.ln("write SUMMARY.html");
return this._writeTemplate(this.templates["summary"], {}, path.join(this.options.output, "SUMMARY.html"));
};
Generator.prototype.finish = function() {
var that = this;
return BaseGenerator.prototype.finish.apply(this)
.then(function() {
return that.writeSummary();
})
.then(function() {
if (!that.ebookFormat) return Q();
var d = Q.defer();
if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) {
that.options.cover = path.join(that.options.output, "cover.jpg");
}
var _options = {
"--cover": that.options.cover,
"--title": that.options.title,
"--comments": that.options.description,
"--isbn": that.options.isbn,
"--authors": that.options.author,
"--publisher": "GitBook",
"--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]",
"--chapter-mark": "pagebreak",
"--page-breaks-before": "/",
"--level1-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-1 ')]",
"--level2-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-2 ')]",
"--level3-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-3 ')]",
"--no-chapters-in-toc": true,
"--max-levels": "1",
"--breadth-first": true
};
if (that.ebookFormat == "pdf") {
var pdfOptions = that.options.pdf;
_.extend(_options, {
"--margin-left": String(pdfOptions.margin.left),
"--margin-right": String(pdfOptions.margin.right),
"--margin-top": String(pdfOptions.margin.top),
"--margin-bottom": String(pdfOptions.margin.bottom),
"--pdf-default-font-size": String(pdfOptions.fontSize),
"--pdf-mono-font-size": String(pdfOptions.fontSize),
"--paper-size": String(pdfOptions.paperSize),
"--pdf-page-numbers": Boolean(pdfOptions.pageNumbers),
"--pdf-header-template": String(pdfOptions.headerTemplate) || "<p class='header'><span>"+that.options.title+"</span></p>",
"--pdf-footer-template": String(pdfOptions.footerTemplate) || "<p class='footer'><span>_SECTION_</span> <span style='float:right;'>_PAGENUM_</span></p>"
});
}
var command = [
"ebook-convert",
path.join(that.options.output, "SUMMARY.html"),
path.join(that.options.output, "index."+that.ebookFormat),
stringUtils.optionsToShellArgs(_options)
].join(" ");
that.book.log.info("start conversion to", that.ebookFormat, "....");
var child = exec(command, function (error, stdout, stderr) {
if (error) {
that.book.log.info.fail();
if (error.code == 127) {
error.message = "Need to install ebook-convert from Calibre";
} else {
error.message = error.message + " "+stdout;
}
return d.reject(error);
}
that.book.log.info.ok();
d.resolve();
});
child.stdout.on('data', function (data) {
that.book.log.debug(data);
});
child.stderr.on('data', function (data) {
that.book.log.debug(data);
});
return d.promise;
});
};
module.exports = Generator;
-11
View File
@@ -1,11 +0,0 @@
var _ = require("lodash");
var EbookGenerator = require("./ebook");
module.exports = {
json: require("./json"),
website: require("./website"),
ebook: EbookGenerator,
pdf: _.partialRight(EbookGenerator, "pdf"),
mobi: _.partialRight(EbookGenerator, "mobi"),
epub: _.partialRight(EbookGenerator, "epub")
};
-76
View File
@@ -1,76 +0,0 @@
var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var fs = require("../utils/fs");
var BaseGenerator = require("../generator");
var links = require("../utils/links");
var Generator = function() {
BaseGenerator.apply(this, arguments);
};
util.inherits(Generator, BaseGenerator);
// Ignore some methods
Generator.prototype.transferFile = function(input) { };
// Convert an input file
Generator.prototype.convertFile = function(input) {
var that = this;
return that.book.parsePage(input)
.then(function(page) {
var json = {
progress: page.progress,
sections: page.sections
};
var output = links.changeExtension(page.path, ".json");
output = path.join(that.options.output, output);
return fs.writeFile(
output,
JSON.stringify(json, null, 4)
);
});
};
// Finish generation
Generator.prototype.finish = function() {
return this.writeReadme();
};
// Write README.json
Generator.prototype.writeReadme = function() {
var that = this;
var mainlang, langs;
return Q()
.then(function() {
langs = that.book.langs;
mainLang = langs.length > 0? _.first(langs).lang : null;
readme = links.changeExtension(that.book.readmeFile, ".json");
// Read readme from main language
return fs.readFile(
mainLang? path.join(that.options.output, mainLang, readme) : path.join(that.options.output, readme)
);
})
.then(function(content) {
// Extend it with infos about the languages
var json = JSON.parse(content);
_.extend(json, {
langs: langs
});
// Write it as README.json
return fs.writeFile(
path.join(that.options.output, "README.json"),
JSON.stringify(json, null, 4)
);
});
};
module.exports = Generator;
-279
View File
@@ -1,279 +0,0 @@
var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var nunjucks = require("nunjucks");
var AutoEscapeExtension = require("nunjucks-autoescape");
var FilterExtension = require("nunjucks-filter");
var I18nExtension = require("nunjucks-i18n");
var fs = require("../utils/fs");
var BaseGenerator = require("../generator");
var links = require("../utils/links");
var pageUtil = require("../utils/page");
var i18n = require("../utils/i18n");
var pkg = require("../../package.json");
var Generator = function() {
BaseGenerator.apply(this, arguments);
// Revision
this.revision = new Date();
// Resources namespace
this.namespace = "website";
// Style to integrates in the output
this.styles = ["website"];
// Convert images (svg -> png)
this.convertImages = false;
// Templates
this.templates = {};
};
util.inherits(Generator, BaseGenerator);
// Prepare the genertor
Generator.prototype.prepare = function() {
return BaseGenerator.prototype.prepare.apply(this)
.then(this.prepareStyles)
.then(this.prepareTemplates)
.then(this.prepareTemplateEngine);
};
// Prepare all styles
Generator.prototype.prepareStyles = function() {
var that = this;
this.styles = _.chain(this.styles)
.map(function(style) {
var stylePath = that.options.styles[style];
if (fs.existsSync(path.resolve(that.book.root, stylePath))) {
return stylePath;
}
return null;
})
.compact()
.value();
return Q();
};
// Prepare templates
Generator.prototype.prepareTemplates = function() {
this.templates["page"] = this.book.plugins.template("site:page") || path.resolve(this.options.theme, 'templates/website/page.html');
this.templates["langs"] = this.book.plugins.template("site:langs") || path.resolve(this.options.theme, 'templates/website/langs.html');
this.templates["glossary"] = this.book.plugins.template("site:glossary") || path.resolve(this.options.theme, 'templates/website/glossary.html');
return Q();
};
// Prepare template engine
Generator.prototype.prepareTemplateEngine = function() {
var that = this;
return Q()
.then(function() {
var language = that.book.config.normalizeLanguage();
if (!i18n.getByLanguage(language) && language != "en") {
that.book.log.warn.ln("Language '"+language+"' is not available as a layout locales (en, "+i18n.getLanguages().join(", ")+")");
}
var folders = _.chain(that.templates)
.values()
.map(path.dirname)
.uniq()
.value();
that.env = new nunjucks.Environment(
new nunjucks.FileSystemLoader(folders),
{
autoescape: true
}
);
// Add filter
that.env.addFilter("contentLink", that.book.contentLink.bind(that.book));
that.env.addFilter('lvl', function(lvl) {
return lvl.split(".").length;
});
// Add extension
that.env.addExtension('AutoEscapeExtension', new AutoEscapeExtension(that.env));
that.env.addExtension('FilterExtension', new FilterExtension(that.env));
that.env.addExtension('I18nExtension', new I18nExtension({
env: that.env,
translations: i18n.getLocales(),
locale: "language"
}));
});
};
// Finis generation
Generator.prototype.finish = function() {
return this.copyAssets()
.then(this.copyCover)
.then(this.writeGlossary)
.then(this.writeSearchIndex)
.then(this.writeLangsIndex)
};
// Convert an input file
Generator.prototype.convertFile = function(input) {
var that = this;
return that.book.parsePage(input, {
convertImages: that.convertImages,
interpolateTemplate: function(page) {
return that.callHook("page:before", page);
},
interpolateContent: function(page) {
return that.callHook("page", page);
}
})
.then(function(page) {
var relativeOutput = that.book.contentLink(page.path);
var output = path.join(that.options.output, relativeOutput);
var basePath = path.relative(path.dirname(output), that.options.output) || ".";
if (process.platform === 'win32') basePath = basePath.replace(/\\/g, '/');
that.book.log.info.ln("write parsed file", page.path, "to", relativeOutput);
return that._writeTemplate(that.templates["page"], {
progress: page.progress,
_input: page.path,
content: page.sections,
basePath: basePath,
staticBase: links.join(basePath, "gitbook")
}, output);
});
};
// Write the index for langs
Generator.prototype.writeLangsIndex = function() {
var that = this;
if (!this.book.langs.length) return Q();
return this._writeTemplate(this.templates["langs"], {
langs: this.book.langs
}, path.join(this.options.output, "index.html"));
};
// Write glossary
Generator.prototype.writeGlossary = function() {
var that = this;
// No glossary
if (this.book.glossary.length == 0) return Q();
return this._writeTemplate(this.templates["glossary"], {}, path.join(this.options.output, "GLOSSARY.html"));
};
// Write the search index
Generator.prototype.writeSearchIndex = function() {
var that = this;
return fs.writeFile(
path.join(this.options.output, "search_index.json"),
JSON.stringify(this.book.searchIndex)
);
};
// Convert a page into a normalized data set
Generator.prototype.normalizePage = function(page) {
var that = this;
var _callHook = function(name) {
return that.callHook(name, page)
.then(function(_page) {
page = _page;
return page;
});
};
return Q()
.then(function() {
return _callHook("page");
})
.then(function() {
return page;
});
};
// Generate a template
Generator.prototype._writeTemplate = function(tpl, options, output, interpolate) {
var that = this;
interpolate = interpolate || _.identity;
return Q()
.then(function(sections) {
return that.env.render(
tpl,
_.extend({
gitbook: {
version: pkg.version
},
styles: that.styles,
revision: that.revision,
title: that.options.title,
description: that.options.description,
language: that.book.config.normalizeLanguage(),
glossary: that.book.glossary,
summary: that.book.summary,
allNavigation: that.book.navigation,
plugins: {
resources: that.book.plugins.resources(that.namespace)
},
pluginsConfig: JSON.stringify(that.options.pluginsConfig),
htmlSnippet: _.partial(_.partialRight(that.book.plugins.html, that, options), that.namespace),
options: that.options,
basePath: ".",
staticBase: path.join(".", "gitbook"),
}, options)
);
})
.then(interpolate)
.then(function(html) {
return fs.writeFile(
output,
html
);
});
};
// Copy assets
Generator.prototype.copyAssets = function() {
var that = this;
// Copy gitbook assets
return fs.copy(
path.join(that.options.theme, "assets"),
path.join(that.options.output, "gitbook")
)
// Copy plugins assets
.then(function() {
return Q.all(
_.map(that.book.plugins.list, function(plugin) {
var pluginAssets = path.join(that.options.output, "gitbook/plugins/", plugin.name);
return plugin.copyAssets(pluginAssets, that.namespace);
})
);
});
};
module.exports = Generator;
+33
View File
@@ -0,0 +1,33 @@
var semver = require('semver');
var pkg = require('../package.json');
var VERSION = pkg.version;
var VERSION_STABLE = VERSION.replace(/\-(\S+)/g, '');
var START_TIME = new Date();
// Verify that this gitbook version satisfies a requirement
// We can't directly use samver.satisfies since it will break all plugins when gitbook version is a prerelease (beta, alpha)
function satisfies(condition) {
// Test with real version
if (semver.satisfies(VERSION, condition)) return true;
// Test with future stable release
return semver.satisfies(VERSION_STABLE, condition);
}
// Return templating/json context for gitbook itself
function getContext() {
return {
gitbook: {
version: pkg.version,
time: START_TIME
}
};
}
module.exports = {
version: pkg.version,
satisfies: satisfies,
getContext: getContext
};
+4 -207
View File
@@ -1,210 +1,7 @@
var Q = require("q");
var _ = require("lodash");
var path = require("path");
var tinylr = require('tiny-lr');
var color = require('bash-color');
var Book = require("./book");
var Plugin = require("./plugin");
var Server = require("./utils/server");
var stringUtils = require("./utils/string");
var watch = require("./utils/watch");
var logger = require("./utils/logger");
var LOG_OPTION = {
name: "log",
description: "Minimum log level to display",
values: _.chain(logger.LEVELS).keys().map(stringUtils.toLowerCase).value(),
defaults: "info"
};
var FORMAT_OPTION = {
name: "format",
description: "Format to build to",
values: ["website", "json", "ebook"],
defaults: "website"
};
var Book = require('./book');
var cli = require('./cli');
module.exports = {
Book: Book,
LOG_LEVELS: logger.LEVELS,
commands: _.flatten([
{
name: "build [book] [output]",
description: "build a book",
options: [
FORMAT_OPTION,
LOG_OPTION
],
exec: function(args, kwargs) {
var input = args[0] || process.cwd();
var output = args[1] || path.join(input, "_book");
var book = new Book(input, _.extend({}, {
'config': {
'output': output
},
'logLevel': kwargs.log
}));
return book.parse()
.then(function() {
return book.generate(kwargs.format);
})
.then(function(){
console.log("");
console.log(color.green("Done, without error"));
});
}
},
_.map(["pdf", "epub", "mobi"], function(ebookType) {
return {
name: ebookType+" [book] [output]",
description: "build a book to "+ebookType,
options: [
LOG_OPTION
],
exec: function(args, kwargs) {
var input = args[0] || process.cwd();
var output = args[1];
var book = new Book(input, _.extend({}, {
'logLevel': kwargs.log
}));
return book.parse()
.then(function() {
return book.generateFile(output, {
ebookFormat: ebookType
});
})
.then(function(){
console.log("");
console.log(color.green("Done, without error"));
});
}
};
}),
{
name: "serve [book]",
description: "Build then serve a gitbook from a directory",
options: [
{
name: "port",
description: "Port for server to listen on",
defaults: 4000
},
{
name: "lrport",
description: "Port for livereload server to listen on",
defaults: 35729
},
{
name: "watch",
description: "Enable/disable file watcher",
defaults: true
},
FORMAT_OPTION,
LOG_OPTION
],
exec: function(args, kwargs) {
var input = args[0] || process.cwd();
var server = new Server();
// Init livereload server
var lrServer = tinylr({});
var lrPath = undefined;
var generate = function() {
if (server.isRunning()) console.log("Stopping server");
return server.stop()
.then(function() {
var book = new Book(input, _.extend({}, {
'config': {
'defaultsPlugins': ["livereload"]
},
'logLevel': kwargs.log
}));
return book.parse()
.then(function() {
return book.generate(kwargs.format);
})
.thenResolve(book);
})
.then(function(book) {
console.log();
console.log('Starting server ...');
return server.start(book.options.output, kwargs.port)
.then(function() {
console.log('Serving book on http://localhost:'+kwargs.port);
if (lrPath) {
// trigger livereload
lrServer.changed({
body: {
files: [lrPath]
}
});
}
if (!kwargs.watch) return;
return watch(book.root)
.then(function(filepath) {
// set livereload path
lrPath = filepath;
console.log("Restart after change in files");
console.log('');
return generate();
})
})
});
};
return Q.nfcall(lrServer.listen.bind(lrServer), kwargs.lrport)
.then(function() {
console.log('Live reload server started on port:', kwargs.lrport);
console.log('Press CTRL+C to quit ...');
console.log('')
return generate();
});
}
},
{
name: "install [book]",
description: "install plugins dependencies",
exec: function(args, kwargs) {
var input = args[0] || process.cwd();
var book = new Book(input);
return book.config.load()
.then(function() {
return book.plugins.install();
})
.then(function(){
console.log("");
console.log(color.green("Done, without error"));
});
}
},
{
name: "init [directory]",
description: "create files and folders based on contents of SUMMARY.md",
exec: function(args, kwargs) {
return Book.init(args[0] || process.cwd())
.then(function(){
console.log("");
console.log(color.green("Done, without error"));
});
}
}
])
Book: Book,
commands: cli.commands
};
+67
View File
@@ -0,0 +1,67 @@
var path = require('path');
var fs = require('./utils/fs');
var Promise = require('./utils/promise');
// Initialize folder structure for a book
// Read SUMMARY to created the right chapter
function initBook(book) {
var extensionToUse = '.md';
book.log.info.ln('init book at', book.root);
return fs.mkdirp(book.root)
.then(function() {
return book.config.load();
})
.then(function() {
book.log.info.ln('detect structure from SUMMARY (if it exists)');
return book.summary.load();
})
.then(function() {
var summary = book.summary.path || 'SUMMARY.md';
var articles = book.summary.flatten();
// Use extension of summary
extensionToUse = path.extname(summary);
// Readme doesn't have a path
if (!articles[0].path) {
articles[0].path = 'README' + extensionToUse;
}
// Summary doesn't exists? create one
if (!book.summary.path) {
articles.push({
title: 'Summary',
path: 'SUMMARY'+extensionToUse
});
}
// Create files that don't exist
return Promise.serie(articles, function(article) {
if (!article.path) return;
var absolutePath = book.resolve(article.path);
return fs.exists(absolutePath)
.then(function(exists) {
if(exists) {
book.log.info.ln('found', article.path);
return;
} else {
book.log.info.ln('create', article.path);
}
return fs.mkdirp(path.dirname(absolutePath))
.then(function() {
return fs.writeFile(absolutePath, '# '+article.title+'\n\n');
});
});
});
})
.then(function() {
book.log.info.ln('initialization is finished');
});
}
module.exports = initBook;
+140
View File
@@ -0,0 +1,140 @@
var util = require('util');
var path = require('path');
var crc = require('crc');
var FolderOutput = require('./folder')();
var Promise = require('../utils/promise');
var fs = require('../utils/fs');
var imagesUtil = require('../utils/images');
var location = require('../utils/location');
var DEFAULT_ASSETS_FOLDER = 'assets';
/*
Mixin to inline all the assets in a book:
- Outline <svg> tags
- Download remote images
- Convert .svg images as png
*/
module.exports = function assetsInliner(Base) {
Base = Base || FolderOutput;
function AssetsInliner() {
Base.apply(this, arguments);
// Map of svg already converted
this.svgs = {};
this.inlineSvgs = {};
// Map of images already downloaded
this.downloaded = {};
}
util.inherits(AssetsInliner, Base);
// Output a SVG buffer as a file
AssetsInliner.prototype.onOutputSVG = function(page, svg) {
this.log.debug.ln('output svg from', page.path);
// Convert svg buffer to a png file
return this.convertSVGBuffer(svg)
// Return relative path from the page
.then(function(filename) {
return page.relative('/' + filename);
});
};
// Output an image as a file
AssetsInliner.prototype.onOutputImage = function(page, src) {
var that = this;
return Promise()
// Download file if external
.then(function() {
if (!location.isExternal(src)) return;
return that.downloadAsset(src)
.then(function(_asset) {
src = '/' + _asset;
});
})
.then(function() {
// Resolve src to a relative filepath to the book's root
src = page.resolveLocal(src);
// Already a PNG/JPG/.. ?
if (path.extname(src).toLowerCase() != '.svg') {
return src;
}
// Convert SVG to PNG
return that.convertSVGFile(that.resolve(src));
})
// Return relative path from the page
.then(function(filename) {
return page.relative(filename);
});
};
// Download an asset if not already download; returns the output file
AssetsInliner.prototype.downloadAsset = function(src) {
if (this.downloaded[src]) return Promise(this.downloaded[src]);
var that = this;
var ext = path.extname(src);
var hash = crc.crc32(src).toString(16);
// Create new file
return this.createNewFile(DEFAULT_ASSETS_FOLDER, hash + ext)
.then(function(filename) {
that.downloaded[src] = filename;
that.log.debug.ln('downloading asset', src);
return fs.download(src, that.resolve(filename))
.thenResolve(filename);
});
};
// Convert a .svg into an .png
// Return the output filename for the .png
AssetsInliner.prototype.convertSVGFile = function(src) {
if (this.svgs[src]) return Promise(this.svgs[src]);
var that = this;
var hash = crc.crc32(src).toString(16);
// Create new file
return this.createNewFile(DEFAULT_ASSETS_FOLDER, hash + '.png')
.then(function(filename) {
that.svgs[src] = filename;
return imagesUtil.convertSVGToPNG(src, that.resolve(filename))
.thenResolve(filename);
});
};
// Convert an inline svg into an .png
// Return the output filename for the .png
AssetsInliner.prototype.convertSVGBuffer = function(buf) {
var that = this;
var hash = crc.crc32(buf).toString(16);
// Already converted?
if (this.inlineSvgs[hash]) return Promise(this.inlineSvgs[hash]);
return this.createNewFile(DEFAULT_ASSETS_FOLDER, hash + '.png')
.then(function(filename) {
that.inlineSvgs[hash] = filename;
return imagesUtil.convertSVGBufferToPNG(buf, that.resolve(filename))
.thenResolve(filename);
});
};
return AssetsInliner;
};
+276
View File
@@ -0,0 +1,276 @@
var _ = require('lodash');
var Ignore = require('ignore');
var path = require('path');
var Promise = require('../utils/promise');
var pathUtil = require('../utils/path');
var location = require('../utils/location');
var PluginsManager = require('../plugins');
var TemplateEngine = require('../template');
/*
Output is like a stream interface for a parsed book
to output "something".
The process is mostly on the behavior of "onPage" and "onAsset"
*/
function Output(book, opts, parent) {
_.bindAll(this);
this.parent = parent;
this.opts = _.defaults({}, opts || {}, {
directoryIndex: true
});
this.book = book;
book.output = this;
this.log = this.book.log;
// Create plugins manager
this.plugins = new PluginsManager(this.book);
// Create template engine
this.template = new TemplateEngine(this);
// Files to ignore in output
this.ignore = Ignore();
}
// Default extension for output
Output.prototype.defaultExtension = '.html';
// Start the generation, for a parsed book
Output.prototype.generate = function() {
var that = this;
var isMultilingual = this.book.isMultilingual();
return Promise()
// Load all plugins
.then(function() {
return that.plugins.loadAll()
.then(function() {
that.template.addFilters(that.plugins.getFilters());
that.template.addBlocks(that.plugins.getBlocks());
});
})
// Transform the configuration
.then(function() {
return that.plugins.hook('config', that.book.config.dump())
.then(function(cfg) {
that.book.config.replace(cfg);
});
})
// Initialize the generation
.then(function() {
return that.plugins.hook('init');
})
.then(function() {
that.log.info.ln('preparing the generation');
return that.prepare();
})
// Process all files
.then(function() {
that.log.debug.ln('listing files');
return that.book.fs.listAllFiles(that.book.root);
})
// We want to process assets first, then pages
// Since pages can have logic based on existance of assets
.then(function(files) {
// Split into pages/assets
var byTypes = _.chain(files)
.filter(that.ignore.createFilter())
// Ignore file present in a language book
.filter(function(filename) {
return !(isMultilingual && that.book.isInLanguageBook(filename));
})
.groupBy(function(filename) {
return (that.book.hasPage(filename)? 'page' : 'asset');
})
.value();
return Promise.serie(byTypes.asset, function(filename) {
that.log.debug.ln('copy asset', filename);
return that.onAsset(filename);
})
.then(function() {
return Promise.serie(byTypes.page, function(filename) {
that.log.debug.ln('process page', filename);
return that.onPage(that.book.getPage(filename));
});
});
})
// Generate sub-books
.then(function() {
if (!that.book.isMultilingual()) return;
return Promise.serie(that.book.books, function(subbook) {
that.log.info.ln('');
that.log.info.ln('start generation of language "' + path.relative(that.book.root, subbook.root) + '"');
var out = that.onLanguageBook(subbook);
return out.generate();
});
})
// Finish the generation
.then(function() {
return that.plugins.hook('finish:before');
})
.then(function() {
that.log.debug.ln('finishing the generation');
return that.finish();
})
.then(function() {
return that.plugins.hook('finish');
})
.then(function() {
if (!that.book.isLanguageBook()) that.log.info.ln('');
that.log.info.ok('generation finished with success!');
});
};
// Prepare the generation
Output.prototype.prepare = function() {
this.ignore.addPattern(_.compact([
'.gitignore',
'.ignore',
'.bookignore',
'node_modules',
'_layouts',
// The configuration file should not be copied in the output
this.book.config.path,
// Structure file to ignore
this.book.summary.path,
this.book.langs.path
]));
};
// Write a page (parsable file), ex: markdown, etc
Output.prototype.onPage = function(page) {
return page.toHTML(this);
};
// Copy an asset file (non-parsable), ex: images, etc
Output.prototype.onAsset = function(filename) {
};
// Finish the generation
Output.prototype.finish = function() {
};
// Resolve an HTML link
Output.prototype.onRelativeLink = function(currentPage, href) {
var to = currentPage.followPage(href);
// Replace by an .html link
if (to) {
href = to.path;
// Recalcul as relative link
href = currentPage.relative(href);
// Replace .md by .html
href = this.toURL(href);
}
return href;
};
// Output a SVG buffer as a file
Output.prototype.onOutputSVG = function(page, svg) {
return null;
};
// Output an image as a file
// Normalize the relative link
Output.prototype.onOutputImage = function(page, imgFile) {
imgFile = page.resolveLocal(imgFile);
return page.relative(imgFile);
};
// Read a template by its source URL
Output.prototype.onGetTemplate = function(sourceUrl) {
throw new Error('template not found '+sourceUrl);
};
// Generate a source URL for a template
Output.prototype.onResolveTemplate = function(from, to) {
return path.resolve(path.dirname(from), to);
};
// Prepare output for a language book
Output.prototype.onLanguageBook = function(book) {
return new this.constructor(book, this.opts, this);
};
// ---- Utilities ----
// Return a default context for templates
Output.prototype.getContext = function() {
return _.extend(
{},
this.book.getContext(),
this.book.langs.getContext(),
this.book.summary.getContext(),
this.book.glossary.getContext(),
this.book.config.getContext()
);
};
// Resolve a file path in the context of a specific page
// Result is an "absolute path relative to the output folder"
Output.prototype.resolveForPage = function(page, href) {
if (_.isString(page)) page = this.book.getPage(page);
href = page.relative(href);
return this.onRelativeLink(page, href);
};
// Filename for output
// READMEs are replaced by index.html
// /test/README.md -> /test/index.html
Output.prototype.outputPath = function(filename, ext) {
ext = ext || this.defaultExtension;
var output = filename;
if (
path.basename(filename, path.extname(filename)) == 'README' ||
output == this.book.readme.path
) {
output = path.join(path.dirname(output), 'index'+ext);
} else {
output = pathUtil.setExtension(output, ext);
}
return output;
};
// Filename for output
// /test/index.html -> /test/
Output.prototype.toURL = function(filename, ext) {
var href = this.outputPath(filename, ext);
if (path.basename(href) == 'index.html' && this.opts.directoryIndex) {
href = path.dirname(href) + '/';
}
return location.normalize(href);
};
module.exports = Output;
+67
View File
@@ -0,0 +1,67 @@
var path = require('path');
var util = require('util');
var folderOutput = require('./folder');
var Git = require('../utils/git');
var fs = require('../utils/fs');
var pathUtil = require('../utils/path');
var location = require('../utils/location');
/*
Mixin for output to resolve git conrefs
*/
module.exports = function conrefsLoader(Base) {
Base = folderOutput(Base);
function ConrefsLoader() {
Base.apply(this, arguments);
this.git = new Git();
}
util.inherits(ConrefsLoader, Base);
// Read a template by its source URL
ConrefsLoader.prototype.onGetTemplate = function(sourceURL) {
var that = this;
return this.git.resolve(sourceURL)
.then(function(filepath) {
// Is local file
if (!filepath) {
filepath = that.book.resolve(sourceURL);
} else {
that.book.log.debug.ln('resolve from git', sourceURL, 'to', filepath);
}
// Read file from absolute path
return fs.readFile(filepath)
.then(function(source) {
return {
src: source.toString('utf8'),
path: filepath
};
});
});
};
// Generate a source URL for a template
ConrefsLoader.prototype.onResolveTemplate = function(from, to) {
// If origin is in the book, we enforce result file to be in the book
if (this.book.isInBook(from)) {
var href = location.toAbsolute(to, path.dirname(from), '');
return this.book.resolve(href);
}
// If origin is in a git repository, we resolve file in the git repository
var gitRoot = this.git.resolveRoot(from);
if (gitRoot) {
return pathUtil.resolveInRoot(gitRoot, to);
}
// If origin is not in the book (include from a git content ref)
return path.resolve(path.dirname(from), to);
};
return ConrefsLoader;
};
+190
View File
@@ -0,0 +1,190 @@
var _ = require('lodash');
var util = require('util');
var juice = require('juice');
var command = require('../utils/command');
var fs = require('../utils/fs');
var Promise = require('../utils/promise');
var error = require('../utils/error');
var WebsiteOutput = require('./website');
var assetsInliner = require('./assets-inliner');
function _EbookOutput() {
WebsiteOutput.apply(this, arguments);
// ebook-convert does not support link like "./"
this.opts.directoryIndex = false;
}
util.inherits(_EbookOutput, WebsiteOutput);
var EbookOutput = assetsInliner(_EbookOutput);
EbookOutput.prototype.name = 'ebook';
// Finish generation, create ebook using ebook-convert
EbookOutput.prototype.finish = function() {
var that = this;
if (that.book.isMultilingual()) {
return EbookOutput.super_.prototype.finish.apply(that);
}
return Promise()
.then(function() {
return EbookOutput.super_.prototype.finish.apply(that);
})
// Generate SUMMARY.html
.then(function() {
return that.render('summary', that.getContext())
.then(function(html) {
return that.writeFile(
'SUMMARY.html',
html
);
});
})
// Start ebook-convert
.then(function() {
return that.ebookConvertOption();
})
.then(function(options) {
if (!that.opts.format) return;
var cmd = [
'ebook-convert',
that.resolve('SUMMARY.html'),
that.resolve('index.'+that.opts.format),
command.optionsToShellArgs(options)
].join(' ');
return command.exec(cmd)
.progress(function(data) {
that.book.log.debug(data);
})
.fail(function(err) {
if (err.code == 127) {
throw error.RequireInstallError({
cmd: 'ebook-convert',
install: 'Install it from Calibre: https://calibre-ebook.com'
});
}
throw error.EbookError(err);
});
});
};
// Generate header/footer for PDF
EbookOutput.prototype.getPDFTemplate = function(tpl) {
var that = this;
var context = _.extend(
{
// Nunjucks context mapping to ebook-convert templating
page: {
num: '_PAGENUM_',
title: '_TITLE_',
section: '_SECTION_'
}
},
this.getContext()
);
return this.render('pdf_'+tpl, context)
// Inline css, include css relative to the output folder
.then(function(output) {
return Promise.nfcall(juice.juiceResources, output, {
webResources: {
relativeTo: that.root()
}
});
});
};
// Locate the cover file to use
// Use configuration or search a "cover.jpg" file
// For multi-lingual book, it can use the one from the main book
EbookOutput.prototype.locateCover = function() {
var cover = this.book.config.get('cover', 'cover.jpg');
// Resolve to absolute
cover = this.resolve(cover);
// Cover doesn't exist and multilingual?
if (!fs.existsSync(cover)) {
if (this.parent) return this.parent.locateCover();
else return undefined;
}
return cover;
};
// Generate options for ebook-convert
EbookOutput.prototype.ebookConvertOption = function() {
var that = this;
var options = {
'--cover': this.locateCover(),
'--title': that.book.config.get('title'),
'--comments': that.book.config.get('description'),
'--isbn': that.book.config.get('isbn'),
'--authors': that.book.config.get('author'),
'--language': that.book.config.get('language'),
'--book-producer': 'GitBook',
'--publisher': 'GitBook',
'--chapter': 'descendant-or-self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' book-chapter \')]',
'--level1-toc': 'descendant-or-self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' book-chapter-1 \')]',
'--level2-toc': 'descendant-or-self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' book-chapter-2 \')]',
'--level3-toc': 'descendant-or-self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' book-chapter-3 \')]',
'--no-chapters-in-toc': true,
'--max-levels': '1',
'--breadth-first': true
};
if (that.opts.format == 'epub') {
options = _.extend(options, {
'--dont-split-on-page-breaks': true
});
}
if (that.opts.format != 'pdf') return Promise(options);
var pdfOptions = that.book.config.get('pdf');
options = _.extend(options, {
'--chapter-mark': String(pdfOptions.chapterMark),
'--page-breaks-before': String(pdfOptions.pageBreaksBefore),
'--margin-left': String(pdfOptions.margin.left),
'--margin-right': String(pdfOptions.margin.right),
'--margin-top': String(pdfOptions.margin.top),
'--margin-bottom': String(pdfOptions.margin.bottom),
'--pdf-default-font-size': String(pdfOptions.fontSize),
'--pdf-mono-font-size': String(pdfOptions.fontSize),
'--paper-size': String(pdfOptions.paperSize),
'--pdf-page-numbers': Boolean(pdfOptions.pageNumbers),
'--pdf-header-template': that.getPDFTemplate('header'),
'--pdf-footer-template': that.getPDFTemplate('footer'),
'--pdf-sans-family': String(pdfOptions.fontFamily)
});
return that.getPDFTemplate('header')
.then(function(tpl) {
options['--pdf-header-template'] = tpl;
return that.getPDFTemplate('footer');
})
.then(function(tpl) {
options['--pdf-footer-template'] = tpl;
return options;
});
};
// Don't write multi-lingual index for wbook
EbookOutput.prototype.outputMultilingualIndex = function() {
};
module.exports = EbookOutput;
+152
View File
@@ -0,0 +1,152 @@
var _ = require('lodash');
var util = require('util');
var path = require('path');
var Output = require('./base');
var fs = require('../utils/fs');
var pathUtil = require('../utils/path');
var Promise = require('../utils/promise');
/*
This output requires the native fs module to output
book as a directory (mapping assets and pages)
*/
module.exports = function folderOutput(Base) {
Base = Base || Output;
function FolderOutput() {
Base.apply(this, arguments);
this.opts.root = path.resolve(this.opts.root || this.book.resolve('_book'));
}
util.inherits(FolderOutput, Base);
// Copy an asset file (non-parsable), ex: images, etc
FolderOutput.prototype.onAsset = function(filename) {
return this.copyFile(
this.book.resolve(filename),
filename
);
};
// Prepare the generation by creating the output folder
FolderOutput.prototype.prepare = function() {
var that = this;
return Promise()
.then(function() {
return FolderOutput.super_.prototype.prepare.apply(that);
})
// Cleanup output folder
.then(function() {
that.log.debug.ln('removing previous output directory');
return fs.rmDir(that.root())
.fail(function() {
return Promise();
});
})
// Create output folder
.then(function() {
that.log.debug.ln('creating output directory');
return fs.mkdirp(that.root());
})
// Add output folder to ignored files
.then(function() {
that.ignore.addPattern([
path.relative(that.book.root, that.root())
]);
});
};
// Prepare output for a language book
FolderOutput.prototype.onLanguageBook = function(book) {
return new this.constructor(book, _.extend({}, this.opts, {
// Language output should be output in sub-directory of output
root: path.resolve(this.root(), book.language)
}), this);
};
// ----- Utility methods -----
// Return path to the root folder
FolderOutput.prototype.root = function() {
return this.opts.root;
};
// Resolve a file in the output directory
FolderOutput.prototype.resolve = function(filename) {
return pathUtil.resolveInRoot.apply(null, [this.root()].concat(_.toArray(arguments)));
};
// Copy a file to the output
FolderOutput.prototype.copyFile = function(from, to) {
var that = this;
return Promise()
.then(function() {
to = that.resolve(to);
var folder = path.dirname(to);
// Ensure folder exists
return fs.mkdirp(folder);
})
.then(function() {
return fs.copy(from, to);
});
};
// Write a file/buffer to the output folder
FolderOutput.prototype.writeFile = function(filename, buf) {
var that = this;
return Promise()
.then(function() {
filename = that.resolve(filename);
var folder = path.dirname(filename);
// Ensure folder exists
return fs.mkdirp(folder);
})
// Write the file
.then(function() {
return fs.writeFile(filename, buf);
});
};
// Return true if a file exists in the output folder
FolderOutput.prototype.hasFile = function(filename) {
var that = this;
return Promise()
.then(function() {
return fs.exists(that.resolve(filename));
});
};
// Create a new unique file
// Returns its filename
FolderOutput.prototype.createNewFile = function(base, filename) {
var that = this;
if (!filename) {
filename = path.basename(filename);
base = path.dirname(base);
}
return fs.uniqueFilename(this.resolve(base), filename)
.then(function(out) {
out = path.join(base, out);
return fs.ensure(that.resolve(out))
.thenResolve(out);
});
};
return FolderOutput;
};
+47
View File
@@ -0,0 +1,47 @@
var conrefsLoader = require('./conrefs');
var JSONOutput = conrefsLoader();
JSONOutput.prototype.name = 'json';
// Don't copy asset on JSON output
JSONOutput.prototype.onAsset = function(filename) {};
// Write a page (parsable file)
JSONOutput.prototype.onPage = function(page) {
var that = this;
// Parse the page
return page.toHTML(this)
// Write as json
.then(function() {
var json = page.getContext();
// Delete some private properties
delete json.config;
// Specify JSON output version
json.version = '3';
return that.writeFile(
page.withExtension('.json'),
JSON.stringify(json, null, 4)
);
});
};
// At the end of generation, generate README.json for multilingual books
JSONOutput.prototype.finish = function() {
if (!this.book.isMultilingual()) return;
// Copy README.json from main book
var mainLanguage = this.book.langs.getDefault().id;
return this.copyFile(
this.resolve(mainLanguage, 'README.json'),
'README.json'
);
};
module.exports = JSONOutput;
+270
View File
@@ -0,0 +1,270 @@
var _ = require('lodash');
var path = require('path');
var util = require('util');
var nunjucks = require('nunjucks');
var I18n = require('i18n-t');
var Promise = require('../utils/promise');
var location = require('../utils/location');
var fs = require('../utils/fs');
var defaultFilters = require('../template/filters');
var conrefsLoader = require('./conrefs');
var Output = require('./base');
// Tranform a theme ID into a plugin
function themeID(plugin) {
return 'theme-' + plugin;
}
// Directory for a theme with the templates
function templatesPath(dir) {
return path.join(dir, '_layouts');
}
function _WebsiteOutput() {
Output.apply(this, arguments);
// Nunjucks environment
this.env;
// Plugin instance for the main theme
this.theme;
// Plugin instance for the default theme
this.defaultTheme;
// Resources loaded from plugins
this.resources;
// i18n for themes
this.i18n = new I18n();
}
util.inherits(_WebsiteOutput, Output);
var WebsiteOutput = conrefsLoader(_WebsiteOutput);
// Name of the generator
// It's being used as a prefix for templates
WebsiteOutput.prototype.name = 'website';
// Load and setup the theme
WebsiteOutput.prototype.prepare = function() {
var that = this;
return Promise()
.then(function() {
return WebsiteOutput.super_.prototype.prepare.apply(that);
})
.then(function() {
var themeName = that.book.config.get('theme');
that.theme = that.plugins.get(themeID(themeName));
that.themeDefault = that.plugins.get(themeID('default'));
if (!that.theme) {
throw new Error('Theme "' + themeName + '" is not installed, add "' + themeID(themeName) + '" to your "book.json"');
}
if (that.themeDefault.root != that.theme.root) {
that.log.info.ln('build using theme "' + themeName + '"');
}
// This list is ordered to give priority to templates in the book
var searchPaths = _.chain([
// The book itself can contains a "_layouts" folder
that.book.root,
// Installed plugin (it can be identical to themeDefault.root)
that.theme.root,
// Is default theme still installed
that.themeDefault? that.themeDefault.root : null
])
.compact()
.uniq()
.value();
// Load i18n
_.each(searchPaths.concat().reverse(), function(searchPath) {
var i18nRoot = path.resolve(searchPath, '_i18n');
if (!fs.existsSync(i18nRoot)) return;
that.i18n.load(i18nRoot);
});
that.env = new nunjucks.Environment(new nunjucks.FileSystemLoader(_.map(searchPaths, templatesPath)));
// Add GitBook default filters
_.each(defaultFilters, function(fn, filter) {
that.env.addFilter(filter, fn);
});
// Translate using _i18n locales
that.env.addFilter('t', function(s) {
return that.i18n.t(that.book.config.get('language'), s);
});
// Transform an absolute path into a relative path
// using this.ctx.page.path
that.env.addFilter('resolveFile', function(href) {
return location.normalize(that.resolveForPage(this.ctx.file.path, href));
});
// Test if a file exists
that.env.addFilter('fileExists', function(href) {
return fs.existsSync(that.resolve(href));
});
// Transform a '.md' into a '.html' (README -> index)
that.env.addFilter('contentURL', function(s) {
return that.toURL(s);
});
// Relase path to an asset
that.env.addFilter('resolveAsset', function(href) {
href = path.join('gitbook', href);
// Resolve for current file
if (this.ctx.file) {
href = that.resolveForPage(this.ctx.file.path, '/' + href);
}
// Use assets from parent
if (that.book.isLanguageBook()) {
href = path.join('../', href);
}
return location.normalize(href);
});
})
// Copy assets from themes before copying files from book
.then(function() {
if (that.book.isLanguageBook()) return;
return Promise.serie([
// Assets from the book are already copied
// The order is reversed from the template's one
// Is default theme still installed
that.themeDefault && that.themeDefault.root != that.theme.root?
that.themeDefault.root : null,
// Installed plugin (it can be identical to themeDefault.root)
that.theme.root
], function(folder) {
if (!folder) return;
// Copy assets only if exists (don't fail otherwise)
var assetFolder = path.join(folder, '_assets', that.name);
if (!fs.existsSync(assetFolder)) return;
that.log.debug.ln('copy assets from theme', assetFolder);
return fs.copyDir(
assetFolder,
that.resolve('gitbook'),
{
deleteFirst: false, // Delete "to" before
overwrite: true,
confirm: true
}
);
});
})
// Load resources for plugins
.then(function() {
return that.plugins.getResources(that.name)
.then(function(resources) {
that.resources = resources;
});
});
};
// Write a page (parsable file)
WebsiteOutput.prototype.onPage = function(page) {
var that = this;
// Parse the page
return page.toHTML(this)
// Render the page template with the same context as the json output
.then(function() {
return that.render('page', page.getContext());
})
// Write the HTML file
.then(function(html) {
return that.writeFile(
that.outputPath(page.path),
html
);
});
};
// Finish generation, create ebook using ebook-convert
WebsiteOutput.prototype.finish = function() {
var that = this;
return Promise()
.then(function() {
return WebsiteOutput.super_.prototype.finish.apply(that);
})
// Copy assets from plugins
.then(function() {
if (that.book.isLanguageBook()) return;
return that.plugins.copyResources(that.name, that.resolve('gitbook'));
})
// Generate homepage to select languages
.then(function() {
if (!that.book.isMultilingual()) return;
return that.outputMultilingualIndex();
});
};
// ----- Utilities ----
// Write multi-languages index
WebsiteOutput.prototype.outputMultilingualIndex = function() {
var that = this;
return that.render('languages', that.getContext())
.then(function(html) {
return that.writeFile(
'index.html',
html
);
});
};
// Render a template using nunjucks
// Templates are stored in `_layouts` folders
WebsiteOutput.prototype.render = function(tpl, context) {
var filename = this.templateName(tpl);
context = _.extend(context, {
template: {
// Same template but in the default theme
default: this.themeDefault? path.resolve(templatesPath(this.themeDefault.root), filename) : null,
// Same template but in the theme
theme: path.resolve(templatesPath(this.theme.root), filename)
},
plugins: {
resources: this.resources
},
options: this.opts
});
return Promise.nfcall(this.env.render.bind(this.env), filename, context);
};
// Return a complete name for a template
WebsiteOutput.prototype.templateName = function(name) {
return path.join(this.name, name+'.html');
};
module.exports = WebsiteOutput;
+280
View File
@@ -0,0 +1,280 @@
var _ = require('lodash');
var url = require('url');
var cheerio = require('cheerio');
var domSerializer = require('dom-serializer');
var slug = require('github-slugid');
var Promise = require('../utils/promise');
var location = require('../utils/location');
// Selector to ignore
var ANNOTATION_IGNORE = '.no-glossary,code,pre,a,script,h1,h2,h3,h4,h5,h6';
function HTMLPipeline(htmlString, opts) {
_.bindAll(this);
this.opts = _.defaults(opts || {}, {
// Called once the description has been found
onDescription: function(description) { },
// Calcul new href for a relative link
onRelativeLink: _.identity,
// Output an image
onImage: _.identity,
// Syntax highlighting
onCodeBlock: _.identity,
// Output a svg, if returns null the svg is kept inlined
onOutputSVG: _.constant(null),
// Words to annotate
annotations: [],
// When an annotation is applied
onAnnotation: function () { }
});
this.$ = cheerio.load(htmlString, {
// We should parse html without trying to normalize too much
xmlMode: false,
// SVG need some attributes to use uppercases
lowerCaseAttributeNames: false,
lowerCaseTags: false
});
}
// Transform a query of elements in the page
HTMLPipeline.prototype._transform = function(query, fn) {
var that = this;
var $elements = this.$(query);
return Promise.serie($elements, function(el) {
var $el = that.$(el);
return fn.call(that, $el);
});
};
// Normalize links
HTMLPipeline.prototype.transformLinks = function() {
return this._transform('a', function($a) {
var href = $a.attr('href');
if (!href) return;
if (location.isAnchor(href)) {
// Don't "change" anchor links
} else if (location.isRelative(href)) {
// Preserve anchor
var parsed = url.parse(href);
var filename = this.opts.onRelativeLink(parsed.pathname);
$a.attr('href', filename + (parsed.hash || ''));
} else {
// External links
$a.attr('target', '_blank');
}
});
};
// Normalize images
HTMLPipeline.prototype.transformImages = function() {
return this._transform('img', function($img) {
return Promise(this.opts.onImage($img.attr('src')))
.then(function(filename) {
$img.attr('src', filename);
});
});
};
// Normalize code blocks
HTMLPipeline.prototype.transformCodeBlocks = function() {
return this._transform('code', function($code) {
// Extract language
var lang = _.chain(
($code.attr('class') || '').split(' ')
)
.map(function(cl) {
// Markdown
if (cl.search('lang-') === 0) return cl.slice('lang-'.length);
// Asciidoc
if (cl.search('language-') === 0) return cl.slice('language-'.length);
return null;
})
.compact()
.first()
.value();
var source = $code.text();
return Promise(this.opts.onCodeBlock(source, lang))
.then(function(blk) {
if (blk.html === false) {
$code.text(blk.body);
} else {
$code.html(blk.body);
}
});
});
};
// Add ID to headings
HTMLPipeline.prototype.transformHeadings = function() {
var that = this;
this.$('h1,h2,h3,h4,h5,h6').each(function() {
var $h = that.$(this);
// Already has an ID?
if ($h.attr('id')) return;
$h.attr('id', slug($h.text()));
});
};
// Outline SVG from the HML
HTMLPipeline.prototype.transformSvgs = function() {
var that = this;
return this._transform('svg', function($svg) {
var content = [
'<?xml version="1.0" encoding="UTF-8"?>',
renderDOM(that.$, $svg)
].join('\n');
return Promise(that.opts.onOutputSVG(content))
.then(function(filename) {
if (!filename) return;
$svg.replaceWith(that.$('<img>').attr('src', filename));
});
});
};
// Annotate the content
HTMLPipeline.prototype.applyAnnotations = function() {
var that = this;
_.each(this.opts.annotations, function(annotation) {
var searchRegex = new RegExp( '\\b(' + pregQuote(annotation.name.toLowerCase()) + ')\\b' , 'gi' );
that.$('*').each(function() {
var $this = that.$(this);
if (
$this.is(ANNOTATION_IGNORE) ||
$this.parents(ANNOTATION_IGNORE).length > 0
) return;
replaceText(that.$, this, searchRegex, function(match) {
that.opts.onAnnotation(annotation);
return '<a href="' + that.opts.onRelativeLink(annotation.href) + '" '
+ 'class="glossary-term" title="'+_.escape(annotation.description)+'">'
+ match
+ '</a>';
});
});
});
};
// Extract page description from html
// This can totally be improved
HTMLPipeline.prototype.extractDescription = function() {
var $p = this.$('p').first();
var description = $p.text().trim().slice(0, 155);
this.opts.onDescription(description);
};
// Write content to the pipeline
HTMLPipeline.prototype.output = function() {
var that = this;
return Promise()
.then(this.extractDescription)
.then(this.transformImages)
.then(this.transformHeadings)
.then(this.transformCodeBlocks)
.then(this.transformSvgs)
.then(this.applyAnnotations)
// Transform of links should be applied after annotations
// because annotations are created as links
.then(this.transformLinks)
.then(function() {
return renderDOM(that.$);
});
};
// Render a cheerio DOM as html
function renderDOM($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options|| dom.options || $._options;
return domSerializer(dom, options);
}
// Replace text in an element
function replaceText($, el, search, replace, text_only ) {
return $(el).each(function(){
var node = this.firstChild,
val,
new_val,
// Elements to be removed at the end.
remove = [];
// Only continue if firstChild exists.
if ( node ) {
// Loop over all childNodes.
while (node) {
// Only process text nodes.
if ( node.nodeType === 3 ) {
// The original node value.
val = node.nodeValue;
// The new value.
new_val = val.replace( search, replace );
// Only replace text if the new value is actually different!
if ( new_val !== val ) {
if ( !text_only && /</.test( new_val ) ) {
// The new value contains HTML, set it in a slower but far more
// robust way.
$(node).before( new_val );
// Don't remove the node yet, or the loop will lose its place.
remove.push( node );
} else {
// The new value contains no HTML, so it can be set in this
// very fast, simple way.
node.nodeValue = new_val;
}
}
}
node = node.nextSibling;
}
}
// Time to remove those elements!
if (remove.length) $(remove).remove();
});
}
function pregQuote( str ) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, '\\$1');
}
module.exports = HTMLPipeline;
+250
View File
@@ -0,0 +1,250 @@
var _ = require('lodash');
var path = require('path');
var direction = require('direction');
var fm = require('front-matter');
var error = require('../utils/error');
var pathUtil = require('../utils/path');
var location = require('../utils/location');
var parsers = require('../parsers');
var gitbook = require('../gitbook');
var pluginCompatibility = require('../plugins/compatibility');
var HTMLPipeline = require('./html');
/*
A page represent a parsable file in the book (Markdown, Asciidoc, etc)
*/
function Page(book, filename) {
if (!(this instanceof Page)) return new Page(book, filename);
var extension;
_.bindAll(this);
this.book = book;
this.log = this.book.log;
// Map of attributes from YAML frontmatter
// Description is also extracted by default from content
this.attributes = {};
// Current content
this.content = '';
// Relative path to the page
this.path = location.normalize(filename);
// Absolute path to the page
this.rawPath = this.book.resolve(filename);
// Last modification date
this.mtime = 0;
// Can we parse it?
extension = path.extname(this.path);
this.parser = parsers.get(extension);
if (!this.parser) throw error.ParsingError(new Error('Can\'t parse file "'+this.path+'"'));
this.type = this.parser.name;
}
// Return the filename of the page with another extension
// "README.md" -> "README.html"
Page.prototype.withExtension = function(ext) {
return pathUtil.setExtension(this.path, ext);
};
// Resolve a filename relative to this page
// It returns a path relative to the book root folder
Page.prototype.resolveLocal = function() {
var dir = path.dirname(this.path);
var file = path.join.apply(path, _.toArray(arguments));
return location.toAbsolute(file, dir, '');
};
// Resolve a filename relative to this page
// It returns an absolute path for the FS
Page.prototype.resolve = function() {
return this.book.resolve(this.resolveLocal.apply(this, arguments));
};
// Convert an absolute path (in the book) to a relative path from this page
Page.prototype.relative = function(name) {
// Convert /test.png -> test.png
name = location.toAbsolute(name, '', '');
return location.relative(
this.resolve('.') + '/',
this.book.resolve(name)
);
};
// Return a page result of a relative page from this page
Page.prototype.followPage = function(filename) {
var absPath = this.resolveLocal(filename);
return this.book.getPage(absPath);
};
// Update content of the page
Page.prototype.update = function(content) {
this.content = content;
};
// Read the page as a string
Page.prototype.read = function() {
var that = this;
return this.book.statFile(this.path)
.then(function(stat) {
that.mtime = stat.mtime;
return that.book.readFile(that.path);
})
.then(this.update);
};
// Return templating context for this page
// This is used both for themes and page parsing
Page.prototype.getContext = function() {
var article = this.book.summary.getArticle(this);
var next = article? article.next() : null;
var prev = article? article.prev() : null;
// Detect text direction in this page
var dir = this.book.config.get('direction');
if (!dir) {
dir = direction(this.content);
if (dir == 'neutral') dir = null;
}
return _.extend(
{
file: {
path: this.path,
mtime: this.mtime,
type: this.type
},
page: _.extend({}, this.attributes, {
title: article? article.title : null,
next: next? next.getContext() : null,
previous: prev? prev.getContext() : null,
level: article? article.level : null,
depth: article? article.depth : 0,
content: this.content,
dir: dir
})
},
gitbook.getContext(),
this.book.getContext(),
this.book.langs.getContext(),
this.book.summary.getContext(),
this.book.glossary.getContext(),
this.book.config.getContext()
);
};
// Parse the page and return its content
Page.prototype.toHTML = function(output) {
var that = this;
this.log.debug.ln('start parsing file', this.path);
// Call a hook in the output
// using an utility to "keep" compatibility with gitbook 2
function hook(name) {
return pluginCompatibility.pageHook(that, function(ctx) {
return output.plugins.hook(name, ctx);
})
.then(function(result) {
if(_.isString(result)) that.update(result);
});
}
return this.read()
// Parse yaml front matter
.then(function() {
var parsed = fm(that.content);
// Extract attributes
that.attributes = parsed.attributes;
// Keep only the body
that.update(parsed.body);
})
.then(function() {
return hook('page:before');
})
// Pre-process page with parser
.then(function() {
return that.parser.page.prepare(that.content)
.then(that.update);
})
// Render template
.then(function() {
return output.template.render(that.content, that.getContext(), {
path: that.path
})
.then(that.update);
})
// Render markup using the parser
.then(function() {
return that.parser.page(that.content)
.then(function(out) {
that.update(out.content);
});
})
// Post process templating
.then(function() {
return output.template.postProcess(that.content)
.then(that.update);
})
// Normalize HTML output
.then(function() {
var pipelineOpts = {
onRelativeLink: _.partial(output.onRelativeLink, that),
onImage: _.partial(output.onOutputImage, that),
onOutputSVG: _.partial(output.onOutputSVG, that),
// Use 'code' template block
onCodeBlock: function(source, lang) {
return output.template.applyBlock('code', {
body: source,
kwargs: {
language: lang
}
});
},
// Extract description from page's content if no frontmatter
onDescription: function(description) {
if (that.attributes.description) return;
that.attributes.description = description;
},
// Convert glossary entries to annotations
annotations: that.book.glossary.annotations()
};
var pipeline = new HTMLPipeline(that.content, pipelineOpts);
return pipeline.output()
.then(that.update);
})
.then(function() {
return hook('page');
})
// Return content itself
.then(function() {
return that.content;
});
};
module.exports = Page;
+60
View File
@@ -0,0 +1,60 @@
var _ = require('lodash');
var path = require('path');
var markdownParser = require('gitbook-markdown');
var asciidocParser = require('gitbook-asciidoc');
var Promise = require('./utils/promise');
// This list is ordered by priority of parsers to use
var PARSERS = [
createParser(markdownParser, {
name: 'markdown',
extensions: ['.md', '.markdown', '.mdown']
}),
createParser(asciidocParser, {
name: 'asciidoc',
extensions: ['.adoc', '.asciidoc']
})
];
// Prepare and compose a parser
function createParser(parser, base) {
var nparser = base;
nparser.glossary = Promise.wrapfn(parser.glossary);
nparser.glossary.toText = Promise.wrapfn(parser.glossary.toText);
nparser.summary = Promise.wrapfn(parser.summary);
nparser.summary.toText = Promise.wrapfn(parser.summary.toText);
nparser.langs = Promise.wrapfn(parser.langs);
nparser.langs.toText = Promise.wrapfn(parser.langs.toText);
nparser.readme = Promise.wrapfn(parser.readme);
nparser.page = Promise.wrapfn(parser.page);
nparser.page.prepare = Promise.wrapfn(parser.page.prepare || _.identity);
return nparser;
}
// Return a specific parser according to an extension
function getParser(ext) {
return _.find(PARSERS, function(input) {
return input.name == ext || _.contains(input.extensions, ext);
});
}
// Return parser for a file
function getParserForFile(filename) {
return getParser(path.extname(filename));
}
module.exports = {
all: PARSERS,
extensions: _.flatten(_.pluck(PARSERS, 'extensions')),
get: getParser,
getForFile: getParserForFile
};
-183
View File
@@ -1,183 +0,0 @@
var _ = require("lodash");
var Q = require("q");
var semver = require("semver");
var path = require("path");
var url = require("url");
var fs = require("./utils/fs");
var resolve = require('resolve');
var pkg = require("../package.json");
var Plugin = function(book, name) {
this.book = book;
this.name = name;
this.packageInfos = {};
this.infos = {};
// Bind methods
_.bindAll(this);
_.each([
"gitbook-plugin-"+name,
"gitbook-"+name,
name,
], function(_name) {
// Load from the book
if (this.load(_name, book.root)) return false;
// Load from default plugins
if (this.load(_name, __dirname)) return false;
}, this);
};
// Type of plugins resources
Plugin.RESOURCES = ["js", "css"];
Plugin.HOOKS = [
"init", "finish", "finish:before"
]
// Load from a name
Plugin.prototype.load = function(name, baseDir) {
try {
var res = resolve.sync(name+"/package.json", { basedir: baseDir });
this.baseDir = path.dirname(res);
this.packageInfos = require(res);
this.infos = require(resolve.sync(name, { basedir: baseDir }));
this.name = name;
return true;
} catch (e) {
this.packageInfos = {};
this.infos = {};
return false;
}
};
Plugin.prototype.normalizeResource = function(resource) {
// Parse the resource path
var parsed = url.parse(resource);
// This is a remote resource
// so we will simply link to using it's URL
if (parsed.protocol) {
return {
"url": resource
};
}
// This will be copied over from disk
// and shipped with the book's build
return { "path": this.name+"/"+resource };
};
// Return resources
Plugin.prototype._getResources = function(base) {
base = base;
var book = this.infos[base];
// Compatibility with version 1.x.x
if (base == "website") book = book || this.infos["book"];
// Nothing specified, fallback to default
if (!book) {
return Q({});
}
// Dynamic function
if(typeof book === "function") {
// Call giving it the context of our book
return Q().then(book.bind(this.book));
}
// Plain data object
return Q(_.cloneDeep(book));
};
// Normalize resources and return them
Plugin.prototype.getResources = function(base) {
var that = this;
return this._getResources(base)
.then(function(resources) {
_.each(Plugin.RESOURCES, function(resourceType) {
resources[resourceType] = (resources[resourceType] || []).map(that.normalizeResource);
});
return resources;
});
};
// Normalize filters and return them
Plugin.prototype.getFilters = function() {
return this.infos.filters || {};
};
// Normalize blocks and return them
Plugin.prototype.getBlocks = function() {
return this.infos.blocks || {};
};
// Test if it's a valid plugin
Plugin.prototype.isValid = function() {
var that = this;
var isValid = (
this.packageInfos &&
this.packageInfos.name &&
this.packageInfos.engines &&
this.packageInfos.engines.gitbook &&
semver.satisfies(pkg.version, this.packageInfos.engines.gitbook)
);
// Valid hooks
_.each(this.infos.hooks, function(hook, hookName) {
if (_.contains(Plugin.HOOKS, hookName)) return;
that.book.log.warn.ln("Hook '"+hookName+" 'used by plugin '"+that.packageInfos.name+"' has been removed or is deprecated");
});
return isValid;
};
// Resolve file path
Plugin.prototype.resolveFile = function(filename) {
return path.resolve(this.baseDir, filename);
};
// Resolve file path
Plugin.prototype.callHook = function(name, data) {
// Our book will be the context to apply
var context = this.book;
var hookFunc = this.infos.hooks? this.infos.hooks[name] : null;
data = data || {};
if (!hookFunc) return Q(data);
this.book.log.debug.ln("call hook", name);
if (!_.contains(Plugin.HOOKS, name)) this.book.log.warn.ln("hook '"+name+"' used by plugin '"+this.name+"' is deprecated, and will be remove in the coming versions");
return Q()
.then(function() {
return hookFunc.apply(context, [data]);
});
};
// Copy plugin assets fodler
Plugin.prototype.copyAssets = function(out, base) {
var that = this;
return this.getResources(base)
.get('assets')
.then(function(assets) {
// Assets are undefined
if(!assets) return false;
return fs.copy(
that.resolveFile(assets),
out
).then(_.constant(true));
}, _.constant(false));
};
module.exports = Plugin;
+45
View File
@@ -0,0 +1,45 @@
var _ = require('lodash');
var error = require('../utils/error');
/*
Return the context for a plugin.
It tries to keep compatibilities with GitBook v2
*/
function pluginCtx(plugin) {
var book = plugin.book;
var ctx = book;
return ctx;
}
// Call a function "fn" with a context of page similar to the one in GitBook v2
function pageHook(page, fn) {
var ctx = {
type: page.type,
content: page.content,
path: page.path,
rawPath: page.rawPath
};
// Deprecate sections
error.deprecateField(ctx, 'sections', [
{ content: ctx.content }
], '"sections" property is deprecated, use page.content instead');
return fn(ctx)
.then(function(result) {
if (!result) return undefined;
if (result.content) {
return result.content;
}
if (result.sections) {
return _.pluck(result.sections, 'content').join('\n');
}
});
}
module.exports = {
pluginCtx: pluginCtx,
pageHook: pageHook
};
+155
View File
@@ -0,0 +1,155 @@
var _ = require('lodash');
var path = require('path');
var Promise = require('../utils/promise');
var fs = require('../utils/fs');
var BookPlugin = require('./plugin');
var registry = require('./registry');
var pluginsConfig = require('../config/plugins');
/*
PluginsManager is an interface to work with multiple plugins at once:
- Extract assets from plugins
- Call hooks for all plugins, etc
*/
function PluginsManager(book) {
this.book = book;
this.log = this.book.log;
this.plugins = [];
_.bindAll(this);
}
// Return count of plugins loaded
PluginsManager.prototype.count = function() {
return _.size(this.plugins);
};
// Returns a plugin by its name
PluginsManager.prototype.get = function(name) {
return _.find(this.plugins, {
id: name
});
};
// Load a plugin, or a list of plugins
PluginsManager.prototype.load = function(name) {
var that = this;
if (_.isArray(name)) {
return Promise.serie(name, function(_name) {
return that.load(_name);
});
}
return Promise()
// Initiate and load the plugin
.then(function() {
var plugin;
if (!_.isString(name)) plugin = name;
else plugin = new BookPlugin(that.book, name);
if (that.get(plugin.id)) {
throw new Error('Plugin "'+plugin.id+'" is already loaded');
}
if (plugin.isLoaded()) return plugin;
else return plugin.load()
.thenResolve(plugin);
})
// Setup the plugin
.then(this._setup);
};
// Load all plugins from the book's configuration
PluginsManager.prototype.loadAll = function() {
var plugins = _.pluck(this.book.config.get('plugins'), 'name');
this.log.info.ln('loading', plugins.length, 'plugins');
return this.load(plugins);
};
// Setup a plugin
// Register its filter, blocks, etc
PluginsManager.prototype._setup = function(plugin) {
this.plugins.push(plugin);
};
// Install all plugins for the book
PluginsManager.prototype.install = function() {
var that = this;
var plugins = _.filter(this.book.config.get('plugins'), function(plugin) {
return !pluginsConfig.isDefaultPlugin(plugin.name);
});
if (plugins.length == 0) {
this.log.info.ln('nothing to install!');
return Promise(0);
}
this.log.info.ln('installing', plugins.length, 'plugins');
return Promise.serie(plugins, function(plugin) {
return registry.install(that.book, plugin.name, plugin.version);
})
.thenResolve(plugins.length);
};
// Call a hook on all plugins to transform an input
PluginsManager.prototype.hook = function(name, input) {
return Promise.reduce(this.plugins, function(current, plugin) {
return plugin.hook(name, current);
}, input);
};
// Extract all resources for a namespace
PluginsManager.prototype.getResources = function(namespace) {
return Promise.reduce(this.plugins, function(out, plugin) {
return plugin.getResources(namespace)
.then(function(pluginResources) {
_.each(BookPlugin.RESOURCES, function(resourceType) {
out[resourceType] = (out[resourceType] || []).concat(pluginResources[resourceType] || []);
});
return out;
});
}, {});
};
// Copy all resources for a plugin
PluginsManager.prototype.copyResources = function(namespace, outputRoot) {
return Promise.serie(this.plugins, function(plugin) {
return plugin.getResources(namespace)
.then(function(resources) {
if (!resources.assets) return;
var input = path.resolve(plugin.root, resources.assets);
var output = path.resolve(outputRoot, plugin.npmId);
return fs.copyDir(input, output);
});
});
};
// Get all filters and blocks
PluginsManager.prototype.getFilters = function() {
return _.reduce(this.plugins, function(out, plugin) {
var filters = plugin.getFilters();
return _.extend(out, filters);
}, {});
};
PluginsManager.prototype.getBlocks = function() {
return _.reduce(this.plugins, function(out, plugin) {
var blocks = plugin.getBlocks();
return _.extend(out, blocks);
}, {});
};
module.exports = PluginsManager;
+299
View File
@@ -0,0 +1,299 @@
var _ = require('lodash');
var path = require('path');
var url = require('url');
var resolve = require('resolve');
var mergeDefaults = require('merge-defaults');
var jsonschema = require('jsonschema');
var jsonSchemaDefaults = require('json-schema-defaults');
var Promise = require('../utils/promise');
var error = require('../utils/error');
var gitbook = require('../gitbook');
var registry = require('./registry');
var compatibility = require('./compatibility');
var HOOKS = [
'init', 'finish', 'finish:before', 'config', 'page', 'page:before'
];
var RESOURCES = ['js', 'css'];
// Return true if an error is a "module not found"
// Wait on https://github.com/substack/node-resolve/pull/81 to be merged
function isModuleNotFound(err) {
return err.message.indexOf('Cannot find module') >= 0;
}
function BookPlugin(book, pluginId) {
this.book = book;
this.log = this.book.log.prefix(pluginId);
this.id = pluginId;
this.npmId = registry.npmId(pluginId);
this.root;
this.packageInfos = undefined;
this.content = undefined;
// Cache for resources
this._resources = {};
_.bindAll(this);
}
// Return true if plugin has been loaded correctly
BookPlugin.prototype.isLoaded = function() {
return Boolean(this.packageInfos && this.content);
};
// Bind a function to the plugin's context
BookPlugin.prototype.bind = function(fn) {
return fn.bind(compatibility.pluginCtx(this));
};
// Load this plugin
// An optional folder to search in can be passed
BookPlugin.prototype.load = function(folder) {
var that = this;
if (this.isLoaded()) {
return Promise.reject(new Error('Plugin "' + this.id + '" is already loaded'));
}
// Fodlers to search plugins in
var searchPaths = _.compact([
folder,
this.book.resolve('node_modules'),
__dirname
]);
// Try loading plugins from different location
var p = Promise.some(searchPaths, function(baseDir) {
// Locate plugin and load pacjage.json
try {
var res = resolve.sync(that.npmId + '/package.json', { basedir: baseDir });
that.root = path.dirname(res);
that.packageInfos = require(res);
} catch (err) {
if (!isModuleNotFound(err)) throw err;
that.packageInfos = undefined;
that.content = undefined;
return false;
}
// Load plugin JS content
try {
that.content = require(resolve.sync(that.npmId, { basedir: baseDir }));
} catch(err) {
// It's no big deal if the plugin doesn't have an "index.js"
// (For example: themes)
if (isModuleNotFound(err)) {
that.content = {};
} else {
throw new error.PluginError(err, {
plugin: that.id
});
}
}
return true;
})
.then(that.validate)
// Validate the configuration and update it
.then(function() {
var config = that.book.config.get(that.getConfigKey(), {});
return that.validateConfig(config);
})
.then(function(config) {
that.book.config.set(that.getConfigKey(), config);
});
this.log.info('loading plugin "' + this.id + '"... ');
return this.log.info.promise(p);
};
// Verify the definition of a plugin
// Also verify that the plugin accepts the current gitbook version
// This method throws erros if plugin is invalid
BookPlugin.prototype.validate = function() {
var isValid = (
this.packageInfos &&
this.packageInfos.name &&
this.packageInfos.engines &&
this.packageInfos.engines.gitbook
);
if (!this.isLoaded()) {
throw new Error('Couldn\'t locate plugin "' + this.id + '", Run \'gitbook install\' to install plugins from registry.');
}
if (!isValid) {
throw new Error('Invalid plugin "' + this.id + '"');
}
if (!gitbook.satisfies(this.packageInfos.engines.gitbook)) {
throw new Error('GitBook doesn\'t satisfy the requirements of this plugin: '+this.packageInfos.engines.gitbook);
}
};
// Normalize, validate configuration for this plugin using its schema
// Throw an error when shcema is not respected
BookPlugin.prototype.validateConfig = function(config) {
var that = this;
return Promise()
.then(function() {
var schema = that.packageInfos.gitbook || {};
if (!schema) return config;
// Normalize schema
schema.id = '/'+that.getConfigKey();
schema.type = 'object';
// Validate and throw if invalid
var v = new jsonschema.Validator();
var result = v.validate(config, schema, {
propertyName: that.getConfigKey()
});
// Throw error
if (result.errors.length > 0) {
throw new error.ConfigurationError(new Error(result.errors[0].stack));
}
// Insert default values
var defaults = jsonSchemaDefaults(schema);
return mergeDefaults(config, defaults);
});
};
// Return key for configuration
BookPlugin.prototype.getConfigKey = function() {
return 'pluginsConfig.'+this.id;
};
// Call a hook and returns its result
BookPlugin.prototype.hook = function(name, input) {
var that = this;
var hookFunc = this.content.hooks? this.content.hooks[name] : null;
input = input || {};
if (!hookFunc) return Promise(input);
this.book.log.debug.ln('call hook "' + name + '" for plugin "' + this.id + '"');
if (!_.contains(HOOKS, name)) {
this.book.log.warn.ln('hook "'+name+'" used by plugin "'+this.name+'" is deprecated, and will be removed in the coming versions');
}
return Promise()
.then(function() {
return that.bind(hookFunc)(input);
});
};
// Return resources without normalization
BookPlugin.prototype._getResources = function(base) {
var that = this;
return Promise()
.then(function() {
if (that._resources[base]) return that._resources[base];
var book = that.content[base];
// Compatibility with version 1.x.x
if (base == 'website') book = book || that.content.book;
// Nothing specified, fallback to default
if (!book) {
return Promise({});
}
// Dynamic function
if(typeof book === 'function') {
// Call giving it the context of our book
return that.bind(book)();
}
// Plain data object
return book;
})
.then(function(resources) {
that._resources[base] = resources;
return _.cloneDeep(resources);
});
};
// Normalize a specific resource
BookPlugin.prototype.normalizeResource = function(resource) {
// Parse the resource path
var parsed = url.parse(resource);
// This is a remote resource
// so we will simply link to using it's URL
if (parsed.protocol) {
return {
'url': resource
};
}
// This will be copied over from disk
// and shipped with the book's build
return { 'path': this.npmId+'/'+resource };
};
// Normalize resources and return them
BookPlugin.prototype.getResources = function(base) {
var that = this;
return this._getResources(base)
.then(function(resources) {
_.each(RESOURCES, function(resourceType) {
resources[resourceType] = _.map(resources[resourceType] || [], that.normalizeResource);
});
return resources;
});
};
// Normalize filters and return them
BookPlugin.prototype.getFilters = function() {
var that = this;
return _.mapValues(this.content.filters || {}, function(fn, filter) {
return function() {
var ctx = _.extend(compatibility.pluginCtx(that), this);
return fn.apply(ctx, arguments);
};
});
};
// Normalize blocks and return them
BookPlugin.prototype.getBlocks = function() {
var that = this;
return _.mapValues(this.content.blocks || {}, function(block, blockName) {
block = _.isFunction(block)? { process: block } : block;
var fn = block.process;
block.process = function() {
var ctx = _.extend(compatibility.pluginCtx(that), this);
return fn.apply(ctx, arguments);
};
return block;
});
};
module.exports = BookPlugin;
module.exports.RESOURCES = RESOURCES;
+115
View File
@@ -0,0 +1,115 @@
var npm = require('npm');
var npmi = require('npmi');
var semver = require('semver');
var _ = require('lodash');
var Promise = require('../utils/promise');
var gitbook = require('../gitbook');
var PLUGIN_PREFIX = 'gitbook-plugin-';
// Return an absolute name for the plugin (the one on NPM)
function npmId(name) {
if (name.indexOf(PLUGIN_PREFIX) === 0) return name;
return [PLUGIN_PREFIX, name].join('');
}
// Return a plugin ID 9the one on GitBook
function pluginId(name) {
return name.replace(PLUGIN_PREFIX, '');
}
// Validate an NPM plugin ID
function validateId(name) {
return name.indexOf(PLUGIN_PREFIX) === 0;
}
// Initialize NPM for operations
var initNPM = _.memoize(function() {
return Promise.nfcall(npm.load, {
silent: true,
loglevel: 'silent'
});
});
// Link a plugin for use in a specific book
function linkPlugin(book, pluginPath) {
book.log('linking', pluginPath);
}
// Resolve the latest version for a plugin
function resolveVersion(plugin) {
var npnName = npmId(plugin);
return initNPM()
.then(function() {
return Promise.nfcall(npm.commands.view, [npnName+'@*', 'engines'], true);
})
.then(function(versions) {
return _.chain(versions)
.pairs()
.map(function(v) {
return {
version: v[0],
gitbook: (v[1].engines || {}).gitbook
};
})
.filter(function(v) {
return v.gitbook && gitbook.satisfies(v.gitbook);
})
.sort(function(v1, v2) {
return semver.lt(v1.version, v2.version)? 1 : -1;
})
.pluck('version')
.first()
.value();
});
}
// Install a plugin in a book
function installPlugin(book, plugin, version) {
book.log.info.ln('installing plugin', plugin);
var npnName = npmId(plugin);
return Promise()
.then(function() {
if (version) return version;
book.log.info.ln('No version specified, resolve plugin "' + plugin + '"');
return resolveVersion(plugin);
})
// Install the plugin with the resolved version
.then(function(version) {
if (!version) {
throw new Error('Found no satisfactory version for plugin "' + plugin + '"');
}
book.log.info.ln('install plugin "' + plugin +'" from npm ('+npnName+') with version', version);
return Promise.nfcall(npmi, {
'name': npnName,
'version': version,
'path': book.root,
'npmLoad': {
'loglevel': 'silent',
'loaded': true,
'prefix': book.root
}
});
})
.then(function() {
book.log.info.ok('plugin "' + plugin + '" installed with success');
});
}
module.exports = {
npmId: npmId,
pluginId: pluginId,
validateId: validateId,
resolve: resolveVersion,
link: linkPlugin,
install: installPlugin
};
-225
View File
@@ -1,225 +0,0 @@
var _ = require("lodash");
var Q = require("q");
var npmi = require('npmi');
var npm = require('npm');
var semver = require('semver');
var Plugin = require("./plugin");
var pkg = require("../package.json");
var initNPM = _.memoize(function() {
return Q.nfcall(npm.load, { silent: true, loglevel: 'silent' });
});
var PluginsList = function(book, plugins) {
this.book = book;
this.log = this.book.log;
// List of Plugin objects
this.list = [];
// List of names of failed plugins
this.failed = [];
// Namespaces
this.namespaces = _.chain(["website", "ebook"])
.map(function(namespace) {
return [
namespace,
{
html: {},
resources: _.chain(Plugin.RESOURCES)
.map(function(type) {
return [type, []];
})
.object()
.value()
}
];
})
.object()
.value();
// Bind methods
_.bindAll(this);
if (plugins) this.load(plugins);
};
// return count of plugins
PluginsList.prototype.count = function() {
return this.list.length;
};
// Add and load a plugin
PluginsList.prototype.load = function(plugin, options) {
var that = this;
if (_.isArray(plugin)) {
return _.reduce(plugin, function(prev, p) {
return prev.then(function() {
return that.load(p);
});
}, Q());
}
if (_.isObject(plugin) && !(plugin instanceof Plugin)) plugin = plugin.name;
if (_.isString(plugin)) plugin = new Plugin(this.book, plugin);
that.log.info("load plugin", plugin.name, "....");
if (!plugin.isValid()) {
that.log.info.fail();
that.failed.push(plugin.name);
return Q();
} else {
that.log.info.ok();
// Push in the list
that.list.push(plugin);
}
// Extract filters
_.each(plugin.getFilters(), function(filterFunc, filterName) {
that.book.template.addFilter(filterName, filterFunc);
});
// Extract blocks
_.each(plugin.getBlocks(), function(block, blockName) {
that.book.template.addBlock(blockName, block);
});
return _.reduce(_.keys(that.namespaces), function(prev, namespaceName) {
return prev.then(function() {
return plugin.getResources(namespaceName)
.then(function(plResources) {
var namespace = that.namespaces[namespaceName];
// Extract js and css
_.each(Plugin.RESOURCES, function(resourceType) {
namespace.resources[resourceType] = (namespace.resources[resourceType] || []).concat(plResources[resourceType] || []);
});
// Map of html resources by name added by each plugin
_.each(plResources.html || {}, function(value, tag) {
// Turn into function if not one already
if (!_.isFunction(value)) value = _.constant(value);
namespace.html[tag] = namespace.html[tag] || [];
namespace.html[tag].push(value);
});
})
});
}, Q());
};
// Call a hook
PluginsList.prototype.hook = function(name, data) {
return _.reduce(this.list, function(prev, plugin) {
return prev.then(function(ret) {
return plugin.callHook(name, ret);
});
}, Q(data));
};
// Return a template from a plugin
PluginsList.prototype.template = function(name) {
var withTpl = _.find(this.list, function(plugin) {
return (
plugin.infos.templates &&
plugin.infos.templates[name]
);
});
if (!withTpl) return null;
return withTpl.resolveFile(withTpl.infos.templates[name]);
};
// Return an html snippet
PluginsList.prototype.html = function(namespace, tag, context, options) {
var htmlSnippets = this.namespaces[namespace].html[tag];
return _.map(htmlSnippets || [], function(code) {
return code.call(context, options);
}).join("\n");
};
// Return a resources map for a namespace
PluginsList.prototype.resources = function(namespace) {
return this.namespaces[namespace].resources;
};
// Install plugins from a book
PluginsList.prototype.install = function() {
var that = this;
var defaultsPlugins = _.pluck(that.book.options.defaultsPlugins)
// Remove defaults (no need to install)
var plugins = _.filter(that.book.options.plugins, function(plugin) {
return !_.contains(defaultsPlugins, plugin.name);
});
// Install plugins one by one
that.book.log.info.ln(plugins.length+" plugins to install");
return _.reduce(plugins, function(prev, plugin) {
return prev.then(function() {
var fullname = "gitbook-plugin-"+plugin.name;
return Q()
// Resolve version if needed
.then(function() {
if (plugin.version) return plugin.version;
that.book.log.info.ln("No version specified, resolve plugin", plugin.name);
return initNPM()
.then(function() {
return Q.nfcall(npm.commands.view, [fullname+"@*", "engines"], true);
})
.then(function(versions) {
return _.chain(versions)
.pairs()
.map(function(v) {
return {
version: v[0],
gitbook: (v[1].engines || {})["gitbook"]
}
})
.filter(function(v) {
return v.gitbook && semver.satisfies(pkg.version, v.gitbook);
})
.sort(function(v1, v2) {
return semver.lt(v1.version, v2.version)? 1 : -1;
})
.pluck("version")
.first()
.value();
});
})
// Install the plugin with the resolved version
.then(function(version) {
if (!version) {
throw "Found no satisfactory version for plugin "+plugin.name;
}
that.book.log.info.ln("install plugin", plugin.name, "from npm ("+fullname+") with version", version);
return Q.nfcall(npmi, {
'name': fullname,
'version': version,
'path': that.book.root,
'npmLoad': {
'loglevel': 'silent',
'loaded': true,
'prefix': that.book.root
}
});
})
.then(function() {
that.book.log.info.ok("plugin", plugin.name, "installed with success");
});
});
}, Q());
};
module.exports = PluginsList;
-370
View File
@@ -1,370 +0,0 @@
var _ = require("lodash");
var Q = require("q");
var path = require("path");
var nunjucks = require("nunjucks");
var git = require("./utils/git");
var stringUtils = require("./utils/string");
var fs = require("./utils/fs");
var pkg = require("../package.json");
// The loader should handle relative and git url
var BookLoader = nunjucks.Loader.extend({
async: true,
init: function(book) {
this.book = book;
},
getSource: function(fileurl, callback) {
var that = this;
git.resolveFile(fileurl)
.then(function(filepath) {
// Is local file
if (!filepath) filepath = path.resolve(that.book.root, fileurl);
else that.book.log.debug.ln("resolve from git", fileurl, "to", filepath)
// Read file from absolute path
return fs.readFile(filepath)
.then(function(source) {
return {
src: source.toString(),
path: filepath
}
});
})
.nodeify(callback);
},
resolve: function(from, to) {
return path.resolve(path.dirname(from), to);
}
});
var TemplateEngine = function(book) {
this.book = book;
this.log = this.book.log;
// Nunjucks env
this.env = new nunjucks.Environment(
new BookLoader(book),
{
// Escaping is done after by the markdown parser
autoescape: false,
// Tags
tags: {
blockStart: '{%',
blockEnd: '%}',
variableStart: '{{',
variableEnd: '}}',
commentStart: '{###',
commentEnd: '###}'
}
}
);
// List of tags shortcuts
this.shortcuts = [];
// Map of blocks
this.blocks = {};
// Bind methods
_.bindAll(this);
// Default block "html" that return html not parsed
this.addBlock("html", {
process: _.identity
});
};
// Process a block in a context
TemplateEngine.prototype.processBlock = function(blk) {
if (_.isString(blk)) blk = { body: blk };
blk = _.defaults(blk, {
parse: false
});
blk.id = _.uniqueId("blk");
//Parsable block, just return it
if (blk.parse) {
return blk.body;
}
// Add to global map
this.blocks[blk.id] = blk;
// Return it as a macro
return "%+%"+blk.id+"%+%";
};
// Replace blocks by body after processing
// This is done to avoid that markdown processer parse the block content
TemplateEngine.prototype.replaceBlocks = function(content) {
var that = this;
return content.replace(/\%\+\%([\s\S]+?)\%\+\%/g, function(match, key) {
var blk = that.blocks[key];
if (!blk) return match;
var body = blk.body;
// Remove it from map
delete that.blocks[key];
return body;
});
};
// Bind a function to a context
TemplateEngine.prototype.bindContext = function(func) {
var that = this;
return function() {
var ctx = {
ctx: this.ctx,
book: that.book,
generator: that.book.options.generator
};
return func.apply(ctx, arguments);
};
};
// Add filter
TemplateEngine.prototype.addFilter = function(filterName, func) {
try {
this.env.getFilter(filterName);
this.log.warn.ln("conflict in filters, '"+filterName+"' is already set");
return false;
} catch(e) {}
this.log.debug.ln("add filter '"+filterName+"'");
this.env.addFilter(filterName, this.bindContext(function() {
var ctx = this;
var args = Array.prototype.slice.apply(arguments);
var callback = _.last(args);
Q()
.then(function() {
return func.apply(ctx, args.slice(0, -1));
})
.nodeify(callback);
}), true);
return true;
};
// Add a block
TemplateEngine.prototype.addBlock = function(name, block) {
var that = this;
block = _.defaults(block || {}, {
shortcuts: [],
end: "end"+name,
process: _.identity,
blocks: []
});
var extName = 'Block'+name+'Extension';
if (this.env.getExtension(extName)) {
this.log.warn.ln("conflict in blocks, '"+name+"' is already defined");
return false;
}
this.log.debug.ln("add block '"+name+"'");
var Ext = function () {
this.tags = [name];
this.parse = function(parser, nodes, lexer) {
var body = null;
var lastBlockName = null;
var lastBlockArgs = null;
var allBlocks = block.blocks.concat([block.end]);
var subbodies = {};
var tok = parser.nextToken();
var args = parser.parseSignature(null, true);
parser.advanceAfterBlockEnd(tok.value);
while (1) {
// Read body
var currentBody = parser.parseUntilBlocks.apply(parser, allBlocks);
// Handle body with previous block name and args
if (lastBlockName) {
subbodies[lastBlockName] = subbodies[lastBlockName] || [];
subbodies[lastBlockName].push({
body: currentBody,
args: lastBlockArgs
});
} else {
body = currentBody;
}
// Read new block
lastBlockName = parser.peekToken().value;
if (lastBlockName == block.end) {
break;
}
// Parse signature and move to the end of the block
lastBlockArgs = parser.parseSignature(null, true);
parser.advanceAfterBlockEnd(lastBlockName);
}
parser.advanceAfterBlockEnd();
var bodies = [body];
_.each(block.blocks, function(blockName) {
subbodies[blockName] = subbodies[blockName] || [];
if (subbodies[blockName].length == 0) {
subbodies[blockName].push({
args: new nodes.NodeList(),
body: new nodes.NodeList()
});
}
bodies.push(subbodies[blockName][0].body);
});
return new nodes.CallExtensionAsync(this, 'run', args, bodies);
};
this.run = function(context) {
var args = Array.prototype.slice.call(arguments, 1);
var callback = args.pop();
// Extract blocks body
var _blocks = _.chain(block.blocks)
.reverse()
.map(function(blockName){
return {
name: blockName,
body: args.pop()()
};
})
.reverse()
.value();
var body = args.pop();
var kwargs = args.pop() || {};
var func = that.bindContext(block.process);
Q()
.then(function() {
return func.call(context, {
body: body(),
args: args,
kwargs: kwargs,
blocks: _blocks
});
})
// process the block returned
.then(that.processBlock)
.nodeify(callback)
};
};
// Add the Extension
this.env.addExtension(extName, new Ext());
// Add shortcuts
if (!_.isArray(block.shortcuts)) block.shortcuts = [block.shortcuts];
_.each(block.shortcuts, function(shortcut) {
this.log.debug.ln("add template shortcut from '"+shortcut.start+"' to block '"+name+"' for parsers ", shortcut.parsers);
this.shortcuts.push({
parsers: shortcut.parsers,
start: shortcut.start,
end: shortcut.end,
tag: {
start: name,
end: block.end
}
});
}, this);
};
// Apply a shortcut to a string
TemplateEngine.prototype._applyShortcut = function(parser, content, shortcut) {
if (!_.contains(shortcut.parsers, parser)) return content;
var regex = new RegExp(
stringUtils.escapeRegex(shortcut.start) + "([\\s\\S]*?[^\\$])" + stringUtils.escapeRegex(shortcut.end),
'g'
);
return content.replace(regex, function(all, match) {
return "{% "+shortcut.tag.start+" %}"+ match + "{% "+shortcut.tag.end+" %}";
});
};
// Render a string from the book
TemplateEngine.prototype.renderString = function(content, context, options) {
var context = _.extend({}, context, {
// Variables from book.json
book: this.book.options.variables,
// infos about gitbook
gitbook: {
version: pkg.version
}
});
options = _.defaults(options || {}, {
path: null,
type: null
});
if (options.path) options.path = this.book.resolve(options.path);
// Replace shortcuts
content = _.reduce(this.shortcuts, _.partial(this._applyShortcut.bind(this), options.type), content);
return Q.nfcall(this.env.renderString.bind(this.env), content, context, options);
};
// Render a file from the book
TemplateEngine.prototype.renderFile = function(filename, options) {
var that = this, context;
return that.book.readFile(filename)
.then(function(content) {
return that.renderString(content, {}, {
path: filename
});
});
};
// Render a page from the book
TemplateEngine.prototype.renderPage = function(page) {
var that = this, context;
return that.book.statFile(page.path)
.then(function(stat) {
context = {
// infos about the file
file: {
path: page.path,
mtime: stat.mtime
}
};
return that.renderString(page.content, context, {
path: page.path,
type: page.type
});
});
};
// Post process content
TemplateEngine.prototype.postProcess = function(content) {
return Q(content)
.then(this.replaceBlocks);
};
module.exports = TemplateEngine;
+16
View File
@@ -0,0 +1,16 @@
var _ = require('lodash');
module.exports = {
// Return non-parsed html
// since blocks are by default non-parsable, a simple identity method works fine
html: _.identity,
// Highlight a code block
// This block can be replaced by plugins
code: function(blk) {
return {
html: false,
body: blk.body
};
}
};
+15
View File
@@ -0,0 +1,15 @@
var moment = require('moment');
module.exports = {
// Format a date
// ex: 'MMMM Do YYYY, h:mm:ss a
date: function(time, format) {
return moment(time).format(format);
},
// Relative Time
dateFromNow: function(time) {
return moment(time).fromNow();
}
};
+431
View File
@@ -0,0 +1,431 @@
var _ = require('lodash');
var path = require('path');
var nunjucks = require('nunjucks');
var escapeStringRegexp = require('escape-string-regexp');
var Promise = require('../utils/promise');
var error = require('../utils/error');
var parsers = require('../parsers');
var defaultBlocks = require('./blocks');
var defaultFilters = require('./filters');
var Loader = require('./loader');
// Return extension name for a specific block
function blockExtName(name) {
return 'Block'+name+'Extension';
}
// Normalize the result of block process function
function normBlockResult(blk) {
if (_.isString(blk)) blk = { body: blk };
return blk;
}
function TemplateEngine(output) {
this.output = output;
this.book = output.book;
this.log = this.book.log;
// Create file loader
this.loader = new Loader(this);
// Create nunjucks instance
this.env = new nunjucks.Environment(
this.loader,
{
// Escaping is done after by the asciidoc/markdown parser
autoescape: false,
// Syntax
tags: {
blockStart: '{%',
blockEnd: '%}',
variableStart: '{{',
variableEnd: '}}',
commentStart: '{###',
commentEnd: '###}'
}
}
);
// List of tags shortcuts
this.shortcuts = [];
// Map of blocks bodies (that requires post-processing)
this.blockBodies = {};
// Map of added blocks
this.blocks = {};
// Bind methods
_.bindAll(this);
// Add default blocks and filters
this.addBlocks(defaultBlocks);
this.addFilters(defaultFilters);
}
// Bind a function to a context
// Filters and blocks are binded to this context
TemplateEngine.prototype.bindContext = function(func) {
var ctx = {
ctx: this.ctx,
output: this.output,
generator: this.output.name
};
return _.bind(func, ctx);
};
// Interpolate a string content to replace shortcuts according to the filetype
TemplateEngine.prototype.interpolate = function(filepath, source) {
var parser = parsers.get(path.extname(filepath));
var type = parser? parser.name : null;
return this.applyShortcuts(type, source);
};
// Add a new custom filter
TemplateEngine.prototype.addFilter = function(filterName, func) {
try {
this.env.getFilter(filterName);
this.log.error.ln('conflict in filters, "'+filterName+'" is already set');
return false;
} catch(e) {
// Filter doesn't exist
}
this.log.debug.ln('add filter "'+filterName+'"');
this.env.addFilter(filterName, this.bindContext(function() {
var ctx = this;
var args = Array.prototype.slice.apply(arguments);
var callback = _.last(args);
Promise()
.then(function() {
return func.apply(ctx, args.slice(0, -1));
})
.nodeify(callback);
}), true);
return true;
};
// Add multiple filters at once
TemplateEngine.prototype.addFilters = function(filters) {
_.each(filters, function(filter, name) {
this.addFilter(name, filter);
}, this);
};
// Return true if a block is defined
TemplateEngine.prototype.hasBlock = function(name) {
return this.env.hasExtension(blockExtName(name));
};
// Remove/Disable a block
TemplateEngine.prototype.removeBlock = function(name) {
if (!this.hasBlock(name)) return;
// Remove nunjucks extension
this.env.removeExtension(blockExtName(name));
// Cleanup shortcuts
this.shortcuts = _.reject(this.shortcuts, {
block: name
});
};
// Add a block
// Using the extensions of nunjucks: https://mozilla.github.io/nunjucks/api.html#addextension
TemplateEngine.prototype.addBlock = function(name, block) {
var that = this, Ext, extName;
// Block can be a simple function
if (_.isFunction(block)) block = { process: block };
block = _.defaults(block || {}, {
shortcuts: [],
end: 'end'+name,
blocks: []
});
extName = blockExtName(name);
if (!block.process) {
throw new Error('Invalid block "' + name + '", it should have a "process" method');
}
if (this.hasBlock(name) && !defaultBlocks[name]) {
this.log.warn.ln('conflict in blocks, "'+name+'" is already defined');
}
// Cleanup previous block
this.removeBlock(name);
this.log.debug.ln('add block \''+name+'\'');
this.blocks[name] = block;
Ext = function () {
this.tags = [name];
this.parse = function(parser, nodes) {
var body = null;
var lastBlockName = null;
var lastBlockArgs = null;
var allBlocks = block.blocks.concat([block.end]);
var subbodies = {};
var tok = parser.nextToken();
var args = parser.parseSignature(null, true);
parser.advanceAfterBlockEnd(tok.value);
do {
// Read body
var currentBody = parser.parseUntilBlocks.apply(parser, allBlocks);
// Handle body with previous block name and args
if (lastBlockName) {
subbodies[lastBlockName] = subbodies[lastBlockName] || [];
subbodies[lastBlockName].push({
body: currentBody,
args: lastBlockArgs
});
} else {
body = currentBody;
}
// Read new block
lastBlockName = parser.peekToken().value;
// Parse signature and move to the end of the block
if (lastBlockName != block.end) {
lastBlockArgs = parser.parseSignature(null, true);
parser.advanceAfterBlockEnd(lastBlockName);
}
} while (lastBlockName != block.end);
parser.advanceAfterBlockEnd();
var bodies = [body];
_.each(block.blocks, function(blockName) {
subbodies[blockName] = subbodies[blockName] || [];
if (subbodies[blockName].length === 0) {
subbodies[blockName].push({
args: new nodes.NodeList(),
body: new nodes.NodeList()
});
}
bodies.push(subbodies[blockName][0].body);
});
return new nodes.CallExtensionAsync(this, 'run', args, bodies);
};
this.run = function(context) {
var args = Array.prototype.slice.call(arguments, 1);
var callback = args.pop();
// Extract blocks
var blocks = args
.concat([])
.slice(-block.blocks.length);
// Eliminate blocks from list
if (block.blocks.length > 0) args = args.slice(0, -block.blocks.length);
// Extract main body and kwargs
var body = args.pop();
var kwargs = _.isObject(_.last(args))? args.pop() : {};
// Extract blocks body
var _blocks = _.map(block.blocks, function(blockName, i){
return {
name: blockName,
body: blocks[i]()
};
});
Promise()
.then(function() {
return that.applyBlock(name, {
body: body(),
args: args,
kwargs: kwargs,
blocks: _blocks
}, context);
})
// Process the block returned
.then(that.processBlock)
.nodeify(callback);
};
};
// Add the Extension
this.env.addExtension(extName, new Ext());
// Add shortcuts if any
if (!_.isArray(block.shortcuts)) {
block.shortcuts = [block.shortcuts];
}
_.each(block.shortcuts, function(shortcut) {
this.log.debug.ln('add template shortcut from "'+shortcut.start+'" to block "'+name+'" for parsers ', shortcut.parsers);
this.shortcuts.push({
block: name,
parsers: shortcut.parsers,
start: shortcut.start,
end: shortcut.end,
tag: {
start: name,
end: block.end
}
});
}, this);
};
// Add multiple blocks at once
TemplateEngine.prototype.addBlocks = function(blocks) {
_.each(blocks, function(block, name) {
this.addBlock(name, block);
}, this);
};
// Apply a block to some content
// This method result depends on the type of block (async or sync)
TemplateEngine.prototype.applyBlock = function(name, blk, ctx) {
var func, block, r;
block = this.blocks[name];
if (!block) throw new Error('Block not found "'+name+'"');
if (_.isString(blk)) {
blk = {
body: blk
};
}
blk = _.defaults(blk, {
args: [],
kwargs: {},
blocks: []
});
// Bind and call block processor
func = this.bindContext(block.process);
r = func.call(ctx || {}, blk);
if (Promise.isPromise(r)) return r.then(normBlockResult);
else return normBlockResult(r);
};
// Process the result of block in a context
TemplateEngine.prototype.processBlock = function(blk) {
blk = _.defaults(blk, {
parse: false,
post: undefined
});
blk.id = _.uniqueId('blk');
var toAdd = (!blk.parse) || (blk.post !== undefined);
// Add to global map
if (toAdd) this.blockBodies[blk.id] = blk;
// Parsable block, just return it
if (blk.parse) {
return blk.body;
}
// Return it as a position marker
return '@%@'+blk.id+'@%@';
};
// Render a string (without post processing)
TemplateEngine.prototype.render = function(content, context, options) {
options = _.defaults(options || {}, {
path: null
});
var filename = options.path;
// Setup path and type
if (options.path) {
options.path = this.book.resolve(options.path);
}
// Replace shortcuts
content = this.applyShortcuts(options.type, content);
return Promise.nfcall(this.env.renderString.bind(this.env), content, context, options)
.fail(function(err) {
throw error.TemplateError(err, {
filename: filename || '<inline>'
});
});
};
// Render a string with post-processing
TemplateEngine.prototype.renderString = function(content, context, options) {
return this.render(content, context, options)
.then(this.postProcess);
};
// Apply a shortcut to a string
TemplateEngine.prototype.applyShortcut = function(content, shortcut) {
var regex = new RegExp(
escapeStringRegexp(shortcut.start) + '([\\s\\S]*?[^\\$])' + escapeStringRegexp(shortcut.end),
'g'
);
return content.replace(regex, function(all, match) {
return '{% '+shortcut.tag.start+' %}'+ match + '{% '+shortcut.tag.end+' %}';
});
};
// Replace position markers of blocks by body after processing
// This is done to avoid that markdown/asciidoc processer parse the block content
TemplateEngine.prototype.replaceBlocks = function(content) {
var that = this;
return content.replace(/\@\%\@([\s\S]+?)\@\%\@/g, function(match, key) {
var blk = that.blockBodies[key];
if (!blk) return match;
var body = blk.body;
return body;
});
};
// Apply all shortcuts to a template
TemplateEngine.prototype.applyShortcuts = function(type, content) {
return _.chain(this.shortcuts)
.filter(function(shortcut) {
return _.contains(shortcut.parsers, type);
})
.reduce(this.applyShortcut, content)
.value();
};
// Post process content
TemplateEngine.prototype.postProcess = function(content) {
var that = this;
return Promise(content)
.then(that.replaceBlocks)
.then(function(_content) {
return Promise.serie(that.blockBodies, function(blk, blkId) {
return Promise()
.then(function() {
if (!blk.post) return;
return blk.post();
})
.then(function() {
delete that.blockBodies[blkId];
});
})
.thenResolve(_content);
});
};
module.exports = TemplateEngine;
+42
View File
@@ -0,0 +1,42 @@
var nunjucks = require('nunjucks');
var location = require('../utils/location');
/*
Simple nunjucks loader which is passing the reponsability to the Output
*/
var Loader = nunjucks.Loader.extend({
async: true,
init: function(engine, opts) {
this.engine = engine;
this.output = engine.output;
},
getSource: function(sourceURL, callback) {
var that = this;
this.output.onGetTemplate(sourceURL)
.then(function(out) {
// We disable cache since content is modified (shortcuts, ...)
out.noCache = true;
// Transform template before runnign it
out.source = that.engine.interpolate(out.path, out.source);
return out;
})
.nodeify(callback);
},
resolve: function(from, to) {
return this.output.onResolveTemplate(from, to);
},
// Handle all files as relative, so that nunjucks pass responsability to 'resolve'
isRelative: function(filename) {
return location.isRelative(filename);
}
});
module.exports = Loader;
+80
View File
@@ -0,0 +1,80 @@
var _ = require('lodash');
var childProcess = require('child_process');
var spawn = require('spawn-cmd').spawn;
var Promise = require('./promise');
// Execute a command
function exec(command, options) {
var d = Promise.defer();
var child = childProcess.exec(command, options, function(err, stdout, stderr) {
if (!err) {
return d.resolve();
}
err.message = stdout.toString('utf8') + stderr.toString('utf8');
d.reject(err);
});
child.stdout.on('data', function (data) {
d.notify(data);
});
child.stderr.on('data', function (data) {
d.notify(data);
});
return d.promise;
}
// Spawn an executable
function spawnCmd(command, args, options) {
var d = Promise.defer();
var child = spawn(command, args, options);
child.on('error', function(error) {
return d.reject(error);
});
child.stdout.on('data', function (data) {
d.notify(data);
});
child.stderr.on('data', function (data) {
d.notify(data);
});
child.on('close', function(code) {
if (code === 0) {
d.resolve();
} else {
d.reject(new Error('Error with command "'+command+'"'));
}
});
return d.promise;
}
// Transform an option object to a command line string
function escapeShellArg(s) {
s = s.replace(/"/g, '\\"');
return '"' + s + '"';
}
function optionsToShellArgs(options) {
return _.chain(options)
.map(function(value, key) {
if (value === null || value === undefined || value === false) return null;
if (value === true) return key;
return key + '=' + escapeShellArg(value);
})
.compact()
.value()
.join(' ');
}
module.exports = {
exec: exec,
spawn: spawnCmd,
optionsToShellArgs: optionsToShellArgs
};
+105
View File
@@ -0,0 +1,105 @@
var _ = require('lodash');
var TypedError = require('error/typed');
var WrappedError = require('error/wrapped');
var deprecated = require('deprecated');
var Logger = require('./logger');
var log = new Logger();
// Enforce as an Error object, and cleanup message
function enforce(err) {
if (_.isString(err)) err = new Error(err);
err.message = err.message.replace(/^Error: /, '');
return err;
}
// Random error wrappers during parsing/generation
var ParsingError = WrappedError({
message: 'Parsing Error: {origMessage}',
type: 'parse'
});
var OutputError = WrappedError({
message: 'Output Error: {origMessage}',
type: 'generate'
});
// A file does not exists
var FileNotFoundError = TypedError({
type: 'file.not-found',
message: 'No "{filename}" file (or is ignored)',
filename: null
});
// A file is outside the scope
var FileOutOfScopeError = TypedError({
type: 'file.out-of-scope',
message: '"{filename}" not in "{root}"',
filename: null,
root: null,
code: 'EACCESS'
});
// A file is outside the scope
var RequireInstallError = TypedError({
type: 'install.required',
message: '"{cmd}" is not installed.\n{install}',
cmd: null,
code: 'ENOENT',
install: ''
});
// Error for nunjucks templates
var TemplateError = WrappedError({
message: 'Error compiling template "{filename}": {origMessage}',
type: 'template',
filename: null
});
// Error for nunjucks templates
var PluginError = WrappedError({
message: 'Error with plugin "{plugin}": {origMessage}',
type: 'plugin',
plugin: null
});
// Error with the book's configuration
var ConfigurationError = WrappedError({
message: 'Error with book\'s configuration: {origMessage}',
type: 'configuration'
});
// Error during ebook generation
var EbookError = WrappedError({
message: 'Error during ebook generation: {origMessage}\n{stdout}',
type: 'ebook',
stdout: ''
});
// Deprecate methods/fields
function deprecateMethod(fn, msg) {
return deprecated.method(msg, log.warn.ln, fn);
}
function deprecateField(obj, prop, value, msg) {
return deprecated.field(msg, log.warn.ln, obj, prop, value);
}
module.exports = {
enforce: enforce,
ParsingError: ParsingError,
OutputError: OutputError,
RequireInstallError: RequireInstallError,
FileNotFoundError: FileNotFoundError,
FileOutOfScopeError: FileOutOfScopeError,
TemplateError: TemplateError,
PluginError: PluginError,
ConfigurationError: ConfigurationError,
EbookError: EbookError,
deprecateMethod: deprecateMethod,
deprecateField: deprecateField
};
+82 -142
View File
@@ -1,66 +1,36 @@
var _ = require("lodash");
var Q = require("q");
var tmp = require("tmp");
var path = require("path");
var fs = require("graceful-fs");
var fsExtra = require("fs-extra");
var Ignore = require("fstream-ignore");
var fs = require('graceful-fs');
var mkdirp = require('mkdirp');
var destroy = require('destroy');
var rmdir = require('rmdir');
var tmp = require('tmp');
var request = require('request');
var path = require('path');
var cp = require('cp');
var cpr = require('cpr');
var fsUtils = {
tmp: {
file: function(opt) {
return Q.nfcall(tmp.file.bind(tmp), opt).get(0)
},
dir: function() {
return Q.nfcall(tmp.dir.bind(tmp)).get(0)
}
},
list: listFiles,
stat: Q.denodeify(fs.stat),
readdir: Q.denodeify(fs.readdir),
readFile: Q.denodeify(fs.readFile),
writeFile: writeFile,
writeStream: writeStream,
mkdirp: Q.denodeify(fsExtra.mkdirp),
copy: Q.denodeify(fsExtra.copy),
remove: Q.denodeify(fsExtra.remove),
symlink: Q.denodeify(fsExtra.symlink),
exists: function(path) {
var d = Q.defer();
fs.exists(path, d.resolve);
return d.promise;
},
existsSync: fs.existsSync.bind(fs),
readFileSync: fs.readFileSync.bind(fs),
clean: cleanFolder,
getUniqueFilename: getUniqueFilename,
}
// Write a file
function writeFile(filename, data, options) {
var d = Q.defer();
try {
fs.writeFileSync(filename, data, options)
} catch(err) {
d.reject(err);
}
d.resolve();
return d.promise;
}
var Promise = require('./promise');
// Write a stream to a file
function writeStream(filename, st) {
var d = Q.defer();
var d = Promise.defer();
var wstream = fs.createWriteStream(filename);
var cleanup = function() {
destroy(wstream);
wstream.removeAllListeners();
};
wstream.on('finish', function () {
cleanup();
d.resolve();
});
wstream.on('error', function (err) {
cleanup();
d.reject(err);
});
st.on('error', function(err) {
cleanup();
d.reject(err);
});
@@ -69,110 +39,80 @@ function writeStream(filename, st) {
return d.promise;
}
// Find a filename available
function getUniqueFilename(base, filename) {
if (!filename) {
filename = base;
base = "/";
}
// Return a promise resolved with a boolean
function fileExists(filename) {
var d = Promise.defer();
filename = path.resolve(base, filename);
fs.exists(filename, function(exists) {
d.resolve(exists);
});
return d.promise;
}
// Generate temporary file
function genTmpFile(opts) {
return Promise.nfcall(tmp.file, opts)
.get(0);
}
// Generate temporary dir
function genTmpDir(opts) {
return Promise.nfcall(tmp.dir, opts)
.get(0);
}
// Download an image
function download(uri, dest) {
return writeStream(dest, request(uri));
}
// Find a filename available in a folder
function uniqueFilename(base, filename) {
var ext = path.extname(filename);
filename = path.resolve(base, filename);
filename = path.join(path.dirname(filename), path.basename(filename, ext));
var _filename = filename+ext;
var i = 0;
while (1) {
if (!fs.existsSync(filename)) break;
_filename = filename+"_"+i+ext;
while (fs.existsSync(filename)) {
_filename = filename + '_' + i + ext;
i = i + 1;
}
return path.relative(base, _filename);
return Promise(path.relative(base, _filename));
}
// List files in a directory
function listFiles(root, options) {
options = _.defaults(options || {}, {
ignoreFiles: [],
ignoreRules: []
});
var d = Q.defer();
// Our list of files
var files = [];
var ig = Ignore({
path: root,
ignoreFiles: options.ignoreFiles
});
// Add extra rules to ignore common folders
ig.addIgnoreRules(options.ignoreRules, '__custom_stuff');
// Push each file to our list
ig.on('child', function (c) {
files.push(
c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? '/' : '')
);
});
ig.on('end', function() {
// Normalize paths on Windows
if(process.platform === 'win32') {
return d.resolve(files.map(function(file) {
return file.replace(/\\/g, '/');
}));
}
// Simply return paths otherwise
return d.resolve(files);
});
ig.on('error', d.reject);
return d.promise;
// Create all required folder to create a file
function ensureFile(filename) {
var base = path.dirname(filename);
return Promise.nfcall(mkdirp, base);
}
// Clean a folder without removing .git and .svn
// Creates it if non existant
function cleanFolder(root) {
if (!fs.existsSync(root)) return fsUtils.mkdirp(root);
return listFiles(root, {
ignoreFiles: [],
ignoreRules: [
// Skip Git and SVN stuff
'.git/',
'.svn/'
]
})
.then(function(files) {
var d = Q.defer();
_.reduce(files, function(prev, file, i) {
return prev.then(function() {
var _file = path.join(root, file);
d.notify({
i: i+1,
count: files.length,
file: _file
});
return fsUtils.remove(_file);
});
}, Q())
.then(function() {
d.resolve();
}, function(err) {
d.reject(err);
});
return d.promise;
// Remove a folder
function rmDir(base) {
return Promise.nfcall(rmdir, base, {
fs: fs
});
}
module.exports = fsUtils;
module.exports = {
exists: fileExists,
existsSync: fs.existsSync,
mkdirp: Promise.nfbind(mkdirp),
readFile: Promise.nfbind(fs.readFile),
writeFile: Promise.nfbind(fs.writeFile),
stat: Promise.nfbind(fs.stat),
statSync: fs.statSync,
readdir: Promise.nfbind(fs.readdir),
writeStream: writeStream,
copy: Promise.nfbind(cp),
copyDir: Promise.nfbind(cpr),
tmpFile: genTmpFile,
tmpDir: genTmpDir,
download: download,
uniqueFilename: uniqueFilename,
ensure: ensureFile,
rmDir: rmDir
};
+106 -89
View File
@@ -1,112 +1,129 @@
var Q = require("q");
var _ = require("lodash");
var url = require("url");
var tmp = require("tmp");
var path = require("path");
var crc = require("crc");
var exec = Q.denodeify(require("child_process").exec);
var URI = require("URIjs");
var _ = require('lodash');
var path = require('path');
var crc = require('crc');
var URI = require('urijs');
var fs = require("./fs");
var pathUtil = require('./path');
var Promise = require('./promise');
var command = require('./command');
var fs = require('./fs');
var GIT_PREFIX = "git+";
var GIT_TMP = null;
var GIT_PREFIX = 'git+';
// Check if an url is a git dependency url
function checkGitUrl(giturl) {
return (giturl.indexOf(GIT_PREFIX) === 0);
function Git() {
this.tmpDir;
this.cloned = {};
}
// Validates a SHA in hexadecimal
function validateSha(str) {
return (/[0-9a-f]{40}/).test(str);
}
// Return an unique ID for a combinaison host/ref
Git.prototype.repoID = function(host, ref) {
return crc.crc32(host+'#'+(ref || '')).toString(16);
};
// Parse and extract infos
function parseGitUrl(giturl) {
var ref, uri, fileParts, filepath;
// Allocate a temporary folder for cloning repos in it
Git.prototype.allocateDir = function() {
var that = this;
if (!checkGitUrl(giturl)) return null;
giturl = giturl.slice(GIT_PREFIX.length);
if (this.tmpDir) return Promise();
uri = new URI(giturl);
ref = uri.fragment() || "master";
uri.fragment(null);
return fs.tmpDir()
.then(function(dir) {
that.tmpDir = dir;
});
};
// Extract file inside the repo (after the .git)
fileParts =uri.path().split(".git");
filepath = fileParts.length > 1? fileParts.slice(1).join(".git") : "";
if (filepath[0] == "/") filepath = filepath.slice(1);
// Clone a git repository if non existant
Git.prototype.clone = function(host, ref) {
var that = this;
// Recreate pathname without the real filename
uri.path(_.first(fileParts)+".git");
return this.allocateDir()
return {
host: uri.toString(),
ref: ref || "master",
filepath: filepath
};
}
// Return or clone the git repo
.then(function() {
// Unique ID for repo/ref combinaison
var repoId = that.repoID(host, ref);
// Clone a git repo from a specific ref
function cloneGitRepo(host, ref) {
var isBranch = false;
// Absolute path to the folder
var repoPath = path.join(that.tmpDir, repoId);
ref = ref || "master";
if (!validateSha(ref)) isBranch = true;
if (that.cloned[repoId]) return repoPath;
return Q()
// Clone repo
return command.exec('git clone '+host+' '+repoPath)
// Create temporary folder to store git repos
.then(function() {
if (GIT_TMP) return;
return fs.tmp.dir()
.then(function(_tmp) {
GIT_TMP = _tmp;
});
})
// Return or clone the git repo
.then(function() {
// Unique ID for repo/ref combinaison
var repoId = crc.crc32(host+"#"+ref).toString(16);
// Absolute path to the folder
var repoPath = path.resolve(GIT_TMP, repoId);
return fs.exists(repoPath)
.then(function(doExists) {
if (doExists) return;
// Clone repo
return exec("git clone "+host+" "+repoPath)
.then(function() {
return exec("git checkout "+ref, { cwd: repoPath });
})
})
.thenResolve(repoPath);
});
}
// Checkout reference if specified
.then(function() {
that.cloned[repoId] = true;
if (!ref) return;
return command.exec('git checkout '+ref, { cwd: repoPath });
})
.thenResolve(repoPath);
});
};
// Get file from a git repo
function resolveFileFromGit(giturl) {
if (_.isString(giturl)) giturl = parseGitUrl(giturl);
if (!giturl) return Q(null);
Git.prototype.resolve = function(giturl) {
// Path to a file in a git repo?
if (!Git.isUrl(giturl)) {
if (this.resolveRoot(giturl)) return Promise(giturl);
return Promise(null);
}
if (_.isString(giturl)) giturl = Git.parseUrl(giturl);
if (!giturl) return Promise(null);
// Clone or get from cache
return cloneGitRepo(giturl.host, giturl.ref)
.then(function(repo) {
// Resolve relative path
return path.resolve(repo, giturl.filepath);
});
// Clone or get from cache
return this.clone(giturl.host, giturl.ref)
.then(function(repo) {
return path.resolve(repo, giturl.filepath);
});
};
// Return root of git repo from a filepath
Git.prototype.resolveRoot = function(filepath) {
var relativeToGit, repoId;
module.exports = {
checkUrl: checkGitUrl,
parseUrl: parseGitUrl,
resolveFile: resolveFileFromGit
// No git repo cloned, or file is not in a git repository
if (!this.tmpDir || !pathUtil.isInRoot(this.tmpDir, filepath)) return null;
// Extract first directory (is the repo id)
relativeToGit = path.relative(this.tmpDir, filepath);
repoId = _.first(relativeToGit.split(path.sep));
if (!repoId) return;
// Return an absolute file
return path.resolve(this.tmpDir, repoId);
};
// Check if an url is a git dependency url
Git.isUrl = function(giturl) {
return (giturl.indexOf(GIT_PREFIX) === 0);
};
// Parse and extract infos
Git.parseUrl = function(giturl) {
var ref, uri, fileParts, filepath;
if (!Git.isUrl(giturl)) return null;
giturl = giturl.slice(GIT_PREFIX.length);
uri = new URI(giturl);
ref = uri.fragment() || null;
uri.fragment(null);
// Extract file inside the repo (after the .git)
fileParts = uri.path().split('.git');
filepath = fileParts.length > 1? fileParts.slice(1).join('.git') : '';
if (filepath[0] == '/') filepath = filepath.slice(1);
// Recreate pathname without the real filename
uri.path(_.first(fileParts)+'.git');
return {
host: uri.toString(),
ref: ref,
filepath: filepath
};
};
module.exports = Git;
-66
View File
@@ -1,66 +0,0 @@
var _ = require("lodash");
var path = require("path");
var fs = require("fs");
var I18N_PATH = path.resolve(__dirname, "../../theme/i18n/")
var getLocales = _.memoize(function() {
var locales = fs.readdirSync(I18N_PATH);
return _.chain(locales)
.map(function(local) {
local = path.basename(local, ".json");
return [local, _.extend(require(path.join(I18N_PATH, local)), {
id: local
})];
})
.object()
.value();
});
var getLanguages = function() {
return _.keys(getLocales());
};
var getByLanguage = function(lang) {
lang = normalizeLanguage(lang);
var locales = getLocales();
return locales[lang];
};
var compareLocales = function(lang, locale) {
var langMain = _.first(lang.split("-"));
var localeMain = _.first(locale.split("-"));
if (locale == lang) return 100;
if (localeMain == langMain) return 50;
return 0;
};
var normalizeLanguage = _.memoize(function(lang) {
var locales = getLocales();
var language = _.chain(locales)
.values()
.map(function(locale) {
locale = locale.id;
return {
locale: locale,
score: compareLocales(lang, locale)
}
})
.filter(function(lang) {
return lang.score > 0;
})
.sortBy("score")
.pluck("locale")
.last()
.value();
return language || lang;
});
module.exports = {
getLocales: getLocales,
getLanguages: getLanguages,
getByLanguage: getByLanguage,
normalizeLanguage: normalizeLanguage
};
+37 -31
View File
@@ -1,38 +1,44 @@
var _ = require("lodash");
var Q = require("q");
var fs = require("./fs");
var exec = require('child_process').exec;
var Promise = require('./promise');
var command = require('./command');
var fs = require('./fs');
var error = require('./error');
var links = require("./links");
// Convert a svg file to a pmg
function convertSVGToPNG(source, dest, options) {
if (!fs.existsSync(source)) return Promise.reject(new error.FileNotFoundError({ filename: source }));
// Convert a svg file
var convertSVG = function(source, dest, options) {
if (!fs.existsSync(source)) return Q.reject(new Error("File doesn't exist: "+source));
var d = Q.defer();
options = _.defaults(options || {}, {
});
var command = "svgexport "+source+" "+dest;
var child = exec(command, function (error, stdout, stderr) {
if (error) {
if (error.code == 127) error = new Error("Need to install 'svgexport' using 'npm install svgexport -g'");
return d.reject(error);
}
if (fs.existsSync(dest)) {
d.resolve();
} else {
d.reject(new Error("Error converting "+source));
return command.spawn('svgexport', [source, dest])
.fail(function(err) {
if (err.code == 'ENOENT') {
err = error.RequireInstallError({
cmd: 'svgexport',
install: 'Install it using: "npm install svgexport -g"'
});
}
throw err;
})
.then(function() {
if (fs.existsSync(dest)) return;
throw new Error('Error converting '+source+' into '+dest);
});
}
return d.promise;
};
// Convert a svg buffer to a png file
function convertSVGBufferToPNG(buf, dest) {
// Create a temporary SVG file to convert
return fs.tmpFile({
postfix: '.svg'
})
.then(function(tmpSvg) {
return fs.writeFile(tmpSvg, buf)
.then(function() {
return convertSVGToPNG(tmpSvg, dest);
});
});
}
module.exports = {
convertSVG: convertSVG,
INVALID: [".svg"]
};
convertSVGToPNG: convertSVGToPNG,
convertSVGBufferToPNG: convertSVGBufferToPNG
};
-69
View File
@@ -1,69 +0,0 @@
var url = require('url');
var path = require('path');
// Is the link an external link
var isExternal = function(href) {
try {
return Boolean(url.parse(href).protocol);
} catch(err) { }
return false;
};
// Return true if the link is relative
var isRelative = function(href) {
try {
var parsed = url.parse(href);
return !!(!parsed.protocol && parsed.path);// && parsed.path[0] != '/';
} catch(err) {}
return true;
};
// Relative to absolute path
// dir: directory parent of the file currently in rendering process
// outdir: directory parent from the html output
var toAbsolute = function(_href, dir, outdir) {
if (isExternal(_href)) return _href;
// Path '_href' inside the base folder
var hrefInRoot = path.normalize(path.join(dir, _href));
if (_href[0] == "/") hrefInRoot = path.normalize(_href.slice(1));
// Make it relative to output
_href = path.relative(outdir, hrefInRoot);
// Normalize windows paths
_href = _href.replace(/\\/g, '/');
return _href;
};
// Join links
var join = function() {
var _href = path.join.apply(path, arguments);
if (process.platform === 'win32') {
_href = _href.replace(/\\/g, '/');
}
return _href;
};
// Change extension
var changeExtension = function(filename, newext) {
return path.join(
path.dirname(filename),
path.basename(filename, path.extname(filename))+newext
);
};
module.exports = {
isRelative: isRelative,
isExternal: isExternal,
toAbsolute: toAbsolute,
join: join,
changeExtension: changeExtension
};
+70
View File
@@ -0,0 +1,70 @@
var url = require('url');
var path = require('path');
// Is the url an external url
function isExternal(href) {
try {
return Boolean(url.parse(href).protocol);
} catch(err) {
return false;
}
}
// Inverse of isExternal
function isRelative(href) {
return !isExternal(href);
}
// Return true if the link is an achor
function isAnchor(href) {
try {
var parsed = url.parse(href);
return !!(!parsed.protocol && !parsed.path && parsed.hash);
} catch(err) {
return false;
}
}
// Normalize a path to be a link
function normalize(s) {
return path.normalize(s).replace(/\\/g, '/');
}
// Convert relative to absolute path
// dir: directory parent of the file currently in rendering process
// outdir: directory parent from the html output
function toAbsolute(_href, dir, outdir) {
if (isExternal(_href)) return _href;
outdir = outdir == undefined? dir : outdir;
_href = normalize(_href);
dir = normalize(dir);
outdir = normalize(outdir);
// Path "_href" inside the base folder
var hrefInRoot = path.normalize(path.join(dir, _href));
if (_href[0] == '/') hrefInRoot = path.normalize(_href.slice(1));
// Make it relative to output
_href = path.relative(outdir, hrefInRoot);
// Normalize windows paths
_href = normalize(_href);
return _href;
}
// Convert an absolute path to a relative path for a specific folder (dir)
// ('test/', 'hello.md') -> '../hello.md'
function relative(dir, file) {
return normalize(path.relative(dir, file));
}
module.exports = {
isExternal: isExternal,
isRelative: isRelative,
isAnchor: isAnchor,
normalize: normalize,
toAbsolute: toAbsolute,
relative: relative
};
+111 -85
View File
@@ -3,100 +3,126 @@ var util = require('util');
var color = require('bash-color');
var LEVELS = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
DISABLED: 10
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
DISABLED: 10
};
var COLORS = {
DEBUG: color.purple,
INFO: color.cyan,
WARN: color.yellow,
ERROR: color.red
DEBUG: color.purple,
INFO: color.cyan,
WARN: color.yellow,
ERROR: color.red
};
module.exports = function(_write, logLevel) {
var logger = {};
var lastChar = '\n';
if (_.isString(logLevel)) logLevel = LEVELS[logLevel.toUpperCase()];
function Logger(write, logLevel, prefix) {
if (!(this instanceof Logger)) return new Logger(write, logLevel);
// Write a simple message
logger.write = function(msg) {
msg = msg.toString();
lastChar = _.last(msg);
return _write(msg);
};
this._write = write || function(msg) { process.stdout.write(msg); };
this.lastChar = '\n';
// Format a message
logger.format = function() {
return util.format.apply(util, arguments);
};
// Define log level
this.setLevel(logLevel);
// Write a line
logger.writeLn = function(msg) {
return this.write((msg || "")+"\n");
};
_.bindAll(this);
// Write a message with a certain level
logger.log = function(level) {
if (level < logLevel) return;
// Create easy-to-use method like "logger.debug.ln('....')"
_.each(_.omit(LEVELS, 'DISABLED'), function(level, levelKey) {
levelKey = levelKey.toLowerCase();
var levelKey = _.findKey(LEVELS, function(v) { return v == level; });
var args = Array.prototype.slice.apply(arguments, [1]);
var msg = logger.format.apply(logger, args);
this[levelKey] = _.partial(this.log, level);
this[levelKey].ln = _.partial(this.logLn, level);
this[levelKey].ok = _.partial(this.ok, level);
this[levelKey].fail = _.partial(this.fail, level);
this[levelKey].promise = _.partial(this.promise, level);
}, this);
}
if (lastChar == '\n') {
msg = COLORS[levelKey](levelKey.toLowerCase()+":")+" "+msg;
}
return logger.write(msg);
};
logger.logLn = function() {
if (lastChar != '\n') logger.write("\n");
var args = Array.prototype.slice.apply(arguments);
args.push("\n");
logger.log.apply(logger, args);
};
// Write a OK
logger.ok = function(level) {
var args = Array.prototype.slice.apply(arguments, [1]);
var msg = logger.format.apply(logger, args);
if (arguments.length > 1) {
logger.logLn(level, color.green('>> ') + msg.trim().replace(/\n/g, color.green('\n>> ')));
} else {
logger.log(level, color.green("OK"), "\n");
}
};
// Write an "FAIL"
logger.fail = function(level) {
return logger.log(level, color.red("ERROR")+"\n");
};
_.each(_.omit(LEVELS, 'DISABLED'), function(level, levelKey) {
levelKey = levelKey.toLowerCase();
logger[levelKey] = _.partial(logger.log, level);
logger[levelKey].ln = _.partial(logger.logLn, level);
logger[levelKey].ok = _.partial(logger.ok, level);
logger[levelKey].fail = _.partial(logger.fail, level);
logger[levelKey].promise = function(p) {
return p.
then(function(st) {
logger[levelKey].ok();
return st;
}, function(err) {
logger[levelKey].fail();
throw err;
});
}
});
return logger;
// Create a new logger prefixed from this logger
Logger.prototype.prefix = function(prefix) {
return (new Logger(this._write, this.logLevel, prefix));
};
module.exports.LEVELS = LEVELS;
module.exports.COLORS = COLORS;
// Change minimum level
Logger.prototype.setLevel = function(logLevel) {
if (_.isString(logLevel)) logLevel = LEVELS[logLevel.toUpperCase()];
this.logLevel = logLevel;
};
// Print a simple string
Logger.prototype.write = function(msg) {
msg = msg.toString();
this.lastChar = _.last(msg);
return this._write(msg);
};
// Format a string using the first argument as a printf-like format.
Logger.prototype.format = function() {
return util.format.apply(util, arguments);
};
// Print a line
Logger.prototype.writeLn = function(msg) {
return this.write((msg || '')+'\n');
};
// Log/Print a message if level is allowed
Logger.prototype.log = function(level) {
if (level < this.logLevel) return;
var levelKey = _.findKey(LEVELS, function(v) { return v == level; });
var args = Array.prototype.slice.apply(arguments, [1]);
var msg = this.format.apply(this, args);
if (this.lastChar == '\n') {
msg = COLORS[levelKey](levelKey.toLowerCase()+':')+' '+msg;
}
return this.write(msg);
};
// Log/Print a line if level is allowed
Logger.prototype.logLn = function() {
if (this.lastChar != '\n') this.write('\n');
var args = Array.prototype.slice.apply(arguments);
args.push('\n');
return this.log.apply(this, args);
};
// Log a confirmation [OK]
Logger.prototype.ok = function(level) {
var args = Array.prototype.slice.apply(arguments, [1]);
var msg = this.format.apply(this, args);
if (arguments.length > 1) {
this.logLn(level, color.green('>> ') + msg.trim().replace(/\n/g, color.green('\n>> ')));
} else {
this.log(level, color.green('OK'), '\n');
}
};
// Log a "FAIL"
Logger.prototype.fail = function(level) {
return this.log(level, color.red('ERROR') + '\n');
};
// Log state of a promise
Logger.prototype.promise = function(level, p) {
var that = this;
return p.
then(function(st) {
that.ok(level);
return st;
}, function(err) {
that.fail(level);
throw err;
});
};
Logger.LEVELS = LEVELS;
Logger.COLORS = COLORS;
module.exports = Logger;
-80
View File
@@ -1,80 +0,0 @@
var _ = require('lodash');
// Cleans up an article/chapter object
// remove 'articles' attributes
function clean(obj) {
return obj && _.omit(obj, ['articles']);
}
function flattenChapters(chapters) {
return _.reduce(chapters, function(accu, chapter) {
return accu.concat([clean(chapter)].concat(flattenChapters(chapter.articles)));
}, []);
}
// Returns from a summary a map of
/*
{
"file/path.md": {
prev: ...,
next: ...,
},
...
}
*/
function navigation(summary, files) {
// Support single files as well as list
files = _.isArray(files) ? files : (_.isString(files) ? [files] : null);
// List of all navNodes
// Flatten chapters, then add in default README node if needed etc ...
var navNodes = flattenChapters(summary.chapters);
// Mapping of prev/next for a give path
var mapping = _.chain(navNodes)
.map(function(current, i) {
var prev = null, next = null;
// Skip if no path
if(!current.path) return null;
// Find prev
prev = _.chain(navNodes)
.slice(0, i)
.reverse()
.find(function(node) {
return node.exists && !node.external;
})
.value();
// Find next
next = _.chain(navNodes)
.slice(i+1)
.find(function(node) {
return node.exists && !node.external;
})
.value();
return [current.path, {
title: current.title,
prev: prev,
next: next,
level: current.level,
}];
})
.compact()
.object()
.value();
// Filter for only files we want
if(files) {
return _.pick(mapping, files);
}
return mapping;
}
// Exports
module.exports = navigation;
-329
View File
@@ -1,329 +0,0 @@
var Q = require('q');
var _ = require('lodash');
var path = require('path');
var cheerio = require('cheerio');
var domSerializer = require('dom-serializer');
var request = require('request');
var crc = require("crc");
var links = require('./links');
var imgUtils = require('./images');
var fs = require('./fs');
// Render a cheerio dom as html
var renderDom = function($, dom, options) {
if (!dom && $._root && $._root.children) {
dom = $._root.children;
}
options = options|| dom.options || $._options;
return domSerializer(dom, options);
};
// Map of images that have been converted
var imgConversionCache = {};
function replaceText($, el, search, replace, text_only ) {
return $(el).each(function(){
var node = this.firstChild,
val,
new_val,
// Elements to be removed at the end.
remove = [];
// Only continue if firstChild exists.
if ( node ) {
// Loop over all childNodes.
do {
// Only process text nodes.
if ( node.nodeType === 3 ) {
// The original node value.
val = node.nodeValue;
// The new value.
new_val = val.replace( search, replace );
// Only replace text if the new value is actually different!
if ( new_val !== val ) {
if ( !text_only && /</.test( new_val ) ) {
// The new value contains HTML, set it in a slower but far more
// robust way.
$(node).before( new_val );
// Don't remove the node yet, or the loop will lose its place.
remove.push( node );
} else {
// The new value contains no HTML, so it can be set in this
// very fast, simple way.
node.nodeValue = new_val;
}
}
}
} while ( node = node.nextSibling );
}
// Time to remove those elements!
remove.length && $(remove).remove();
});
};
function pregQuote( str ) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
};
// Adapt an html snippet to be relative to a base folder
function normalizeHtml(src, options) {
var $ = cheerio.load(src, {
// We should parse html without trying to normalize too much
xmlMode: false,
// SVG need some attributes to use uppercases
lowerCaseAttributeNames: false,
lowerCaseTags: false
});
var toConvert = [];
var svgContent = {};
var outputRoot = options.book.options.output;
imgConversionCache[outputRoot] = imgConversionCache[outputRoot] || {};
// Find svg images to extract and process
if (options.convertImages) {
$("svg").each(function() {
var content = renderDom($, $(this));
var svgId = _.uniqueId("svg");
var dest = svgId+".svg";
// Generate filename
dest = "/"+fs.getUniqueFilename(outputRoot, dest);
svgContent[dest] = content;
$(this).replaceWith($("<img>").attr("src", dest));
});
}
// Find images to normalize
$("img").each(function() {
var origin = undefined;
var src = $(this).attr("src");
var isExternal = links.isExternal(src);
// Transform as relative to the bases
if (links.isRelative(src)) {
src = links.toAbsolute(src, options.base, options.output);
}
// Convert if needed
if (options.convertImages) {
// If image is external and ebook, then downlaod the images
if (isExternal) {
origin = src;
src = "/"+crc.crc32(origin).toString(16)+path.extname(origin);
src = links.toAbsolute(src, options.base, options.output);
isExternal = false;
}
var ext = path.extname(src);
var srcAbs = path.join("/", options.base, src);
// Test image extension
if (_.contains(imgUtils.INVALID, ext)) {
if (imgConversionCache[outputRoot][srcAbs]) {
// Already converted
src = imgConversionCache[outputRoot][srcAbs];
} else {
// Not converted yet
var dest = "";
// Replace extension
dest = path.join(path.dirname(srcAbs), path.basename(srcAbs, ext)+".png");
dest = dest[0] == "/"? dest.slice(1) : dest;
// Get a name that doesn't exists
dest = fs.getUniqueFilename(outputRoot, dest);
options.book.log.debug.ln("detect invalid image (will be converted to png):", srcAbs);
// Add to cache
imgConversionCache[outputRoot][srcAbs] = "/"+dest;
// Push to convert
toConvert.push({
origin: origin,
content: svgContent[srcAbs],
source: isExternal? srcAbs : path.join("./", srcAbs),
dest: path.join("./", dest)
});
src = path.join("/", dest);
}
// Reset as relative to output
src = links.toAbsolute(src, options.base, options.output);
}
else if (origin) {
// Need to downlaod image
toConvert.push({
origin: origin,
source: path.join("./", srcAbs)
});
}
}
$(this).attr("src", src);
});
$("a").each(function() {
var href = $(this).attr("href");
if (links.isRelative(href)) {
var absolutePath = path.join(options.base, href);
// If is in navigation relative: change extsnio nto be .html
if (options.navigation[absolutePath]) href = links.changeExtension(href, ".html");
// Transform as absolute
href = links.toAbsolute(href, options.base, options.output);
} else {
$(this).attr("target", "_blank");
}
// Transform extension
$(this).attr("href", href);
});
// Replace glossayr terms
_.each(options.glossary, function(term) {
var r = new RegExp( "\\b(" + pregQuote(term.name.toLowerCase()) + ")\\b" , 'gi' );
var includedInFiles = false;
$("*").each(function() {
replaceText($, this, r, function(match) {
// Add to files index in glossary
if (!includedInFiles) {
includedInFiles = true;
term.files = term.files || [];
term.files.push(options.navigation[options.input]);
}
return "<a href='"+links.toAbsolute("/GLOSSARY.html", options.base, options.output)+"#"+term.id+"' class='glossary-term' title='"+term.description+"'>"+match+"</a>";
});
});
});
return {
html: renderDom($),
images: toConvert
};
};
// Convert svg images to png
function convertImages(images, options) {
if (!options.convertImages) return Q();
var downloaded = [];
options.book.log.debug.ln("convert ", images.length, "images to png");
return _.reduce(images, function(prev, image) {
var imgin = path.resolve(options.book.options.output, image.source);
return prev
// Write image if need to be download
.then(function() {
if (!image.origin && !_.contains(downloaded, image.origin)) return;
options.book.log.debug("download image", image.origin, "...");
downloaded.push(image.origin);
return options.book.log.debug.promise(fs.writeStream(imgin, request(image.origin)));
})
// Write svg if content
.then(function() {
if (!image.content) return;
return fs.writeFile(imgin, image.content);
})
// Convert
.then(function() {
if (!image.dest) return;
var imgout = path.resolve(options.book.options.output, image.dest);
options.book.log.debug("convert image", image.source, "to", image.dest, "...");
return options.book.log.debug.promise(imgUtils.convertSVG(imgin, imgout));
});
}, Q())
.then(function() {
options.book.log.debug.ok(images.length+" images converted with success");
});
};
// Adapt page content to be relative to a base folder
function normalizePage(sections, options) {
options = _.defaults(options || {}, {
// Current book
book: null,
// Do we need to convert svg?
convertImages: false,
// Current file path
input: ".",
// Navigation to use to transform path
navigation: {},
// Directory parent of the file currently in rendering process
base: "./",
// Directory parent from the html output
output: "./",
// Glossary terms
glossary: []
});
// List of images to convert
var toConvert = [];
sections = _.map(sections, function(section) {
if (section.type != "normal") return section;
var out = normalizeHtml(section.content, options);;
toConvert = toConvert.concat(out.images);
section.content = out.html;
return section;
});
return Q()
.then(function() {
toConvert = _.uniq(toConvert, 'source');
return convertImages(toConvert, options);
})
.thenResolve(sections);
};
// Extract text from sections
function extractText(sections) {
return _.reduce(sections, function(prev, section) {
if (section.type != "normal") return prev;
var $ = cheerio.load(section.content);
$("*").each(function() {
prev = prev+" "+$(this).text();
});
return prev;
}, "");
};
module.exports = {
normalize: normalizePage,
extractText: extractText
};
+58
View File
@@ -0,0 +1,58 @@
var _ = require('lodash');
var path = require('path');
var error = require('./error');
// Normalize a filename
function normalizePath(filename) {
return path.normalize(filename);
}
// Return true if file path is inside a folder
function isInRoot(root, filename) {
filename = path.normalize(filename);
return (filename.substr(0, root.length) === root);
}
// Resolve paths in a specific folder
// Throw error if file is outside this folder
function resolveInRoot(root) {
var input, result;
input = _.chain(arguments)
.toArray()
.slice(1)
.reduce(function(current, p) {
// Handle path relative to book root ("/README.md")
if (p[0] == '/' || p[0] == '\\') return p.slice(1);
return current? path.join(current, p) : path.normalize(p);
}, '')
.value();
result = path.resolve(root, input);
if (!isInRoot(root, result)) {
throw new error.FileOutOfScopeError({
filename: result,
root: root
});
}
return result;
}
// Chnage extension
function setExtension(filename, ext) {
return path.join(
path.dirname(filename),
path.basename(filename, path.extname(filename)) + ext
);
}
module.exports = {
isInRoot: isInRoot,
resolveInRoot: resolveInRoot,
normalize: normalizePath,
setExtension: setExtension
};
-47
View File
@@ -1,47 +0,0 @@
var _ = require("lodash");
// Returns from a navigation and a current file, a snapshot of current detailed state
var calculProgress = function(navigation, current) {
var n = _.size(navigation);
var percent = 0, prevPercent = 0, currentChapter = null;
var done = true;
var chapters = _.chain(navigation)
.map(function(nav, path) {
nav.path = path;
return nav;
})
.map(function(nav, i) {
// Calcul percent
nav.percent = (i * 100) / Math.max((n - 1), 1);
// Is it done
nav.done = done;
if (nav.path == current) {
currentChapter = nav;
percent = nav.percent;
done = false;
} else if (done) {
prevPercent = nav.percent;
}
return nav;
})
.value();
return {
// Previous percent
prevPercent: prevPercent,
// Current percent
percent: percent,
// List of chapter with progress
chapters: chapters,
// Current chapter
current: currentChapter
};
}
module.exports = calculProgress;
+62
View File
@@ -0,0 +1,62 @@
var Q = require('q');
var _ = require('lodash');
// Reduce an array to a promise
function reduce(arr, iter, base) {
return _.reduce(arr, function(prev, elem, i) {
return prev.then(function(val) {
return iter(val, elem, i);
});
}, Q(base));
}
// Transform an array
function serie(arr, iter, base) {
return reduce(arr, function(before, item, i) {
return Q(iter(item, i))
.then(function(r) {
before.push(r);
return before;
});
}, []);
}
// Iter over an array and return first result (not null)
function some(arr, iter) {
return _.reduce(arr, function(prev, elem, i) {
return prev.then(function(val) {
if (val) return val;
return iter(elem, i);
});
}, Q());
}
// Map an array using an async (promised) iterator
function map(arr, iter) {
return reduce(arr, function(prev, entry, i) {
return Q(iter(entry, i))
.then(function(out) {
prev.push(out);
return prev;
});
}, []);
}
// Wrap a fucntion in a promise
function wrap(func) {
return _.wrap(func, function(_func) {
var args = Array.prototype.slice.call(arguments, 1);
return Q()
.then(function() {
return _func.apply(null, args);
});
});
}
module.exports = Q;
module.exports.reduce = reduce;
module.exports.map = map;
module.exports.serie = serie;
module.exports.some = some;
module.exports.wrapfn = wrap;
-32
View File
@@ -1,32 +0,0 @@
var _ = require("lodash");
function escapeShellArg(arg) {
var ret = '';
ret = arg.replace(/"/g, '\\"');
return "\"" + ret + "\"";
}
function optionsToShellArgs(options) {
return _.chain(options)
.map(function(value, key) {
if (value == null || value === false) return null;
if (value === true) return key;
return key+"="+escapeShellArg(value);
})
.compact()
.value()
.join(" ");
}
function escapeRegex(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
module.exports = {
escapeRegex: escapeRegex,
escapeShellArg: escapeShellArg,
optionsToShellArgs: optionsToShellArgs,
toLowerCase: String.prototype.toLowerCase.call.bind(String.prototype.toLowerCase)
};
-38
View File
@@ -1,38 +0,0 @@
var Q = require('q');
var _ = require('lodash');
var path = require('path');
var Gaze = require('gaze').Gaze;
var parsers = require('gitbook-parsers')
function watch(dir) {
var d = Q.defer();
dir = path.resolve(dir);
var toWatch = [
"book.json", "book.js"
];
_.each(parsers.extensions, function(ext) {
toWatch.push("**/*"+ext);
});
var gaze = new Gaze(toWatch, {
cwd: dir
});
gaze.once("all", function(e, filepath) {
gaze.close();
d.resolve(filepath);
});
gaze.once("error", function(err) {
gaze.close();
d.reject(err);
});
return d.promise;
}
module.exports = watch;
+89 -71
View File
@@ -1,74 +1,92 @@
{
"name": "gitbook",
"version": "2.0.0-alpha.7",
"homepage": "https://www.gitbook.com",
"description": "Library and cmd utility to generate GitBooks",
"main": "lib/index.js",
"dependencies": {
"q": "1.0.1",
"lunr": "0.5.7",
"lodash": "2.4.1",
"graceful-fs": "3.0.5",
"resolve": "0.6.3",
"fs-extra": "0.16.3",
"fstream-ignore": "1.0.2",
"gitbook-parsers": "0.4.0",
"nunjucks": "git+https://github.com/SamyPesse/nunjucks.git#4019d1b7379372336b86ce1b0bf84352a2029747",
"nunjucks-autoescape": "0.1.0",
"nunjucks-filter": "0.1.0",
"nunjucks-i18n": "1.0.0",
"semver": "2.2.1",
"npmi": "0.1.1",
"cheerio": "0.18.0",
"gitbook-plugin-livereload": "0.0.1",
"gaze": "~0.5.1",
"send": "0.2.0",
"tiny-lr": "0.1.5",
"tmp": "0.0.24",
"crc": "3.2.1",
"bash-color": "0.0.3",
"URIjs": "1.14.1",
"request": "2.51.0",
"npm": "2.4.1",
"dom-serializer": "0.1.0"
"name": "gitbook",
"version": "3.0.0-pre.4",
"homepage": "https://www.gitbook.com",
"description": "Library and cmd utility to generate GitBooks",
"main": "lib/index.js",
"dependencies": {
"bash-color": "0.0.3",
"cheerio": "0.20.0",
"chokidar": "1.4.3",
"cp": "0.2.0",
"cpr": "1.0.0",
"crc": "3.4.0",
"deprecated": "0.0.1",
"destroy": "1.0.4",
"direction": "0.1.5",
"dom-serializer": "0.1.0",
"error": "7.0.2",
"escape-string-regexp": "1.0.5",
"eslint": "^2.2.0",
"front-matter": "2.0.6",
"gitbook-asciidoc": "1.0.2",
"gitbook-markdown": "1.0.3",
"gitbook-plugin-fontsettings": "1.0.2",
"gitbook-plugin-highlight": "2.0.0",
"gitbook-plugin-livereload": "0.0.1",
"gitbook-plugin-search": "1.2.0",
"gitbook-plugin-sharing": "1.0.1",
"gitbook-plugin-theme-default": "1.0.0-pre.4",
"github-slugid": "1.0.0",
"graceful-fs": "4.1.3",
"i18n-t": "1.0.0",
"ignore": "3.0.3",
"json-schema-defaults": "0.1.1",
"jsonschema": "1.1.0",
"juice": "1.10.0",
"lodash": "3.10.1",
"merge-defaults": "0.2.1",
"mkdirp": "0.5.1",
"moment": "2.11.2",
"npm": "3.7.5",
"npmi": "1.0.1",
"nunjucks": "2.3.0",
"nunjucks-autoescape": "1.0.1",
"q": "1.4.1",
"request": "2.69.0",
"resolve": "0.6.3",
"rmdir": "1.2.0",
"semver": "5.1.0",
"send": "0.13.1",
"spawn-cmd": "0.0.2",
"tiny-lr": "0.2.1",
"tmp": "0.0.28",
"urijs": "1.17.1"
},
"devDependencies": {
"eslint": "2.2.0",
"mocha": "2.4.5",
"should": "8.2.2"
},
"scripts": {
"test": "node_modules/.bin/mocha --reporter spec --bail --timeout 15000 ./test/all.js",
"lint": "eslint ."
},
"repository": {
"type": "git",
"url": "https://github.com/GitbookIO/gitbook.git"
},
"bin": {
"gitbook": "./bin/gitbook.js"
},
"keywords": [
"git",
"book",
"gitbook"
],
"author": "FriendCode Inc. <contact@gitbook.com>",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/GitbookIO/gitbook/issues"
},
"contributors": [
{
"name": "Aaron O'Mullan",
"email": "aaron@gitbook.com"
},
"devDependencies": {
"mocha": "1.18.2",
"grunt": "~0.4.2",
"grunt-cli": "0.1.11",
"grunt-contrib-copy": "0.5.0",
"grunt-contrib-less": "~0.5.0",
"grunt-contrib-requirejs": "0.4.1",
"grunt-bower-install-simple": "0.9.2"
},
"scripts": {
"test": "export TESTING=true; mocha --reporter list --timeout 15000"
},
"repository": {
"type": "git",
"url": "https://github.com/GitbookIO/gitbook.git"
},
"bin": {
"gitbook": "./bin/gitbook.js"
},
"keywords": [
"git",
"book",
"gitbook"
],
"author": "FriendCode Inc. <contact@gitbook.com>",
"license": "Apache 2",
"bugs": {
"url": "https://github.com/GitbookIO/gitbook/issues"
},
"contributors": [
{
"name": "Aaron O'Mullan",
"email": "aaron@gitbook.com"
},
{
"name": "Samy Pessé",
"email": "samy@gitbook.com"
}
]
{
"name": "Samy Pessé",
"email": "samy@gitbook.com"
}
]
}
+33
View File
@@ -0,0 +1,33 @@
// Module API
require('./exports');
// Utilities
require('./location');
require('./paths');
// Parsing
require('./locate');
require('./config');
require('./readme');
require('./summary');
require('./glossary');
require('./langs');
require('./parse');
require('./git');
require('./plugins');
require('./template');
require('./conrefs');
// Page and HTML generation
require('./page');
// Output
require('./assets-inliner');
require('./output-json');
require('./output-website');
require('./output-ebook');
// Misc
require('./init');
+75
View File
@@ -0,0 +1,75 @@
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var cheerio = require('cheerio');
var should = require('should');
// Assertions to test if an Output has generated a file
should.Assertion.add('file', function(file, description) {
var rootFolder;
if (_.isFunction(this.obj.root)) {
rootFolder = this.obj.root();
} else {
rootFolder = this.obj;
}
this.params = {
actual: rootFolder,
operator: 'have file ' + file,
message: description
};
if (_.isFunction(this.obj.resolve)) {
file = this.obj.resolve(file);
} else {
file = path.resolve(rootFolder, file);
}
this.assert(fs.existsSync(file));
});
should.Assertion.add('html', function(rules, description) {
this.params = { actual: 'HTML string', operator: 'valid html', message: description };
var $ = cheerio.load(this.obj);
_.each(rules, function(validations, query) {
validations = _.defaults(validations || {}, {
// Select a specific element in the list of matched elements
index: null,
// Check that there is the correct count of elements
count: 1,
// Check attribute values
attributes: {},
// Trim inner text
trim: false,
// Check inner text
text: undefined
});
var $el = $(query);
// Select correct element
if (_.isNumber(validations.index)) $el = $($el.get(validations.index));
// Test number of elements
$el.length.should.be.equal(validations.count);
// Test text
if (validations.text !== undefined) {
var text = $el.text();
if (validations.trim) text = text.trim();
text.should.be.equal(validations.text);
}
// Test attributes
_.each(validations.attributes, function(value, name) {
var attr = $el.attr(name);
should(attr).be.ok();
attr.should.be.equal(value);
});
});
});

Some files were not shown because too many files have changed in this diff Show More