You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.2 KiB

  1. /*******************************
  2. Summarize Docs
  3. *******************************/
  4. var
  5. // node dependencies
  6. console = require('better-console'),
  7. fs = require('fs'),
  8. YAML = require('yamljs')
  9. ;
  10. var data = {};
  11. /**
  12. * Test for prefix in string.
  13. * @param {string} str
  14. * @param {string} prefix
  15. * @return {boolean}
  16. */
  17. function startsWith(str, prefix) {
  18. return str.indexOf(prefix) === 0;
  19. };
  20. /**
  21. * Parses a file for metadata and stores result in data object.
  22. * @param {File} file - object provided by map-stream.
  23. * @param {function(?,File)} - callback provided by map-stream to
  24. * reply when done.
  25. */
  26. function parseFile(file, cb) {
  27. if (file.isNull())
  28. return cb(null, file); // pass along
  29. if (file.isStream())
  30. return cb(new Error("Streaming not supported"));
  31. try {
  32. var
  33. /** @type {string} */
  34. text = String(file.contents.toString('utf8')),
  35. lines = text.split('\n');
  36. if (!lines)
  37. return;
  38. var filename = file.path;
  39. filename = filename.substring(0, filename.length - 4);
  40. var key = 'server/documents';
  41. var position = filename.indexOf(key);
  42. if (position < 0)
  43. return cb(null, file);
  44. filename = filename.substring(position + key.length + 1, filename.length);
  45. //console.log('Parsing ' + filename);
  46. var n = lines.length,
  47. active = false,
  48. yaml = [],
  49. line
  50. ;
  51. var line;
  52. for (var i = 0; i < n; i++) {
  53. line = lines[i];
  54. // Wait for metadata block to begin
  55. if (!active) {
  56. if (startsWith(line, '---'))
  57. active = true;
  58. continue;
  59. }
  60. // End of metadata block, stop parsing.
  61. if (startsWith(line, '---'))
  62. break;
  63. yaml.push(line);
  64. }
  65. // Parse yaml.
  66. var meta = YAML.parse(yaml.join('\n'));
  67. meta.category = meta.type;
  68. meta.filename = filename;
  69. meta._title = meta.title; // preserve original, just in case
  70. meta.title = meta.type + ': ' + meta.title;
  71. // Primary key will by filepath
  72. data[filename] = meta;
  73. //console.log("Parsed " + filename + ": " + JSON.stringify(meta));
  74. } catch(e) {
  75. console.log(e);
  76. }
  77. cb(null,file);
  78. }
  79. /**
  80. * Export function expected by map-stream.
  81. */
  82. module.exports = {
  83. result: data,
  84. parser: parseFile
  85. };