star.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. const fetch = require('npm-registry-fetch')
  2. const log = require('npmlog')
  3. const npa = require('npm-package-arg')
  4. const getIdentity = require('./utils/get-identity')
  5. const BaseCommand = require('./base-command.js')
  6. class Star extends BaseCommand {
  7. static get description () {
  8. return 'Mark your favorite packages'
  9. }
  10. /* istanbul ignore next - see test/lib/load-all-commands.js */
  11. static get name () {
  12. return 'star'
  13. }
  14. /* istanbul ignore next - see test/lib/load-all-commands.js */
  15. static get usage () {
  16. return ['[<pkg>...]']
  17. }
  18. /* istanbul ignore next - see test/lib/load-all-commands.js */
  19. static get params () {
  20. return [
  21. 'registry',
  22. 'unicode',
  23. ]
  24. }
  25. exec (args, cb) {
  26. this.star(args).then(() => cb()).catch(cb)
  27. }
  28. async star (args) {
  29. if (!args.length)
  30. throw new Error(this.usage)
  31. // if we're unstarring, then show an empty star image
  32. // otherwise, show the full star image
  33. const unicode = this.npm.config.get('unicode')
  34. const unstar = this.npm.config.get('star.unstar')
  35. const full = unicode ? '\u2605 ' : '(*)'
  36. const empty = unicode ? '\u2606 ' : '( )'
  37. const show = unstar ? empty : full
  38. const pkgs = args.map(npa)
  39. for (const pkg of pkgs) {
  40. const [username, fullData] = await Promise.all([
  41. getIdentity(this.npm, this.npm.flatOptions),
  42. fetch.json(pkg.escapedName, {
  43. ...this.npm.flatOptions,
  44. spec: pkg,
  45. query: { write: true },
  46. preferOnline: true,
  47. }),
  48. ])
  49. if (!username)
  50. throw new Error('You need to be logged in!')
  51. const body = {
  52. _id: fullData._id,
  53. _rev: fullData._rev,
  54. users: fullData.users || {},
  55. }
  56. if (!unstar) {
  57. log.info('star', 'starring', body._id)
  58. body.users[username] = true
  59. log.verbose('star', 'starring', body)
  60. } else {
  61. delete body.users[username]
  62. log.info('unstar', 'unstarring', body._id)
  63. log.verbose('unstar', 'unstarring', body)
  64. }
  65. const data = await fetch.json(pkg.escapedName, {
  66. ...this.npm.flatOptions,
  67. spec: pkg,
  68. method: 'PUT',
  69. body,
  70. })
  71. this.npm.output(show + ' ' + pkg.name)
  72. log.verbose('star', data)
  73. return data
  74. }
  75. }
  76. }
  77. module.exports = Star