Skip to content

Commit

Permalink
fetch latest version if the info command is run without one
Browse files Browse the repository at this point in the history
  • Loading branch information
charliegerard committed Nov 9, 2023
1 parent edf65a6 commit 66c287d
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 11 deletions.
32 changes: 21 additions & 11 deletions lib/commands/info/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import chalk from 'chalk'
import meow from 'meow'
import fetch from 'node-fetch'
import ora from 'ora'

import { outputFlags, validationFlags } from '../../flags/index.js'
Expand All @@ -19,7 +20,7 @@ export const info = {
async run (argv, importMeta, { parentName }) {
const name = parentName + ' info'

const input = setupCommand(name, info.description, argv, importMeta)
const input = await setupCommand(name, info.description, argv, importMeta)
const packageData = input && await fetchPackageData(input.pkgName, input.pkgVersion, input)

if (packageData) {
Expand All @@ -45,9 +46,9 @@ export const info = {
* @param {string} description
* @param {readonly string[]} argv
* @param {ImportMeta} importMeta
* @returns {void|CommandContext}
* @returns {Promise<void|CommandContext>}
*/
function setupCommand (name, description, argv, importMeta) {
async function setupCommand (name, description, argv, importMeta) {
const flags = {
...outputFlags,
...validationFlags,
Expand Down Expand Up @@ -90,15 +91,24 @@ function setupCommand (name, description, argv, importMeta) {

const versionSeparator = rawPkgName.lastIndexOf('@')

let pkgVersion, pkgName
if (versionSeparator < 1) {
throw new InputError('Need to specify a full package identifier, like eg: [email protected]')
}

const pkgName = rawPkgName.slice(0, versionSeparator)
const pkgVersion = rawPkgName.slice(versionSeparator + 1)

if (!pkgVersion) {
throw new InputError('Need to specify a version, like eg: [email protected]')
// Get the latest version
try {
pkgName = rawPkgName
const response = await fetch(`https://registry.npmjs.org/${rawPkgName}/latest`)
/** @type any */
const packageDetails = await response.json() || null

if (packageDetails?.version) {
pkgVersion = packageDetails.version
}
} catch (e) {
throw new Error('Issue fetching package version')
}
} else {
pkgName = rawPkgName.slice(0, versionSeparator)
pkgVersion = rawPkgName.slice(versionSeparator + 1)
}

return {
Expand Down
67 changes: 67 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"is-interactive": "^2.0.0",
"is-unicode-supported": "^1.3.0",
"meow": "^12.0.1",
"node-fetch": "^3.3.2",
"ora": "^6.1.2",
"pony-cause": "^2.1.8",
"prompts": "^2.4.2",
Expand Down

0 comments on commit 66c287d

Please sign in to comment.