UNPKG

2.8 kBJavaScriptView Raw
1
2/*******************************
3 Summarize Docs
4*******************************/
5
6var
7 // node dependencies
8 console = require('better-console'),
9 fs = require('fs'),
10 YAML = require('yamljs')
11;
12
13var data = {};
14
15/**
16 * Test for prefix in string.
17 * @param {string} str
18 * @param {string} prefix
19 * @return {boolean}
20 */
21function startsWith(str, prefix) {
22 return str.indexOf(prefix) === 0;
23};
24
25function inArray(needle, haystack) {
26 var length = haystack.length;
27 for(var i = 0; i < length; i++) {
28 if(haystack[i] == needle) return true;
29 }
30 return false;
31}
32
33/**
34 * Parses a file for metadata and stores result in data object.
35 * @param {File} file - object provided by map-stream.
36 * @param {function(?,File)} - callback provided by map-stream to
37 * reply when done.
38 */
39function parser(file, callback) {
40 // file exit conditions
41 if(file.isNull()) {
42 return callback(null, file); // pass along
43 }
44
45 if(file.isStream()) {
46 return callback(new Error('Streaming not supported'));
47 }
48
49 try {
50
51 var
52 /** @type {string} */
53 text = String(file.contents.toString('utf8')),
54 lines = text.split('\n'),
55 filename = file.path.substring(0, file.path.length - 4),
56 key = 'server/documents',
57 position = filename.indexOf(key)
58 ;
59
60 // exit conditions
61 if(!lines) {
62 return;
63 }
64 if(position < 0) {
65 return callback(null, file);
66 }
67
68 filename = filename.substring(position + key.length + 1, filename.length);
69
70 var
71 lineCount = lines.length,
72 active = false,
73 yaml = [],
74 categories = [
75 'UI Element',
76 'UI Global',
77 'UI Collection',
78 'UI View',
79 'UI Module',
80 'UI Behavior'
81 ],
82 index,
83 meta,
84 line
85 ;
86
87 for(index = 0; index < lineCount; index++) {
88
89 line = lines[index];
90
91 // Wait for metadata block to begin
92 if(!active) {
93 if(startsWith(line, '---')) {
94 active = true;
95 }
96 continue;
97 }
98 // End of metadata block, stop parsing.
99 if(startsWith(line, '---')) {
100 break;
101 }
102 yaml.push(line);
103 }
104
105
106 // Parse yaml.
107 meta = YAML.parse(yaml.join('\n'));
108 if(meta && meta.type && meta.title && inArray(meta.type, categories) ) {
109 meta.category = meta.type;
110 meta.filename = filename;
111 meta.url = '/' + filename;
112 meta.title = meta.title;
113 // Primary key will by filepath
114 data[meta.element] = meta;
115 }
116 else {
117 // skip
118 // console.log(meta);
119 }
120
121
122 }
123
124 catch(error) {
125 console.log(error, filename);
126 }
127
128 callback(null, file);
129
130}
131
132/**
133 * Export function expected by map-stream.
134 */
135module.exports = {
136 result : data,
137 parser : parser
138};