UNPKG

2.43 kBJavaScriptView Raw
1var _ = require('lodash');
2var Q = require('q');
3var path = require('path');
4
5var Book = require('./book');
6var fs = require('./utils/fs');
7
8// Initialize folder structure for a book
9// Read SUMMARY to created the right chapter
10function initBook(root, opts) {
11 var book = new Book(root, opts);
12 var extensionToUse = '.md';
13
14 var chaptersPaths = function(chapters) {
15 return _.reduce(chapters || [], function(accu, chapter) {
16 var o = {
17 title: chapter.title
18 };
19 if (chapter.path) o.path = chapter.path;
20
21 return accu.concat(
22 [o].concat(chaptersPaths(chapter.articles))
23 );
24 }, []);
25 };
26
27 book.log.info.ln('init book at', root);
28 return fs.mkdirp(root)
29 .then(function() {
30 book.log.info.ln('detect structure from SUMMARY (if it exists)');
31 return book.parseSummary();
32 })
33 .fail(function() {
34 return Q();
35 })
36 .then(function() {
37 var summary = book.summaryFile || 'SUMMARY.md';
38 var chapters = book.summary.chapters || [];
39 extensionToUse = path.extname(summary);
40
41 if (chapters.length === 0) {
42 chapters = [
43 {
44 title: 'Summary',
45 path: 'SUMMARY'+extensionToUse
46 },
47 {
48 title: 'Introduction',
49 path: 'README'+extensionToUse
50 }
51 ];
52 }
53
54 return Q(chaptersPaths(chapters));
55 })
56 .then(function(chapters) {
57 // Create files that don't exist
58 return Q.all(_.map(chapters, function(chapter) {
59 if (!chapter.path) return Q();
60 var absolutePath = path.resolve(book.root, chapter.path);
61
62 return fs.exists(absolutePath)
63 .then(function(exists) {
64 if(exists) {
65 book.log.info.ln('found', chapter.path);
66 return;
67 } else {
68 book.log.info.ln('create', chapter.path);
69 }
70
71 return fs.mkdirp(path.dirname(absolutePath))
72 .then(function() {
73 return fs.writeFile(absolutePath, '# '+chapter.title+'\n');
74 });
75 });
76 }));
77 })
78 .then(function() {
79 book.log.info.ln('initialization is finished');
80 });
81}
82
83module.exports = initBook;