options-conflicts.js
This file
Path
examples/options-conflicts.js
71 lines · 2.6 KiB · JavaScript
Last changed by
Add extended conflicts example (#1700)John Geebefore adoption1d27078
History of this fileTake it
Add extended conflicts example (#1700)John Geebefore adoption1d27078
lines 1–71why, one step back1#!/usr/bin/env node2// const { Command, Option } = require('commander'); // (normal include)3const { Command, Option } = require('../'); // include commander in git clone of commander repo4const program = new Command();56// You can use .conflicts() with a single string, which is the camel-case name of the conflicting option.7program8 .command('pay')9 .addOption(new Option('--cash').conflicts('creditCard'))10 .addOption(new Option('--credit-card'))11 .action((options) => {12 if (options.cash) {13 console.log('Paying by cash')14 } else if (options.creditCard) {15 console.log('Paying by credit card')16 } else {17 console.log('Payment method unknown')18 }19 });2021 // The default value for an option does not cause a conflict.22 // A value specified using an environment variable is checked for conflicts.23program24 .command('source')25 .addOption(new Option('-p, --port <number>', 'port number for server')26 .default(80)27 .env('PORT')28 ).addOption(new Option('--interactive', 'prompt for user input instead of listening to a port')29 .conflicts('port')30 ).action((options) => {31 if (options.interactive) {32 console.log('What do you want to do today?')33 } else {34 console.log(`Running server on port: ${options.port}`);35 }36 });3738// You can use .conflicts() with an array of option names.39// A negated option is not separate from the positive option for conflicts (they have same option name).40program41 .command('paint')42 .addOption(new Option('--summer', 'use a mixture of summer colors').conflicts(['autumn', 'colour']))43 .addOption(new Option('--autumn', 'use a mixture of autumn colors').conflicts(['summer', 'colour']))44 .addOption(new Option('--colour <shade>', 'use a single solid colour'))45 .addOption(new Option('--no-colour', 'leave surface natural'))46 .action((options) => {47 let colour = 'not specified';48 if (options.colour === false) {49 colour = 'natural';50 } else if (options.colour) {51 colour = options.colour;52 } else if (options.summer) {53 colour = 'summer';54 } else if (options.autumn) {55 colour = 'autumn';56 }57 console.log(`Painting colour is ${colour}`);58 });5960program.parse();6162// Try the following:63// node options-conflicts.js pay --cash --credit-card64//65// node options-conflicts.js source66// node options-conflicts.js source --interactive67// node options-conflicts.js source --port 8080 --interactive68// PORT=8080 node options-conflicts.js source --interactive69//70// node options-conflicts.js paint --colour=red --summer71// node options-conflicts.js paint --no-colour --autumn