@rocketmakers/shell
v0.2.0
Published
The suite of `@rocketmakers/shell-*` packages provides support for running common commands in a shell, using TypeScript.
Downloads
1,057
Keywords
Readme
The suite of @rocketmakers/shell-* packages provides support for running common commands in a shell, using TypeScript.
Overview
@rocketmakers/shell
All scripts will need to use @rocketmakers/shell package, which provides the core features:
- Parsing command line arguments
- Prerequisite checking for required commands in the environment
- Logging utilities
- An abstraction for running a command in a shell, with options for how the output is handled
- The executor can be used from the
@rocketmakers/shell-executorpackage, or a custom implementation could be implemented if needed
- The executor can be used from the
@rocketmakers/shell-executor
This contains a default implementation of the IShellExecutor interface.
@rocketmakers/shell-* packages
The majority of @rocketmakers/shell-* packages contain commands relating to a shell executable. For example, @rocketmakers/shell-sops contains commands for working with sops.
Quick start
This shows a typical script using @rocketmakers/shell:
- Create an
IShellExecutor - Parse arguments
- Set a default log level
- Perform a prerequisites check
- Execute commands
import { LoggerLevel } from '@rocketmakers/log';
import * as Args from '@rocketmakers/shell/args';
import { createLogger, setDefaultLoggerLevel } from '@rocketmakers/shell/logger';
import * as Prerequisites from '@rocketmakers/shell/prerequisites';
import { ShellExecutor } from '@rocketmakers/shell-executor';
// Any loggers created via createLogger will respect the level set by seDefaultLoggerLevel
const logger = createLogger('hello-world');
// We need an instance of IShellExecutor to run commands
const shell = new ShellExecutor();
async function run() {
const args = await Args.match({
// Example of matching an optional log level argument, defaulting to an environment variable
log: Args.single({
description: 'The log level',
shortName: 'l',
defaultValue: process.env.LOG_LEVEL || 'info',
validValues: ['trace', 'debug', 'info', 'warn', 'error', 'fatal'],
}),
});
if (args?.log) {
setDefaultLoggerLevel(args.log as LoggerLevel);
}
// Args.match prints the docs for each arg if args couldn't be parsed so this is a useful pattern for supporting --help
if (!args) {
if (process.argv.includes('--help')) {
return;
}
throw new Error('There was a problem parsing the arguments');
}
// This will throw if the environment does not contain the expected commands
await Prerequisites.check(shell);
await shell.exec(['echo', '"Hello World!"']);
}
run()
.then(() => logger.info('🚀 Done 🚀'))
.catch(err => {
logger.fatal(err);
process.exit(-1);
});