You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const path = require('path');
  3. const trimRepeated = require('trim-repeated');
  4. const filenameReservedRegex = require('filename-reserved-regex');
  5. const stripOuter = require('strip-outer');
  6. // Doesn't make sense to have longer filenames
  7. const MAX_FILENAME_LENGTH = 100;
  8. const reControlChars = /[\u0000-\u001f\u0080-\u009f]/g; // eslint-disable-line no-control-regex
  9. const reRelativePath = /^\.+/;
  10. const fn = (string, options) => {
  11. if (typeof string !== 'string') {
  12. throw new TypeError('Expected a string');
  13. }
  14. options = options || {};
  15. const replacement = options.replacement === undefined ? '!' : options.replacement;
  16. if (filenameReservedRegex().test(replacement) && reControlChars.test(replacement)) {
  17. throw new Error('Replacement string cannot contain reserved filename characters');
  18. }
  19. string = string.replace(filenameReservedRegex(), replacement);
  20. string = string.replace(reControlChars, replacement);
  21. string = string.replace(reRelativePath, replacement);
  22. if (replacement.length > 0) {
  23. string = trimRepeated(string, replacement);
  24. string = string.length > 1 ? stripOuter(string, replacement) : string;
  25. }
  26. string = filenameReservedRegex.windowsNames().test(string) ? string + replacement : string;
  27. string = string.slice(0, MAX_FILENAME_LENGTH);
  28. return string;
  29. };
  30. fn.path = (pth, options) => {
  31. pth = path.resolve(pth);
  32. return path.join(path.dirname(pth), fn(path.basename(pth), options));
  33. };
  34. module.exports = fn;