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.

115 lines
2.3 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 parser(file, callback) {
  27. // file exit conditions
  28. if(file.isNull()) {
  29. return callback(null, file); // pass along
  30. }
  31. if(file.isStream()) {
  32. return callback(new Error('Streaming not supported'));
  33. }
  34. try {
  35. var
  36. /** @type {string} */
  37. text = String(file.contents.toString('utf8')),
  38. lines = text.split('\n')
  39. filename = file.path.substring(0, file.path.length - 4),
  40. key = 'server/documents',
  41. position = filename.indexOf(key)
  42. ;
  43. // exit conditions
  44. if(!lines) {
  45. return;
  46. }
  47. if(position < 0) {
  48. return callback(null, file);
  49. }
  50. filename = filename.substring(position + key.length + 1, filename.length);
  51. var
  52. lineCount = lines.length,
  53. active = false,
  54. yaml = [],
  55. index,
  56. meta,
  57. line
  58. ;
  59. for (index = 0; index < lineCount; index++) {
  60. line = lines[index];
  61. // Wait for metadata block to begin
  62. if(!active) {
  63. if(startsWith(line, '---')) {
  64. active = true;
  65. }
  66. continue;
  67. }
  68. // End of metadata block, stop parsing.
  69. if(startsWith(line, '---')) {
  70. break;
  71. }
  72. yaml.push(line);
  73. }
  74. // Parse yaml.
  75. meta = YAML.parse(yaml.join('\n'));
  76. if(meta && meta.category !== 'Draft' && meta.title !== undefined) {
  77. meta.category = meta.type;
  78. meta.filename = filename;
  79. meta.title = meta.title;
  80. }
  81. // Primary key will by filepath
  82. data[filename] = meta;
  83. }
  84. catch(error) {
  85. console.log(error, filename);
  86. }
  87. callback(null, file);
  88. }
  89. /**
  90. * Export function expected by map-stream.
  91. */
  92. module.exports = {
  93. result : data,
  94. parser : parser
  95. };