summaryrefslogtreecommitdiffstats
path: root/lib/book.js
blob: c211adff4de91238f57e9fd5dd9cea062ab945d6 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
var _ = require('lodash');
var path = require('path');
var Ignore = require('ignore');
var parsers = require('gitbook-parsers');

var Logger = require('./logger');
var Config = require('./config');
var Readme = require('./backbone/readme');
var Glossary = require('./backbone/glossary');
var Summary = require('./backbone/summary');
var Langs = require('./backbone/langs');
var Page = require('./backbone/page');
var pathUtil = require('./utils/path');
var Promise = require('./utils/promise');

function Book(opts) {
    if (!(this instanceof Book)) return new Book(opts);

    opts = _.defaults(opts || {}, {
        fs: null,

        // Root path for the book
        root: '',

        // Extend book configuration
        config: {},

        // Log function
        log: function(msg) {
            process.stdout.write(msg);
        },

        // Log level
        logLevel: 'info'
    });

    if (!opts.fs) throw new Error('Book requires a fs instance');

    // Root path for the book
    this.root = opts.root;

    // If multi-lingual, book can have a parent
    this.parent = opts.parent;

    // A book is linked to an fs, to access its content
    this.fs = opts.fs;

    // Rules to ignore some files
    this.ignore = Ignore();
    this.ignore.addPattern([
        // Skip Git stuff
        '.git/',
        '.gitignore',

        // Skip OS X meta data
        '.DS_Store',

        // Skip stuff installed by plugins
        'node_modules',

        // Skip book outputs
        '_book',
        '*.pdf',
        '*.epub',
        '*.mobi',

        // Skip config files
        '.ignore',
        '.bookignore',
        'book.json'
    ]);

    // Create a logger for the book
    this.log = new Logger(opts.log, opts.logLevel);

    // Create an interface to access the configuration
    this.config = new Config(this, opts.config);

    // Interfaces for the book structure
    this.readme = new Readme(this);
    this.summary = new Summary(this);
    this.glossary = new Glossary(this);

    // Multilinguals book
    this.langs = new Langs(this);
    this.books = [];

    // List of page in the book
    this.pages = {};

    _.bindAll(this);
}

// Parse and prepare the configuration, fail if invalid
Book.prototype.prepareConfig = function() {
    return this.config.load();
};

// Resolve a path in the book source
// Enforce that the output path is in the scope
Book.prototype.resolve = function() {
    var filename = path.resolve.apply(path, [this.root].concat(_.toArray(arguments)));
    if (!this.isFileInScope(filename)) {
        var err = new Error('EACCESS: "' + filename + '" not in "' + this.root + '"');
        err.code = 'EACCESS';
        throw err;
    }

    return filename;
};

// Return false if a file is outside the book' scope
Book.prototype.isFileInScope = function(filename) {
    filename = path.resolve(this.root, filename);

    // Is the file in the scope of the parent?
    if (this.parent && this.parent.isFileInScope(filename)) return true;

    // Is file in the root folder?
    return pathUtil.isInRoot(this.root, filename);
};

// Parse .gitignore, etc to extract rules
Book.prototype.parseIgnoreRules = function() {
    var that = this;

    return Promise.series([
        '.ignore',
        '.gitignore',
        '.bookignore'
    ], function(filename) {
        return that.readFile(filename)
        .then(function(content) {
            that.ignore.addPattern(content.toString().split(/\r?\n/));
        });
    });
};

// Parse the whole book
Book.prototype.parse = function() {
    var that = this;

    return Promise()
    .then(this.prepareConfig)
    .then(this.parseIgnoreRules)

    // Parse languages
    .then(function() {
        return that.langs.load();
    })

    .then(function() {
        if (that.isMultilingual()) {
            if (that.isLanguageBook()) {
                throw new Error('A multilingual book as a language book is forbidden');
            }

            that.log.info.ln('Parsing multilingual book, with', that.langs.count(), 'languages');

            // Create a new book for each language and parse it
            return Promise.serial(that.langs.list(), function(lang) {
                that.log.debug.ln('Preparing book for language', lang.id);
                var langBook = new Book({
                    fs: that.fs,
                    parent: that,
                    root: that.resolve(lang.id)
                });

                that.books.push(langBook);

                return langBook.parse();
            });
        }

        return Promise()
        .then(that.readme.load)
        .then(function() {
            if (that.readme.exists()) return;

            throw new Error('No README file (or is ignored)');
        })

        .then(that.summary.load)
        .then(function() {
            if (that.summary.exists()) return;

            throw new Error('No SUMMARY file (or is ignored)');
        })

        .then(that.glossary.load);
    });
};

// Mark a filename as being parsable
Book.prototype.addPage = function(filename) {
    filename = pathUtil.normalize(filename);

    if (this.pages[filename]) return;
    this.pages[filename] = new Page(this, filename);
};

// Return a page by its filename (or undefined)
Book.prototype.getPage = function(filename) {
    filename = pathUtil.normalize(filename);
    return this.pages[filename];
};


// Return true, if has a specific page
Book.prototype.hasPage = function(filename) {
    return Boolean(this.getPage(filename));
};

// Test if a file is ignored, return true if it is
Book.prototype.isFileIgnored = function(filename) {
    return this.ignore.filter([filename]).length == 0;
};

// Read a file in the book, throw error if ignored
Book.prototype.readFile = function(filename) {
    if (this.isFileIgnored(filename)) return Promise.reject(new Error('File "'+filename+'" is ignored'));
    return this.fs.readAsString(this.resolve(filename));
};

// Find a parsable file using a filename
Book.prototype.findParsableFile = function(filename) {
    var that = this;

    var ext = path.extname(filename);
    var basename = path.basename(filename, ext);

    // Ordered list of extensions to test
    var exts = parsers.extensions;
    if (ext) exts = _.uniq([ext].concat(exts));

    return _.reduce(exts, function(prev, ext) {
        return prev.then(function(output) {
            // Stop if already find a parser
            if (output) return output;

            var filepath = basename+ext;

            return that.fs.findFile(that.root, filepath)
            .then(function(realFilepath) {
                if (!realFilepath) return null;

                return {
                    parser: parsers.get(ext),
                    path: realFilepath
                };
            });
        });
    }, Promise(null));
};

// Return true if book is associated to a language
Book.prototype.isLanguageBook = function() {
    return Boolean(this.parent);
};
Book.prototype.isSubBook = Book.prototype.isLanguageBook;

// Return true if the book is main instance of a multilingual book
Book.prototype.isMultilingual = function() {
    return this.langs.count() > 0;
};

// Return true if file is in the scope of a child book
Book.prototype.isInLanguageBook = function(filename) {
    return _.some(this.langs.list(), function(lang) {
        return pathUtil.isInRoot(
            this.resolve(lang.id),
            this.resolve(filename)
        );
    });
};

module.exports = Book;