Repository: mochajs/mocha

Problem statement:
node flag parsing strategy is backwards
https://github.com/nodejs/node/pull/34637 introduces a `-u` flag for `node`, which conflicts with Mocha's `-u`/`--ui` flag.  I had expected Mocha would prefer its _own_ options over `node`'s where there was a conflict, but this is not the case--instead, Mocha explicitly whitelists `-r`/`--require`, which was previously the only known command-line flag shared between `mocha` and `node`.

To fix this, Mocha needs to change its strategy to detect its own options _first_, _then_ attempt to detect if something is a `node` option.  Currently, Mocha checks for `node` options first.
node flag parsing strategy is backwards
https://github.com/nodejs/node/pull/34637 introduces a `-u` flag for `node`, which conflicts with Mocha's `-u`/`--ui` flag.  I had expected Mocha would prefer its _own_ options over `node`'s where there was a conflict, but this is not the case--instead, Mocha explicitly whitelists `-r`/`--require`, which was previously the only known command-line flag shared between `mocha` and `node`.

To fix this, Mocha needs to change its strategy to detect its own options _first_, _then_ attempt to detect if something is a `node` option.  Currently, Mocha checks for `node` options first.


Hints:
cc @bethgriggs
This _does_ mean that if someone wants to use custom conditions w/ `mocha`, they need to use `--conditions`, not `-u`.
cc @bethgriggs
This _does_ mean that if someone wants to use custom conditions w/ `mocha`, they need to use `--conditions`, not `-u`.

Patch:
diff --git a/lib/cli/node-flags.js b/lib/cli/node-flags.js
--- a/lib/cli/node-flags.js
+++ b/lib/cli/node-flags.js
@@ -7,6 +7,7 @@
  */
 
 const nodeFlags = process.allowedNodeEnvironmentFlags;
+const {isMochaFlag} = require('./run-option-metadata');
 const unparse = require('yargs-unparser');
 
 /**
@@ -43,16 +44,14 @@ exports.isNodeFlag = (flag, bareword = true) => {
     flag = flag.replace(/^--?/, '');
   }
   return (
-    // treat --require/-r as Mocha flag even though it's also a node flag
-    !(flag === 'require' || flag === 'r') &&
     // check actual node flags from `process.allowedNodeEnvironmentFlags`,
     // then historical support for various V8 and non-`NODE_OPTIONS` flags
     // and also any V8 flags with `--v8-` prefix
-    ((nodeFlags && nodeFlags.has(flag)) ||
-      debugFlags.has(flag) ||
-      /(?:preserve-symlinks(?:-main)?|harmony(?:[_-]|$)|(?:trace[_-].+$)|gc(?:[_-]global)?$|es[_-]staging$|use[_-]strict$|v8[_-](?!options).+?$)/.test(
-        flag
-      ))
+    (!isMochaFlag(flag) && nodeFlags && nodeFlags.has(flag)) ||
+    debugFlags.has(flag) ||
+    /(?:preserve-symlinks(?:-main)?|harmony(?:[_-]|$)|(?:trace[_-].+$)|gc(?:[_-]global)?$|es[_-]staging$|use[_-]strict$|v8[_-](?!options).+?$)/.test(
+      flag
+    )
   );
 };
 
diff --git a/lib/cli/run-option-metadata.js b/lib/cli/run-option-metadata.js
--- a/lib/cli/run-option-metadata.js
+++ b/lib/cli/run-option-metadata.js
@@ -12,7 +12,7 @@
  * @type {{string:string[]}}
  * @private
  */
-exports.types = {
+const TYPES = (exports.types = {
   array: [
     'extension',
     'file',
@@ -58,7 +58,7 @@ exports.types = {
     'slow',
     'timeout'
   ]
-};
+});
 
 /**
  * Option aliases keyed by canonical option name.
@@ -88,3 +88,26 @@ exports.aliases = {
   ui: ['u'],
   watch: ['w']
 };
+
+const ALL_MOCHA_FLAGS = Object.keys(TYPES).reduce((acc, key) => {
+  // gets all flags from each of the fields in `types`, adds those,
+  // then adds aliases of each flag (if any)
+  TYPES[key].forEach(flag => {
+    acc.add(flag);
+    const aliases = exports.aliases[flag] || [];
+    aliases.forEach(alias => {
+      acc.add(alias);
+    });
+  });
+  return acc;
+}, new Set());
+
+/**
+ * Returns `true` if the provided `flag` is known to Mocha.
+ * @param {string} flag - Flag to check
+ * @returns {boolean} If `true`, this is a Mocha flag
+ * @private
+ */
+exports.isMochaFlag = flag => {
+  return ALL_MOCHA_FLAGS.has(flag.replace(/^--?/, ''));
+};


Test patch:
diff --git a/test/node-unit/cli/node-flags.spec.js b/test/node-unit/cli/node-flags.spec.js
--- a/test/node-unit/cli/node-flags.spec.js
+++ b/test/node-unit/cli/node-flags.spec.js
@@ -1,22 +1,34 @@
 'use strict';
 
-const nodeEnvFlags = process.allowedNodeEnvironmentFlags;
+const nodeEnvFlags = [...process.allowedNodeEnvironmentFlags];
 const {
   isNodeFlag,
   impliesNoTimeouts,
   unparseNodeFlags
 } = require('../../../lib/cli/node-flags');
 
+const {isMochaFlag} = require('../../../lib/cli/run-option-metadata');
+
 describe('node-flags', function() {
   describe('isNodeFlag()', function() {
     describe('for all allowed node environment flags', function() {
-      // NOTE: this is not stubbing nodeEnvFlags in any way, so relies on
-      // the userland polyfill to be correct.
-      nodeEnvFlags.forEach(envFlag => {
-        it(`${envFlag} should return true`, function() {
-          expect(isNodeFlag(envFlag), 'to be true');
+      nodeEnvFlags
+        .filter(flag => !isMochaFlag(flag))
+        .forEach(envFlag => {
+          it(`${envFlag} should return true`, function() {
+            expect(isNodeFlag(envFlag), 'to be true');
+          });
+        });
+    });
+
+    describe('for all allowed node env flags which conflict with mocha flags', function() {
+      nodeEnvFlags
+        .filter(flag => isMochaFlag(flag))
+        .forEach(envFlag => {
+          it(`${envFlag} should return false`, function() {
+            expect(isNodeFlag(envFlag), 'to be false');
+          });
         });
-      });
     });
 
     describe('when expecting leading dashes', function() {
@@ -24,11 +36,6 @@ describe('node-flags', function() {
         expect(isNodeFlag('throw-deprecation', false), 'to be false');
         expect(isNodeFlag('--throw-deprecation', false), 'to be true');
       });
-
-      it('should return false for --require/-r', function() {
-        expect(isNodeFlag('--require', false), 'to be false');
-        expect(isNodeFlag('-r', false), 'to be false');
-      });
     });
 
     describe('special cases', function() {
@@ -132,14 +139,5 @@ describe('node-flags', function() {
         ['--v8-numeric-one=1', '--v8-boolean-one', '--v8-numeric-two=2']
       );
     });
-
-    it('should special-case "--require"', function() {
-      // note the only way for this to happen IN REAL LIFE is if you use "--require esm";
-      // mocha eats all --require args otherwise.
-      expect(unparseNodeFlags({require: 'mcrib'}), 'to equal', [
-        '--require',
-        'mcrib'
-      ]);
-    });
   });
 });