• Stars
    star
    123
  • Rank 280,079 (Top 6 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created about 15 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A mixin for creating command line applications - gives an easy DSL for argument specification and processing

Mixlib::CLI

Build Status Gem Version

Umbrella Project: Chef Foundation

Project State: Active

Issues Response Time Maximum: 14 days

Pull Request Response Time Maximum: 14 days

Mixlib::CLI provides a class-based command line option parsing object, like the one used in Chef, Ohai and Relish. To use in your project:

require "mixlib/cli"

class MyCLI
  include Mixlib::CLI

  option :config_file,
    short: "-c CONFIG",
    long: "--config CONFIG",
    default: "config.rb",
    description: "The configuration file to use"

  option :log_level,
    short: "-l LEVEL",
    long: "--log_level LEVEL",
    description: "Set the log level (debug, info, warn, error, fatal)",
    required: true,
    in: [:debug, :info, :warn, :error, :fatal],
    proc: Proc.new { |l| l.to_sym }

  option :help,
    short: "-h",
    long: "--help",
    description: "Show this message",
    on: :tail,
    boolean: true,
    show_options: true,
    exit: 0

end

# ARGV = [ '-c', 'foo.rb', '-l', 'debug' ]
cli = MyCLI.new
cli.parse_options
cli.config[:config_file] # 'foo.rb'
cli.config[:log_level]   # :debug

If you are using this in conjunction with Mixlib::Config, you can do something like this (building on the above definition):

class MyConfig
  extend(Mixlib::Config)

  log_level   :info
  config_file "default.rb"
end

class MyCLI
  def run(argv = ARGV)
    parse_options(argv)
    MyConfig.merge!(config)
  end
end

c = MyCLI.new
# ARGV = [ '-l', 'debug' ]
c.run
MyConfig[:log_level] # :debug

For supported arguments to option, see the function documentation in lib/mixlib/cli.rb.

If you need access to the leftover options that aren't captured in the config, you can get at them through +cli_arguments+ (referring to the above definition of MyCLI).

# ARGV = [ '-c', 'foo.rb', '-l', 'debug', 'file1', 'file2', 'file3' ]
cli = MyCLI.new
cli.parse_options
cli.cli_arguments # [ 'file1', 'file2', 'file3' ]

Deprecating CLI Options

mixlib-cli 2.1.0 and later supports declaring options as deprecated. Using a deprecated option will result in a warning message being displayed. If a deprecated flag is supplied, its value is assigned to the replacement flag. You can control this assignment by specifying a value_mapper function in the arguments (see example below, and function docs)

Usage notes (see docs for arguments to Mixlib::CLI::ClassMethods#deprecated_option for more):

  • Define deprecated items last, after all non-deprecated items have been defined. You will see errors if your deprecated item references a replacement that hasn't been defined yet.
  • deprecated_option only takes a subset of 'option' configuration. You can only specify short, long - these should map to the short/long values of the option from before its deprecation.
    • item description will automatically be generated along the lines of "-f/--flag is deprecated. Use -n/--new-flag instead."
    • if the replacement argument is not given, item description will look like "-f/--flag is deprecated and will be removed in a future release"

Example

Given the following example:

# my_cli.rb

class MyCLI
  include Mixlib::CLI


  option :arg_not_required,
    description: "This takes no argument.",
    long: "--arg-not-required",
    short: "-n"

  option :arg_required,
    description: "This takes an argument.",
    long: "--arg-required ARG",
    short: "-a",
    in: ["a", "b", "c"]

  deprecated_option :dep_one,
    short: "-1",
    long: "--dep-one",
    # this deprecated option maps to the '--arg-not-required' option:
    replacement: :arg_not_required,
    # Do not keep 'dep_one' in `config` after parsing.
    keep: false

  deprecated_option :dep_two,
    short: "-2",
    long: "--dep-two ARG",
    replacement: :arg_required,
    # will map the  given value to a valid value for `--arg-required`.
    value_mapper: Proc.new { |arg|
      case arg
      when "q"; "invalid" # We'll use this to show validation still works
      when "z"; "a"
      when "x"; "b"
      else
        "c"
      end
    }

end

c = MyCLI.new()
c.parse_options

puts "arg_required: #{c.config[:arg_required]}" if c.config.key? :arg_required
puts "arg_not_required: #{c.config[:arg_not_required]}" if c.config.key? :arg_not_required
puts "dep_one: #{c.config[:dep_one]}" if c.config.key? :dep_one
puts "dep_two: #{c.config[:dep_two]}" if c.config.key? :dep_two

In this example, --dep-one will be used. Note that dep_one will not have a value of its own in options because keep: false was given to the deprecated option.

$ ruby my_cli.rb --dep-one

-1/--dep-one: This flag is deprecated. Use -n/--arg-not-required instead
arg_not_required: true

In this example, the value provided to dep-two will be converted to a value that --arg-required will accept,a nd populate :arg\_required with

$ ruby my_cli.rb --dep-two z # 'q' maps to 'invalid' in the value_mapper proc above

-2/--dep-two: This flag is deprecated. Use -a/--arg-required instead.

arg_required: a # The value is mapped to its replacement using the function provided.
dep_two: z  # the deprecated value is kept by default

In this example, the value provided to dep-two will be converted to a value that --arg-required will reject, showing how content rules are applied even when the input is coming from a deprecated option:

$ ruby my_cli.rb --dep-two q

-2/--dep-two: This flag is deprecated. Use -a/--arg-required instead.
-a/--arg-required: invalid is not one of the allowed values: 'a', 'b', or 'c'

Documentation

Class and module documentation is maintained using YARD. You can generate it by running:

rake docs

You can serve them locally with live refresh using:

bundle exec yard server --reload

Contributing

For information on contributing to this project please see our Contributing Documentation

License & Copyright

  • Copyright:: Copyright (c) 2008-2018 Chef Software, Inc.
  • License:: Apache License, Version 2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

chef

Chef Infra, a powerful automation platform that transforms infrastructure into code automating how infrastructure is configured, deployed and managed across any environment, at any scale
Ruby
7,442
star
2

bento

Packer templates for building minimal Vagrant baseboxes for multiple platforms
HCL
4,160
star
3

omnibus

Easily create full-stack installers for your project across a variety of platforms.
Ruby
1,269
star
4

ohai

Ohai profiles your system and emits JSON
Ruby
672
star
5

chef-zero

Simple, easy-run, fast-start in-memory Chef server for testing and solo purposes
Ruby
535
star
6

chef-vault

Securely manage passwords, certs, and other secrets in Chef
Ruby
407
star
7

knife-ec2

Chef knife plug-in for AWS EC2
Ruby
403
star
8

chef-server

Chef Infra Server is a hub for configuration data; storing cookbooks, node policies and metadata of managed nodes.
Erlang
279
star
9

automate

Chef Automate provides a full suite of enterprise capabilities for maintaining continuous visibility into application, infrastructure, and security automation.
Go
220
star
10

supermarket

Chef's community platform
Ruby
210
star
11

knife-vsphere

Chef knife plug-in for VMware vSphere
Ruby
201
star
12

knife-windows

Plugin for Chef's knife tool for working with Windows nodes
Ruby
151
star
13

mixlib-shellout

mixin library for subprocess management, output collection
Ruby
132
star
14

omnibus-software

Open Source Software for use in Omnibus built packages
Ruby
132
star
15

chef-workstation

Chef Workstation gives you everything you need to get started with Chef, so you can automate how you audit, configure, and manage applications end environments.
Go
128
star
16

chef-web-docs

All The Documentation
HTML
127
star
17

knife-openstack

Chef Infra knife plug-in for OpenStack
Ruby
120
star
18

cookstyle

A linting tool that helps you to write better Chef Infra cookbooks and InSpec profiles by detecting and automatically correcting style, syntax, and logic mistakes in your code.
Ruby
107
star
19

chef-oss-practices

Documentation and Practices for Open Source Development at Chef
Ruby
81
star
20

knife-azure

Chef knife plug-in for Microsoft Azure
Ruby
72
star
21

artifactory-client

A simple, lightweight Ruby client for interacting with the Artifactory API.
Ruby
68
star
22

knife-google

Chef knife plug-in for Google Compute
Ruby
67
star
23

win32-service

A Ruby library that allows users to inspect, control or create services on MS Windows
Ruby
65
star
24

mixer

Mix in functions from other modules
Erlang
64
star
25

os_release

A repo containing the /etc/os-release file from various Linux distros
59
star
26

concrete

Concrete enhances your rebar based Erlang project by providing a common Makefile wrapper, a dialyzer make target that caches PLT analysis of your project's dependencies, and a mechanism to specify development only dependencies.
Erlang
55
star
27

mixlib-config

A simple class based Config mechanism, similar to the one found in Chef
Ruby
51
star
28

sqerl

General purpose RDBMS abstraction layer
Erlang
42
star
29

vscode-chef

Chef Infra Extension for Visual Studio Code
TypeScript
40
star
30

cheffish

Resources and tools for testing and interacting with Chef and Chef Server.
Ruby
39
star
31

knife-tidy

Report on stale Chef Server nodes/cookbooks, clean those up and additionally clean data integrity issues from a knife-ec-backup object based backup!
Ruby
36
star
32

homebrew-chef

A homebrew tap for ChefDK, Workstation, and InSpec
Ruby
36
star
33

mixlib-log

A simple class based Log mechanism, similar to Merb and Chef, that you can mix in to your project.
Ruby
34
star
34

effortless

Automated best practices for Chef Infra and Chef InSpec
Shell
33
star
35

knife-ec-backup

Backup and restore Chef Infra Server in a repository-compatible format
Ruby
31
star
36

chef-load

chef-load - a tool for simulating load on a Chef Infra Server and/or a Chef Automate server
Roff
31
star
37

mini_s3

Minimal AWS S3 client for Erlang
Erlang
28
star
38

okta_aws

Tool for accessing the AWS API for an account you normally access via okta
Python
27
star
39

omnitruck

Web service to automate the release of Omnibus artifacts
Ruby
26
star
40

dep-selector

Fast Dependency Solver for Ruby using Gecode
Ruby
25
star
41

win32-process

A Ruby library that adds or redefines several methods for the Process module
Ruby
25
star
42

kitchen-vcenter

A test-kitchen driver for vCenter REST API
Ruby
25
star
43

omnibus-ctl

Provides service control for omnibus packages
Ruby
23
star
44

mixlib-authentication

AuthN signing and verification. Appears in both the client and server
Ruby
22
star
45

knife-cloud

Library for Chef knife cloud plugins
Ruby
18
star
46

mixlib-versioning

General purpose Ruby library that allows you to parse, compare, and manipulate version strings in multiple formats.
Ruby
17
star
47

win32-taskscheduler

A Ruby interface for the task scheduler on MS Windows
Ruby
17
star
48

win32-eventlog

The win32-eventlog library provides a Ruby interface for reading from and writing to the Windows Event Log
Ruby
17
star
49

chefstyle

Version Pinned RuboCop with Chef approved Cop list for linting software - NOT FOR COOKBOOKS
Ruby
15
star
50

chef-cli

The 'chef' command line tool included in Chef Workstation
Ruby
14
star
51

win32-file

Extra methods, and redefined methods, for the File class on MS Windows
Ruby
14
star
52

appbundler

Generate locked binstubs for ruby applications
Ruby
14
star
53

stats_hero

General purpose stats collection
Erlang
13
star
54

knife-vrealize

Plugin for Chef's knife tool to interact with VMware vRealize products
Ruby
13
star
55

anka-buildkite-plugin

Run Buildkite steps inside Veertu Anka Virtual Machines
Shell
13
star
56

chef-apply

The ad-hoc execution tool for the Chef ecosystem.
Ruby
13
star
57

wmi-lite

Lightweight, low-dependency wrapper for basic WMI functionality on Windows.
Ruby
13
star
58

mixlib-install

A library for interacting with Chef Software Inc's software distribution systems.
Ruby
12
star
59

ffi-libarchive

A Ruby FFI binding to libarchive.
Ruby
12
star
60

chef_authn

Erlang API request authentication signing and verification for Chef
Erlang
11
star
61

fixie

Low level manipulation tool for chef in sql
Ruby
10
star
62

ffi-yajl

Ruby FFI gem wrapper around yajl2 library
Ruby
10
star
63

dep-selector-libgecode

Bundled Gecode Libraries for dep-selector
Ruby
10
star
64

win32-certstore

Ruby library for accessing the certificate store on Windows
Ruby
10
star
65

corefoundation

FFI based Ruby bindings for the CoreFoundation frameworks
Ruby
10
star
66

chef-workstation-app

The Chef Workstation desktop application.
TypeScript
10
star
67

knife-vcenter

Chef knife plug-in for VMware REST API
Ruby
9
star
68

win32-security

A Ruby interface for security aspects of MS Windows
Ruby
9
star
69

win32-dir

A series of constants, and extra or redefined methods, for the Dir class on Windows
Ruby
8
star
70

chef_backup

A library to backup an Chef server
Ruby
8
star
71

chef-vault-testfixtures

provides an RSpec shared context for testing Chef cookbooks that use chef-vault
Ruby
7
star
72

opscoderl_httpc

Opscode helper application for being an HTTP client
Erlang
7
star
73

license-acceptance

Chef Software libraries for accepting usage license
Ruby
7
star
74

rubydistros

Dockerfiles for Ruby on various Linux distros
Dockerfile
7
star
75

win32-mmap

A Ruby interface for memory mapped files on MS Windows
Ruby
7
star
76

win32-event

A Ruby interface to Event objects on MS Windows
Ruby
6
star
77

chef-analyze

A CLI to analyze artifacts from a Chef Infra Server
Go
6
star
78

license_scout

Discovers license information of the dependencies of a project.
Ruby
6
star
79

.github

.github files that are inherited by all org repos unless specifically included in a repo
6
star
80

cookbook-omnifetch

Fetch Chef Cookbooks from Various Sources to a Local Cache
Ruby
6
star
81

github-workflows

Github Actions Workflows
5
star
82

win32-ipc

A Ruby abstract base class for synchronization objects on MS Windows
Ruby
5
star
83

appbundle-updater

A little help when you want to update an appbundled project inside of a Chef/ChefDK omnibus package
Ruby
5
star
84

ci-studio-common

Shared helpers for use inside CIs (like Travis) and a Habitat Studio
Go
5
star
85

omnibus-toolchain

Omnibus packaging for Omnibus toolchain
Ruby
5
star
86

chef-web-core

Shared resources for Chef web properties
Ruby
5
star
87

gatherlogs-reporter

Inspec profiles for examining gatherlog output from chef-products for support.
Ruby
5
star
88

architecture-center

Ruby
5
star
89

chocolatey-packages

PowerShell
4
star
90

compliance-workshop-environment

Ruby
4
star
91

inspec-extra-resources

Ruby
4
star
92

folsom_graphite

Send data from folsom automatically to graphite
Erlang
4
star
93

cookstylist

Cookstyle GitHub app
Ruby
4
star
94

chef-powershell-shim

.NET 4.0/COM wrapper around PowerShell host
Ruby
4
star
95

automate-liveness-agent

Agent that sends "keep alive" messages to Chef Automate
Ruby
4
star
96

community_cookbook_releaser

A simple script to aid in version bumps and changelog generation for Chef managed community cookbooks
Ruby
4
star
97

habitat_exporter

Go
4
star
98

mixlib-archive

A very simple gem to create and extract archives.
Ruby
4
star
99

win32-mutex

A Ruby interface for mutexes on MS Windows
Ruby
3
star
100

chef_dictionary

A dictionary file of words in the Chef ecosystem
Ruby
3
star