index.js 700 B

1234567891011121314151617181920212223242526272829
  1. 'use strict';
  2. var path = require('path');
  3. var homedir = require('homedir-polyfill');
  4. var isAbsolute = require('is-absolute');
  5. var removeTrailingSep = require('remove-trailing-separator');
  6. function replaceHomedir(filepath, replacement) {
  7. if (typeof filepath !== 'string') {
  8. throw new Error('Path for replace-homedir must be a string.');
  9. }
  10. if (!isAbsolute(filepath)) {
  11. return filepath;
  12. }
  13. var home = removeTrailingSep(homedir());
  14. var lookupHome = home + path.sep;
  15. var lookupPath = removeTrailingSep(filepath) + path.sep;
  16. if (lookupPath.indexOf(lookupHome) !== 0) {
  17. return filepath;
  18. }
  19. return filepath.replace(home, replacement);
  20. }
  21. module.exports = replaceHomedir;