summaryrefslogtreecommitdiffstats
path: root/afm-client/bower_components/foundation-apps/bin/gulp-dynamic-routing.js
blob: 3dc5350ef9a9ac3c361c770cf03f6c17433ece1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
var through     = require('through2');
var gutil       = require('gulp-util');
var fm          = require('front-matter');
var PluginError = gutil.PluginError;
var path        = require('path');
var fs           = require('fs');

module.exports = function(options) {
  var configs = [];
  var directory = options.dir || process.cwd();

  function bufferContents(file, enc, cb) {
    var config;
    var content;

    if(file.isNull()) return cb(null, file);

    if(file.isBuffer()) {
      try {
        content = fm(String(file.contents));
      } catch (e) {
        return cb(new PluginError('Gulp Dynamic Routing', e));
      }

      if(content.attributes.name) {
        file.contents = new Buffer(content.body);
        config = content.attributes;
        var relativePath = path.relative(directory + path.sep + options.root, file.path);
        config.path = relativePath.split(path.sep).join('/');
        configs.push(config);
      }
    }

    this.push(file);

    return cb();
  }

  function endStream(cb) {
    var self = this;
    var appPath = options.path;

    configs.sort(function(a, b) {
      return a.url < b.url;
    });


    fs.writeFile(appPath, 'var foundationRoutes = ' + JSON.stringify(configs) + '; \n', function(err) {
      if(err) throw err;
      cb();
    });

  }

  return through.obj(bufferContents, endStream);
};