index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. var gutil = require('gulp-util');
  2. var through = require('through2');
  3. var semver = require('semver');
  4. var setDefaultOptions = function(opts) {
  5. opts = opts || {};
  6. opts.key = opts.key || 'version';
  7. opts.indent = opts.indent || void 0;
  8. // default type bump is patch
  9. if (!opts.type || !semver.inc('0.0.1', opts.type)) {
  10. opts.type = 'patch';
  11. }
  12. // if passed specific version - validate it
  13. if (opts.version && !semver.valid(opts.version, opts.type)) {
  14. gutil.log('invalid version used as option', gutil.colors.red(opts.version));
  15. opts.version = null;
  16. }
  17. return opts;
  18. };
  19. // Preserver new line at the end of a file
  20. var possibleNewline = function (json) {
  21. var lastChar = (json.slice(-1) === '\n') ? '\n' : '';
  22. return lastChar;
  23. };
  24. // Figured out which "space" params to be used for JSON.stringfiy.
  25. var space = function space(json) {
  26. var match = json.match(/^(?:(\t+)|( +))"/m);
  27. return match ? (match[1] ? '\t' : match[2].length) : '';
  28. };
  29. module.exports = function(opts) {
  30. // set task options
  31. opts = setDefaultOptions(opts);
  32. var key = opts.key;
  33. var version = opts.version;
  34. var indent = opts.indent;
  35. var type = opts.type;
  36. var content, json;
  37. return through.obj(function(file, enc, cb) {
  38. if (file.isNull()) {
  39. return cb(null, file);
  40. }
  41. if (file.isStream()) {
  42. return cb(new gutil.PluginError('gulp-bump', 'Streaming not supported'));
  43. }
  44. json = file.contents.toString();
  45. try {
  46. content = JSON.parse(json);
  47. } catch (e) {
  48. return cb(new gutil.PluginError('gulp-bump', 'Problem parsing JSON file', {fileName: file.path, showStack: true}));
  49. }
  50. // just set a version to the key
  51. if (version) {
  52. if (!content[key]) {
  53. // log to user that key didn't exist before
  54. gutil.log('Creating key', gutil.colors.red(key), 'with version:', gutil.colors.cyan(version));
  55. }
  56. content[key] = version;
  57. }
  58. else if (semver.valid(content[key])) {
  59. // increment the key with type
  60. content[key] = semver.inc(content[key], type);
  61. }
  62. else {
  63. return cb(new gutil.PluginError('gulp-bump', 'Detected invalid semver ' + key, {fileName: file.path, showStack: false}));
  64. }
  65. file.contents = new Buffer(JSON.stringify(content, null, indent || space(json)) + possibleNewline(json));
  66. gutil.log('Bumped ' + gutil.colors.magenta(key) + ' to: ' + gutil.colors.cyan(content[key]));
  67. cb(null, file);
  68. });
  69. };