0.1.25 • Published 8 months ago

@fnet/args v0.1.25

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
8 months ago

@fnet/args

Introduction

@fnet/args is a command-line interface (CLI) utility designed to assist in parsing and validating command-line arguments. It leverages the capabilities of JSON Schema for validation, providing a robust method to ensure the correctness of user inputs. This tool is ideal for developers who need a straightforward way to manage command-line arguments and ensure they adhere to expected schemas.

How It Works

@fnet/args operates by receiving an array of command-line arguments, a JSON Schema for validation, and optional configurations like initial arguments or a package callback. The utility parses these arguments using the minimist library and then validates them against the provided schema, ensuring they are correctly formatted and contain the required data types and structures.

Key Features

  • Argument Parsing: Uses the minimist library to parse command-line arguments, handling various input formats including flags and key-value pairs.
  • JSON Schema Validation: Validates the parsed arguments against a JSON Schema, leveraging the AJV library for dynamic schema compilation and validation.
  • Dot Notation Support: Allows the use of dot notation for nested parameter specification, making it easier to define complex configuration structures.
  • Schema Display in YAML: Converts and displays the JSON Schema in a readable YAML format with highlighted keys and values for easy understanding of expected arguments.
  • Extensibility: Offers options to provide initial arguments and callbacks for package information, supporting flexible integration into various CLI tools.

Conclusion

In essence, @fnet/args provides a reliable and efficient solution for parsing and validating command-line inputs, ensuring they meet expected schema requirements. It automates error checking in CLI applications, reducing potential bugs or unexpected behavior from user inputs.

Developer Guide for @fnet/args

Overview

The @fnet/args library is designed to parse and validate command-line arguments in JavaScript applications using JSON Schema. It simplifies handling command-line inputs and ensures that they meet the specified requirements through seamless integration with schemas. Key features include parsing arguments, validating them against defined schemas, merging initial settings, and automatic conversion of schemas to a readable format.

Installation

To install @fnet/args, use either npm or yarn:

npm install @fnet/args

or

yarn add @fnet/args

Usage

Parsing and Validating Command-Line Arguments

To use @fnet/args, provide a JSON Schema for validation, and the library will parse the command-line arguments provided to your application. You can also merge initial arguments or provide custom validation functions.

import parseArgs from '@fnet/args';

// Define a JSON Schema for validation
const schema = {
  type: 'object',
  properties: {
    port: { type: 'number' },
    host: { type: 'string' }
  },
  required: ['port']
};

// Parse and validate command-line arguments
const args = parseArgs({
  schema,
  exitOnError: true // Exit the process if validation fails
});

// Use args.host and args.port safely, as they are validated
console.log(`Server running at http://${args.host}:${args.port}`);

Displaying Help or Version Information

You can also add functionality to display help or version information:

const args = parseArgs({
  schema,
  packageCallback: async () => {
    return {
      name: 'YourAppName',
      version: '1.0.0'
    };
  }
});

// Now, `--help` or `--version` commands will display respective information

Examples

Basic Example

// Assuming CLI input: node script.js --port 8080 --host localhost

const schema = {
  type: 'object',
  properties: {
    port: { type: 'number' },
    host: { type: 'string' }
  }
};

const parsed = parseArgs({ schema });
console.log(parsed.port); // 8080
console.log(parsed.host); // 'localhost'

Initial Arguments

const defaultArgs = { host: '127.0.0.1' };
const schema = {
  type: 'object',
  properties: {
    port: { type: 'number' },
    host: { type: 'string' }
  }
};

const args = parseArgs({
  schema,
  initial: defaultArgs
});

console.log(args.host); // If `--host` is not provided, defaults to '127.0.0.1'

Using a Custom Validation Function

import Ajv from 'ajv';

const ajv = new Ajv();
const customValidate = ajv.compile(schema);

const args = parseArgs({
  schema,
  validate: customValidate
});

Acknowledgement

This library relies on minimist for argument parsing and ajv for JSON Schema validation (dynamically imported if needed). These dependencies ensure robust parsing and validation capabilities out of the box.

Input Schema

$schema: https://json-schema.org/draft/2020-12/schema
type: object
properties:
  schema:
    type: object
    description: A valid JSON Schema for validating the arguments.
  argv:
    type: array
    items:
      type: string
    description: An array of command-line arguments to be parsed and validated.
      Defaults to process.argv.
  validate:
    type: object
    description: A precompiled validation function. If not provided, AJV will be
      dynamically imported to compile the schema.
  initial:
    type: object
    description: Initial arguments to merge with parsed arguments.
  exitOnError:
    type: boolean
    description: Whether to exit the process on validation failure. Defaults to true.
  packageCallback:
    type: object
    description: A callback function to retrieve the package information.
required:
  - schema