Update JSON API
[src/app-framework-demo.git] / afm-client / bower_components / foundation-apps / bin / gulp-dynamic-routing.js
1 var through     = require('through2');
2 var gutil       = require('gulp-util');
3 var fm          = require('front-matter');
4 var PluginError = gutil.PluginError;
5 var path        = require('path');
6 var fs           = require('fs');
7
8 module.exports = function(options) {
9   var configs = [];
10   var directory = options.dir || process.cwd();
11
12   function bufferContents(file, enc, cb) {
13     var config;
14     var content;
15
16     if(file.isNull()) return cb(null, file);
17
18     if(file.isBuffer()) {
19       try {
20         content = fm(String(file.contents));
21       } catch (e) {
22         return cb(new PluginError('Gulp Dynamic Routing', e));
23       }
24
25       if(content.attributes.name) {
26         file.contents = new Buffer(content.body);
27         config = content.attributes;
28         var relativePath = path.relative(directory + path.sep + options.root, file.path);
29         config.path = relativePath.split(path.sep).join('/');
30         configs.push(config);
31       }
32     }
33
34     this.push(file);
35
36     return cb();
37   }
38
39   function endStream(cb) {
40     var self = this;
41     var appPath = options.path;
42
43     configs.sort(function(a, b) {
44       return a.url < b.url;
45     });
46
47
48     fs.writeFile(appPath, 'var foundationRoutes = ' + JSON.stringify(configs) + '; \n', function(err) {
49       if(err) throw err;
50       cb();
51     });
52
53   }
54
55   return through.obj(bufferContents, endStream);
56 };