Parse readme from book

@param {Book} book
@return {Promise<Book>}
346686
function parseReadme(book) {
    var logger = book.getLogger();

    return parseStructureFile(book, 'readme')
    .spread(function(file, result) {
        if (!file) {
            throw new error.FileNotFoundError({ filename: 'README' });
        }

        logger.debug.ln('readme found at', file.getPath());

        var readme = Readme.create(file, result);
        return book.set('readme', readme);
    });
}
56431
function loadForBook(book) {
    var logger = book.getLogger();

    // List the dependencies
    var requirements = listDepsForBook(book);

    // List all plugins installed in the book
    return findForBook(book)
    .then(function(installedMap) {
        var missing = [];
        var plugins = requirements.reduce(function(result, dep) {
            var name = dep.getName();
            var installed = installedMap.get(name);

            if (installed) {
                var deps = installedMap
                    .filter(function(plugin) {
                        return plugin.getParent() === name;
                    })
                    .toArray();

                result = result.concat(deps);
                result.push(installed);
            } else {
                missing.push(name);
            }

            return result;
        }, []);

        // Convert plugins list to a map
        plugins = Immutable.List(plugins)
            .map(function(plugin) {
                return [
                    plugin.getName(),
                    plugin
                ];
            });
        plugins = Immutable.OrderedMap(plugins);

        // Log state
        logger.info.ln(installedMap.size + ' plugins are installed');
        if (requirements.size != installedMap.size) {
            logger.info.ln(requirements.size + ' explicitly listed');
        }

        // Verify that all plugins are present
        if (missing.length > 0) {
            throw new Error('Couldn\'t locate plugins "' + missing.join(', ') + '", Run \'gitbook install\' to install plugins from registry.');
        }

        return Promise.map(plugins, function(plugin) {
            return loadPlugin(book, plugin);
        });
    });
}
775987
function validateConfig(book, plugins) {
    return Promise.reduce(plugins, function(newBook, plugin) {
        return validatePluginConfig(newBook, plugin);
    }, book);
}
939734
function processSection(section) {
  var result = {};
  var bookRegexp = new RegExp(language.bookRegexp, 'i');
  var match = section.match(bookRegexp);
  var book = match && match.length ? match[0] : '';
  var noBook = book ? section.replace(book, '').replace(' ', '') : section;
  var chapterVerseSplit = noBook.split(':').filter(valid);
  // TODO: match '.' or ':' for seperator
  // '1.2'.match(/(\d+)(:|\.)*(\d+)*/) => ["1.2", "1", ".", "2"]

  currentSection++;

  if (book) {
    result.book = bookKey(book);
  }

  if (chapterVerseSplit[0]) {
    result[currentSection === 2 && isNum(lastSection.verse) && chapterVerseSplit.length === 1 ? 'verse' : 'chapter'] = Number(chapterVerseSplit[0]);
  }

  if (chapterVerseSplit[1] && !isNum(result.verse)) {
    result.verse = Number(chapterVerseSplit[1]);
  }

  lastSection = result;
  return result;
}
204184
function parseFilePage(book, filePath) {
    var fs = book.getContentFS();

    return fs.statFile(filePath)
    .then(
        function(file) {
            var page = Page.createForFile(file);
            return parsePage(book, page);
        },
        function(err) {
            // file doesn't exist
            return null;
        }
    )
    .fail(function(err) {
        var logger = book.getLogger();
        logger.error.ln('error while parsing page "' + filePath + '":');
        throw err;
    });
}
324050
function createReadFilePromise () {
  return (filepath) => {
    return new Promise((resolve, reject) => {
      fs.readFile(filepath, 'utf8', function (error, data) {
        if (error) {
          reject(new Error(`Cannot read ${filepath}, got: ${error}`))
        } else if (!data) {
          reject(new Error(`No content at ${filepath}`))
        } else {
          resolve(data.split('\n'))
        }
      })
    })
  }
}
980896
function readFile (file, options) {
    // return new Promise that will be resolved with data
    return new Promise((resolve, reject) => {
        // create write stream
        this.createReadStream(file, options).then(stream => {
            // create new concat stream that will call back with stream data
            var concatStream = ConcatStream(buffer => {
                // resolve with string if encoding set or buffer
                var data = defined(options) && defined(options.encoding)
                    ? buffer.toString(options.encoding)
                    : buffer
                // resolve with data
                resolve(data)
            })
            // reject on errors
            stream.on('error', reject)
            // pipe read stream to concat stream which will resolve when done
            stream.pipe(concatStream)
        })
        // pass rejection
        .catch(reject)
    })
}
538245
function readFile(options, href) {
	var filePath = path.join(path.isAbsolute(href) ? options.root : path.dirname(options.from), href);

	return new Promise(function (resolve, reject) {
		return fs.readFile(filePath, 'utf8', function (err, res) {
			return err ? reject(err) : resolve(res);
		});
	});
}
1317272
function readFile() {
                    return new Promise(function (resolve, reject) {
                        /** @type {?} */
                        var reader = new FileReader();
                        reader.onload = function (event) {
                            resolve(reader.result);
                        };
                        reader.onerror = function (err) {
                            reject(err);
                        };
                        reader.readAsDataURL(file);
                    });
                }
621367
function readdir (archive, name, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }
  opts = opts || {}

  return maybe(cb, async function () {
    // options
    var recursive = (opts && !!opts.recursive)

    // run first readdir
    var promise = new Promise((resolve, reject) => {
      archive.readdir(name, (err, names) => {
        if (err) reject(toBeakerError(err, 'readdir'))
        else resolve(names)
      })
    })
    var results = await promise

    // recurse if requested
    if (recursive) {
      var rootPath = name
      const readdirSafe = name => new Promise(resolve => {
        archive.readdir(name, (_, names) => resolve(names || []))
      })
      const recurse = async function (names, parentPath) {
        await Promise.all(names.map(async function (name) {
          var thisPath = path.join(parentPath, name)
          var subnames = await readdirSafe(thisPath)
          await recurse(subnames, thisPath)
          results = results.concat(subnames.map(subname => normalize(rootPath, thisPath, subname)))
        }))
      }
      await recurse(results, name)
    }
    return results
  })
}
1020304
function initBook(rootFolder) {
    var extension = '.md';

    return fs.mkdirp(rootFolder)

    // Parse the summary and readme
    .then(function() {
        var fs = createNodeFS(rootFolder);
        var book = Book.createForFS(fs);

        return Parse.parseReadme(book)

        // Setup default readme if doesn't found one
        .fail(function() {
            var readmeFile = File.createWithFilepath('README' + extension);
            var readme = Readme.create(readmeFile);
            return book.setReadme(readme);
        });
    })
    .then(Parse.parseSummary)

    .then(function(book) {
        var logger = book.getLogger();
        var summary = book.getSummary();
        var summaryFile = summary.getFile();
        var summaryFilename = summaryFile.getPath() || ('SUMMARY' + extension);

        var articles = summary.getArticlesAsList();

        // Write pages
        return Promise.forEach(articles, function(article) {
            var articlePath = article.getPath();
            var filePath = articlePath? path.join(rootFolder, articlePath) : null;
            if (!filePath) {
                return;
            }

            return fs.assertFile(filePath, function() {
                return fs.ensureFile(filePath)
                .then(function() {
                    logger.info.ln('create', article.getPath());
                    return fs.writeFile(filePath, '# ' + article.getTitle() + '\n\n');
                });
            });
        })

        // Write summary
        .then(function() {
            var filePath = path.join(rootFolder, summaryFilename);

            return fs.ensureFile(filePath)
            .then(function() {
                logger.info.ln('create ' + path.basename(filePath));
                return fs.writeFile(filePath, summary.toText(extension));
            });
        })

        // Log end
        .then(function() {
            logger.info.ln('initialization is finished');
        });
    });
}
1037000
function StreamReader(read) {

	var tail = '', messages = new Array();

	/**
	 * Parsa new data.
	 * @param {String} data New data from the stream
	 */
	function parse(data, initExpected) {
		var lines, i, last;
		data = tail + data;
		data = data.replace(/\r*\n+/g, "\n");
		lines = data.split("\n");
		last = lines.length - 1;
		for (i = 0; i < last; i++) {
			messages.push(read(lines[i], initExpected));
		}
		tail = lines[lines.length - 1];
	}

	/**
	 * Pop the next message
	 */
	function pop() {
		return messages.shift();
  	}

	/**
	 * Return if it has no more messages
	 */
	function isEmpty() {
		return messages.length == 0;
  	}

	// Public methods
	that = {
		parse: parse,
		pop: pop,
		isEmpty: isEmpty
	};


	return that;
}
36836
function get(data) {
    if ('string' === typeof data) return { content: data };
    if (data.readme) return { content: data.readme, file: 'readme' };
    if (data.content) return data;
  }
2386
function(next) {
            fs.readFile(path.join(config.root_out, config.akashacmsEPUB.bookmetadata.toc.href), 'utf8',
                function(err, data) {
                    if (err) next(err);
                    else {
                        // logger.info('read '+ path.join(config.root_out, config.akashacmsEPUB.bookmetadata.toc.href));
                        tocHtml = data;
                        next();
                    }
                });
        }
219067
function promiseReadFile(path, encoding = 'utf-8') {
  return new Promise((resolve, reject) => {
    fs.readFile(path, encoding, (err, content) => {
      if (err) reject(err);

      resolve({
        path,
        fileName: path.split('/').pop(),
        content
      });
    });
  });
}
936509
function parseFile(target) {
  return new Promise((resolve, reject) => {
    fs.readFile(target, 'utf8', (err, data) => {
      if (err) reject(err)
      // const doc = parser.parseFromString(data, 'application/xml')
      const doc = cheerio.load(data, { xmlMode: true })
      resolve(doc)
    })
  })
}
1030417
async function readFiles (locations) {
  return Promise.all(locations.map((location) => {
    return fs.readFile(location, 'utf-8')
  }))
}