module-name.js 973 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict'
  2. var path = require('path')
  3. module.exports = moduleName
  4. module.exports.test = {}
  5. module.exports.test.pathToPackageName = pathToPackageName
  6. function pathToPackageName (dir) {
  7. if (dir == null) return ''
  8. if (dir === '') return ''
  9. var name = path.relative(path.resolve(dir, '..'), dir)
  10. var scoped = path.relative(path.resolve(dir, '../..'), dir)
  11. if (scoped[0] === '@') return scoped.replace(/\\/g, '/')
  12. return name.trim()
  13. }
  14. module.exports.test.isNotEmpty = isNotEmpty
  15. function isNotEmpty (str) {
  16. return str != null && str !== ''
  17. }
  18. var unknown = 0
  19. function moduleName (tree) {
  20. if (tree.name) { return tree.name }
  21. var pkg = tree.package || tree
  22. if (isNotEmpty(pkg.name) && typeof pkg.name === 'string') return pkg.name.trim()
  23. var pkgName = pathToPackageName(tree.path)
  24. if (pkgName !== '') return pkgName
  25. if (tree._invalidName != null) return tree._invalidName
  26. tree._invalidName = '!invalid#' + (++unknown)
  27. return tree._invalidName
  28. }