summaryrefslogtreecommitdiffstats
path: root/tasks/publish.js
blob: 9c3d1d6362d1d92ffcf8de5a8f0780037f6cddb5 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
var _ = require('underscore'),
    async = require('async'),
    AWS = require('aws-sdk'),
    git = require('./util/git');

module.exports = function(grunt) {
  grunt.registerTask('publish', function() {
    var done = this.async();
    initSDK();

    git.commitInfo(function(err, info) {
      if (info.isMaster) {
        publish(fileMap(['-latest', '-' + info.head]), done);
      } else {
        // Silently ignore for branches
        done();
      }
    });
  });
  grunt.registerTask('publish:version', function() {
    var done = this.async();
    initSDK();

    git.commitInfo(function(err, info) {
      if (!info.tagName) {
        throw new Error('The current commit must be tagged');
      }
      publish(fileMap(['-' + info.tagName]), done);
    });
  });

  function initSDK() {
    var bucket = process.env.S3_BUCKET_NAME,
        key = process.env.S3_ACCESS_KEY_ID,
        secret = process.env.S3_SECRET_ACCESS_KEY;

    if (!bucket || !key || !secret) {
      throw new Error('Missing S3 config values');
    }

    AWS.config.update({accessKeyId: key, secretAccessKey: secret});
  }
  function publish(files, callback) {
    var s3 = new AWS.S3(),
        bucket = process.env.S3_BUCKET_NAME;

    async.forEach(_.keys(files), function(file, callback) {
        var params = {Bucket: bucket, Key: file, Body: grunt.file.read(files[file])};
        s3.putObject(params, function(err, data) {
          if (err) {
            throw err;
          } else {
            grunt.log.writeln('Published ' + file + ' to build server.');
            callback();
          }
        });
      },
      callback);
  }
  function fileMap(suffixes) {
    var map = {};
    _.each(['handlebars.js', 'handlebars.min.js', 'handlebars.runtime.js', 'handlebars.runtime.min.js'], function(file) {
      _.each(suffixes, function(suffix) {
        map[file.replace(/\.js$/, suffix + '.js')] = 'dist/' + file;
      });
    });
    return map;
  }
};