commit.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. var fs = require('fs');
  3. var path = require('path');
  4. var through = require('through2');
  5. var mkdirp = require('mkdirp');
  6. var rimraf = require('rimraf');
  7. function write(file) {
  8. var dir = path.dirname(file.path);
  9. if (!fs.existsSync(dir)) {
  10. mkdirp.sync(dir);
  11. }
  12. fs.writeFileSync(file.path, file.contents, {
  13. mode: file.stat ? file.stat.mode : null
  14. });
  15. }
  16. function remove(file) {
  17. rimraf.sync(file.path);
  18. }
  19. module.exports = function (filters, cb) {
  20. var store = this.store;
  21. if (arguments.length === 1) {
  22. cb = filters;
  23. filters = [];
  24. }
  25. var modifiedFilter = through.obj(function (file, enc, cb) {
  26. // Don't process deleted file who haven't been commited yet.
  27. if (file.state === 'modified' || (file.state === 'deleted' && !file.isNew)) {
  28. this.push(file);
  29. }
  30. cb();
  31. });
  32. var commitFilter = through.obj(function (file, enc, cb) {
  33. store.add(file);
  34. if (file.state === 'modified') {
  35. write(file);
  36. } else if (file.state === 'deleted') {
  37. remove(file);
  38. }
  39. delete file.state;
  40. delete file.isNew;
  41. cb();
  42. });
  43. filters.unshift(modifiedFilter);
  44. filters.push(commitFilter);
  45. var stream = filters.reduce(function (stream, filter) {
  46. return stream.pipe(filter);
  47. }, this.store.stream());
  48. stream.on('finish', cb);
  49. };