2023-01-09 07:53:01 -05:00
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
2024-10-16 11:53:18 -04:00
import { fileURLToPath } from "node:url" ;
2023-01-09 07:53:01 -05:00
2024-04-30 16:36:13 -04:00
export const getEnv = ( /** @type {string} */ key ) => process . env [ key ] ;
export const setEnv = ( /** @type {string} */ key , value ) => {
2023-01-09 07:53:01 -05:00
process . env [ key ] = value ;
} ;
2024-10-02 11:09:03 -04:00
/**
* Check if the running file was run directly.
* @param {string | URL} fileUrl
*/
export const isMain = ( fileUrl ) => process . argv [ 1 ] === fileURLToPath ( fileUrl ) ;
2024-10-03 09:54:34 -04:00
/**
* @typedef {import("node:util").ParseArgsConfig} ParseArgsConfig
* @typedef {ReturnType<import("node:util").parseArgs>} ParsedResults
*
* @param {import("node:util").ParseArgsConfig} config
* @param {ParsedResults} results
* @returns {{ errors: string[] | null }}
*/
export const validateArgs = ( config , results ) => {
if ( ! config . options ) {
return { } ;
}
/** @type {string[] | null} */
let errors = null ;
for ( const option in config . options ) {
const optionRequired = config . options [ option ] ? . required ;
const optionPresent = Object . hasOwn ( results . values , option ) ;
if ( optionRequired && ! optionPresent ) {
errors = errors ? ? [ ] ;
2024-10-07 12:34:12 -04:00
errors . push ( ` Missing required argument "-- ${ option } ". ` ) ;
2024-10-03 09:54:34 -04:00
}
}
2024-10-07 12:34:12 -04:00
return { errors } ;
2024-10-03 09:54:34 -04:00
} ;
2024-10-24 09:49:17 -04:00
/**
* Take a list of options and program info and print a man page.
* @param {Record<string, {} extends { required?: boolean, description?: string }>} options
* @param {{ name: string, synopsis: string, description: string }} programInfo
*/
export const printManPage = ( options , programInfo ) => {
const { name , synopsis , description } = programInfo ;
console . log ( "NAME" ) ;
console . log ( ` ${ name } ` ) ;
console . log ( ) ;
console . log ( "SYNOPSIS" ) ;
console . log ( ` ${ synopsis } ` ) ;
console . log ( ) ;
console . log ( "DESCRIPTION" ) ;
console . log ( ` ${ description } ` ) ;
console . log ( ) ;
console . log ( "OPTIONS" ) ;
const optionPadding =
Math . max ( ... Object . keys ( options ) . map ( ( key ) => key . length ) ) + 4 ;
for ( const [ key , value ] of Object . entries ( options ) ) {
const paddedKey = ` -- ${ key } ` . padEnd ( optionPadding ) ;
console . log (
` ${ paddedKey } ${ value . type } ${ ( value . description ? ? "" ) && ` - ${ value . description } ` } ` ,
) ;
}
} ;