oclif: The Open CLI Framework
  • Getting Started
  • API Reference
  • Blog
  • GitHub

›How to

Getting Started

  • Introduction
  • Features
  • FAQs
  • Generator Commands

API Reference

  • Commands
  • Command Arguments
  • Command Flags
  • Configuration
  • Topics
  • Topic Separators
  • Hooks
  • Plugins
  • Help Classes
  • Error Handling
  • JSON

How to

  • Release
  • Testing
  • Running Commands Programmatically
  • Aliases
  • Custom Base Class
  • Prompting
  • Spinner
  • Table
  • Notifications
  • Debugging
  • Flexible Taxonomy
  • Global Flags

Also See

  • Examples
  • External Links
  • Related Repositories
  • How We Work
  • Feedback
Edit

Custom Base Class

Use inheritance to share functionality between common commands. Here is an example of a command base class that has some common shared flags and a log method that can be shared among many commands.

For large CLIs with multiple plugins, it's useful to put this base class into its own npm package to be shared.

// src/base.ts
import {Command, Flags} from '@oclif/core'

export default abstract class extends Command {
  static flags = {
    loglevel: Flags.string({options: ['error', 'warn', 'info', 'debug']})
  }

  log(msg, level) {
    switch (this.flags.loglevel) {
    case 'error':
      if (level === 'error') console.error(msg)
      break
    // a complete example would need to have all the levels
    }
  }

  async init() {
    // do some initialization
    const {flags} = this.parse(this.constructor)
    this.flags = flags
  }
  async catch(err) {
    // add any custom logic to handle errors from the command
    // or simply return the parent class error handling
    return super.catch(err);
  }
  async finally(err) {
    // called after run and catch regardless of whether or not the command errored
    return super.finally(_);
  }
}

// src/commands/mycommand.ts
import Command from '../base'

export class MyCommand extends Command {
  static flags = {
    ...Command.flags,
    extraflag: Flags.string()
  }

  async run() {
    this.log('information', 'info')
    this.log('uh oh!', 'error')
  }
}
Last updated on 1/20/2022
← AliasesPrompting →
Made with 💜 by Salesforce — MIT License