ordered-options.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // This is an example of using tokens to add a custom behaviour.
  2. //
  3. // This adds a option order check so that --some-unstable-option
  4. // may only be used after --enable-experimental-options
  5. //
  6. // Note: this is not a common behaviour, the order of different options
  7. // does not usually matter.
  8. import { parseArgs } from '../index.js';
  9. function findTokenIndex(tokens, target) {
  10. return tokens.findIndex((token) => token.kind === 'option' &&
  11. token.name === target
  12. );
  13. }
  14. const experimentalName = 'enable-experimental-options';
  15. const unstableName = 'some-unstable-option';
  16. const options = {
  17. [experimentalName]: { type: 'boolean' },
  18. [unstableName]: { type: 'boolean' },
  19. };
  20. const { values, tokens } = parseArgs({ options, tokens: true });
  21. const experimentalIndex = findTokenIndex(tokens, experimentalName);
  22. const unstableIndex = findTokenIndex(tokens, unstableName);
  23. if (unstableIndex !== -1 &&
  24. ((experimentalIndex === -1) || (unstableIndex < experimentalIndex))) {
  25. throw new Error(`'--${experimentalName}' must be specified before '--${unstableName}'`);
  26. }
  27. console.log(values);
  28. /* eslint-disable max-len */
  29. // Try the following:
  30. // node ordered-options.mjs
  31. // node ordered-options.mjs --some-unstable-option
  32. // node ordered-options.mjs --some-unstable-option --enable-experimental-options
  33. // node ordered-options.mjs --enable-experimental-options --some-unstable-option