|
| 1 | +/** |
| 2 | + * External dependencies |
| 3 | + */ |
| 4 | +const fs = require( 'fs' ); |
| 5 | +const path = require( 'path' ); |
| 6 | + |
| 7 | +/** |
| 8 | + * Internal dependencies |
| 9 | + */ |
| 10 | +const { log } = require( '../lib/logger' ); |
| 11 | + |
| 12 | +exports.options = [ |
| 13 | + { |
| 14 | + argname: '-s, --slug <slug>', |
| 15 | + description: 'Standalone plugin slug to get version from plugins.json', |
| 16 | + }, |
| 17 | +]; |
| 18 | + |
| 19 | +/** |
| 20 | + * Command to get the plugin version based on the slug. |
| 21 | + * |
| 22 | + * @param {Object} opt Command options. |
| 23 | + */ |
| 24 | +exports.handler = async ( opt ) => { |
| 25 | + doRunGetPluginVersion( { |
| 26 | + pluginsJsonFile: 'plugins.json', // Path to plugins.json file. |
| 27 | + slug: opt.slug, // Plugin slug. |
| 28 | + } ); |
| 29 | +}; |
| 30 | + |
| 31 | +/** |
| 32 | + * Returns the match plugin version from plugins.json file. |
| 33 | + * |
| 34 | + * @param {Object} settings Plugin settings. |
| 35 | + */ |
| 36 | +function doRunGetPluginVersion( settings ) { |
| 37 | + if ( settings.slug === undefined ) { |
| 38 | + throw Error( 'A slug must be provided via the --slug (-s) argument.' ); |
| 39 | + } |
| 40 | + |
| 41 | + const pluginsFile = path.join( '.', settings.pluginsJsonFile ); |
| 42 | + |
| 43 | + // Buffer contents of plugins JSON file. |
| 44 | + let pluginsFileContent = ''; |
| 45 | + |
| 46 | + try { |
| 47 | + pluginsFileContent = fs.readFileSync( pluginsFile, 'utf-8' ); |
| 48 | + } catch ( e ) { |
| 49 | + throw Error( `Error reading file at "${ pluginsFile }": ${ e }` ); |
| 50 | + } |
| 51 | + |
| 52 | + // Validate that the plugins JSON file contains content before proceeding. |
| 53 | + if ( ! pluginsFileContent ) { |
| 54 | + throw Error( `Contents of file at "${ pluginsFile }" could not be read, or are empty.` ); |
| 55 | + } |
| 56 | + |
| 57 | + const plugins = JSON.parse( pluginsFileContent ); |
| 58 | + |
| 59 | + // Check for valid and not empty object resulting from plugins JSON file parse. |
| 60 | + if ( |
| 61 | + 'object' !== typeof plugins || |
| 62 | + 0 === Object.keys( plugins ).length |
| 63 | + ) { |
| 64 | + throw Error( `File at "${ pluginsFile }" parsed, but detected empty/non valid JSON object.` ); |
| 65 | + } |
| 66 | + |
| 67 | + for ( const moduleDir in plugins ) { |
| 68 | + const pluginVersion = plugins[ moduleDir ]?.version; |
| 69 | + const pluginSlug = plugins[ moduleDir ]?.slug; |
| 70 | + if ( pluginVersion && pluginSlug && ( settings.slug === pluginSlug ) ) { |
| 71 | + return log( pluginVersion ); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + throw Error( `The "${ settings.slug }" module slug is missing in the file "${ pluginsFile }".` ); |
| 76 | +} |
0 commit comments