index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. var Stream = require('stream');
  3. var Path = require('path');
  4. function gulpRename(obj, options) {
  5. options = options || {};
  6. var stream = new Stream.Transform({ objectMode: true });
  7. function parsePath(path) {
  8. var extname = options.multiExt
  9. ? Path.basename(path).slice(Path.basename(path).indexOf('.'))
  10. : Path.extname(path);
  11. return {
  12. dirname: Path.dirname(path),
  13. basename: Path.basename(path, extname),
  14. extname: extname
  15. };
  16. }
  17. stream._transform = function(originalFile, unused, callback) {
  18. var file = originalFile.clone({ contents: false });
  19. var parsedPath = parsePath(file.relative);
  20. var path;
  21. var type = typeof obj;
  22. if (type === 'string' && obj !== '') {
  23. path = obj;
  24. } else if (type === 'function') {
  25. let newParsedPath = obj(parsedPath, file);
  26. if (typeof newParsedPath === 'object' && newParsedPath !== null) {
  27. parsedPath = newParsedPath;
  28. }
  29. path = Path.join(
  30. parsedPath.dirname,
  31. parsedPath.basename + parsedPath.extname
  32. );
  33. } else if (type === 'object' && obj !== undefined && obj !== null) {
  34. var dirname = 'dirname' in obj ? obj.dirname : parsedPath.dirname,
  35. prefix = obj.prefix || '',
  36. suffix = obj.suffix || '',
  37. basename = 'basename' in obj ? obj.basename : parsedPath.basename,
  38. extname = 'extname' in obj ? obj.extname : parsedPath.extname;
  39. path = Path.join(dirname, prefix + basename + suffix + extname);
  40. } else {
  41. callback(
  42. new Error('Unsupported renaming parameter type supplied'),
  43. undefined
  44. );
  45. return;
  46. }
  47. file.path = Path.join(file.base, path);
  48. // Rename sourcemap if present
  49. if (file.sourceMap) {
  50. file.sourceMap.file = file.relative;
  51. }
  52. callback(null, file);
  53. };
  54. return stream;
  55. }
  56. module.exports = gulpRename;