summaryrefslogtreecommitdiffstats
path: root/lib/init.js
blob: 2fc8016c9b6e8ed2988872411252a29ead1b4d45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var _ = require('lodash');
var Q = require('q');
var path = require('path');

var Book = require('./book');
var fs = require('./utils/fs');

// Initialize folder structure for a book
// Read SUMMARY to created the right chapter
function initBook(root, opts) {
    var book = new Book(root, opts);
    var extensionToUse = '.md';

    var chaptersPaths = function(chapters) {
        return _.reduce(chapters || [], function(accu, chapter) {
            var o = {
                title: chapter.title
            };
            if (chapter.path) o.path = chapter.path;

            return accu.concat(
                [o].concat(chaptersPaths(chapter.articles))
            );
        }, []);
    };

    book.log.info.ln('init book at', root);
    return fs.mkdirp(root)
    .then(function() {
        book.log.info.ln('detect structure from SUMMARY (if it exists)');
        return book.parseSummary();
    })
    .fail(function() {
        return Q();
    })
    .then(function() {
        var summary = book.summaryFile || 'SUMMARY.md';
        var chapters = book.summary.chapters || [];
        extensionToUse = path.extname(summary);

        if (chapters.length === 0) {
            chapters = [
                {
                    title: 'Summary',
                    path: 'SUMMARY'+extensionToUse
                },
                {
                    title: 'Introduction',
                    path: 'README'+extensionToUse
                }
            ];
        }

        return Q(chaptersPaths(chapters));
    })
    .then(function(chapters) {
        // Create files that don't exist
        return Q.all(_.map(chapters, function(chapter) {
            if (!chapter.path) return Q();
            var absolutePath = path.resolve(book.root, chapter.path);

            return fs.exists(absolutePath)
            .then(function(exists) {
                if(exists) {
                    book.log.info.ln('found', chapter.path);
                    return;
                } else {
                    book.log.info.ln('create', chapter.path);
                }

                return fs.mkdirp(path.dirname(absolutePath))
                .then(function() {
                    return fs.writeFile(absolutePath, '# '+chapter.title+'\n');
                });
            });
        }));
    })
    .then(function() {
        book.log.info.ln('initialization is finished');
    });
}

module.exports = initBook;