nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: yargs/yargs
Pull request #990 (2017-10-19 05:48:15)

fix: help strings for sub-commands were missing parent command
help messages for sub-commands were missing the context of their parent command.


Patch:
diff --git a/lib/usage.js b/lib/usage.js
index 902fb4d..cf79b10 100644
--- a/lib/usage.js
+++ b/lib/usage.js
@@ -197,13 +197,16 @@ module.exports = function usage (yargs, y18n) {
     if (commands.length) {
       ui.div(__('Commands:'))
 
+      const context = yargs.getContext()
+      const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''
+
       commands.forEach((command) => {
-        const commandString = `${base$0} ${command[0].replace(/^\$0 ?/, '')}` // drop $0 from default commands.
+        const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}` // drop $0 from default commands.
         ui.span(
           {
             text: commandString,
             padding: [0, 2, 0, 2],
-            width: maxWidth(commands, theWrap, base$0) + 4
+            width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
           },
           {text: command[1]}
         )


Test patch:
diff --git a/test/command.js b/test/command.js
index 4dfbe9a..86eb2b3 100644
--- a/test/command.js
+++ b/test/command.js
@@ -536,8 +536,8 @@ describe('Command', () => {
         'command dream [command] [opts]',
         'Go to sleep and dream',
         'Commands:',
-        '  command of-memory <memory>               Dream about a specific memory',
-        '  command within-a-dream [command] [opts]  Dream within a dream',
+        '  command dream of-memory <memory>               Dream about a specific memory',
+        '  command dream within-a-dream [command] [opts]  Dream within a dream',
         'Options:',
         '  --help     Show help  [boolean]',
         '  --version  Show version number  [boolean]',
@@ -682,7 +682,7 @@ describe('Command', () => {
         'command cmd <sub>',
         'Try a command',
         'Commands:',
-        '  command sub  Run the subcommand',
+        '  command cmd sub  Run the subcommand',
         'Options:',
         '  --help     Show help  [boolean]',
         '  --version  Show version number  [boolean]',
diff --git a/test/yargs.js b/test/yargs.js
index b17785b..80439c7 100644
--- a/test/yargs.js
+++ b/test/yargs.js
@@ -338,7 +338,7 @@ describe('yargs dsl tests', () => {
       })
     })
 
-    it("skips executing top-level command if builder's help is executed", () => {
+    it("skips executing root-level command if builder's help is executed", () => {
       const r = checkOutput(() => {
         yargs(['blerg', '-h'])
           .command(
@@ -362,7 +362,7 @@ describe('yargs dsl tests', () => {
         'handle blerg things',
         '',
         'Commands:',
-        '  usage snuh  snuh command',
+        '  usage blerg snuh  snuh command',
         '',
         'Options:',
         '  --version  Show version number  [boolean]',
Repository: yargs/yargs
Pull request #1015 (2017-11-28 07:19:07)

Fix for requiresArg with number type


Patch:
diff --git a/lib/validation.js b/lib/validation.js
index 1eee2fb..3f5c49d 100644
--- a/lib/validation.js
+++ b/lib/validation.js
@@ -57,7 +57,7 @@ module.exports = function validation (yargs, usage, y18n) {
   // make sure that any args that require an
   // value (--foo=bar), have a value.
   self.missingArgumentValue = function missingArgumentValue (argv) {
-    const defaultValues = [true, false, '']
+    const defaultValues = [true, false, '', undefined]
     const options = yargs.getOptions()
 
     if (options.requiresArg.length > 0) {


Test patch:
diff --git a/test/validation.js b/test/validation.js
index 213cf7f..cd9fb14 100644
--- a/test/validation.js
+++ b/test/validation.js
@@ -369,6 +369,46 @@ describe('validation tests', () => {
         .argv
     })
 
+    it('fails when a required argument of type number is missing', (done) => {
+      yargs('-w')
+        .option('w', {type: 'number', requiresArg: true})
+        .fail((msg) => {
+          msg.should.equal('Missing argument value: w')
+          return done()
+        })
+        .argv
+    })
+
+    it('fails when a required argument of type string is missing', (done) => {
+      yargs('-w')
+        .option('w', {type: 'string', requiresArg: true})
+        .fail((msg) => {
+          msg.should.equal('Missing argument value: w')
+          return done()
+        })
+        .argv
+    })
+
+    it('fails when a required argument of type boolean is missing', (done) => {
+      yargs('-w')
+        .option('w', {type: 'boolean', requiresArg: true})
+        .fail((msg) => {
+          msg.should.equal('Missing argument value: w')
+          return done()
+        })
+        .argv
+    })
+
+    it('fails when a required argument of type array is missing', (done) => {
+      yargs('-w')
+        .option('w', {type: 'array', requiresArg: true})
+        .fail((msg) => {
+          msg.should.equal('Missing argument value: w')
+          return done()
+        })
+        .argv
+    })
+
     it('fails when required arguments are present, but a command is missing', (done) => {
       yargs('-w 10 -m wombat')
         .demand(1, ['w', 'm'])
Repository: yargs/yargs
Pull request #1282 (2019-01-30 02:07:10)

fix: middleware added multiple times due to reference bug


Patch:
diff --git a/lib/command.js b/lib/command.js
index fdf9e37..e643d16 100644
--- a/lib/command.js
+++ b/lib/command.js
@@ -17,12 +17,11 @@ module.exports = function command (yargs, usage, validation, globalMiddleware) {
   let aliasMap = {}
   let defaultCommand
   globalMiddleware = globalMiddleware || []
-  self.addHandler = function addHandler (cmd, description, builder, handler, middlewares) {
+  self.addHandler = function addHandler (cmd, description, builder, handler, _middlewares) {
     let aliases = []
+    const middlewares = (_middlewares || []).slice(0)
     handler = handler || (() => {})
-    middlewares = middlewares || []
-    globalMiddleware.push(...middlewares)
-    middlewares = globalMiddleware
+
     if (Array.isArray(cmd)) {
       aliases = cmd.slice(1)
       cmd = cmd[0]
@@ -232,7 +231,7 @@ module.exports = function command (yargs, usage, validation, globalMiddleware) {
     if (commandHandler.handler && !yargs._hasOutput()) {
       yargs._setHasOutput()
 
-      const middlewares = commandHandler.middlewares || []
+      const middlewares = globalMiddleware.slice(0).concat(commandHandler.middlewares || [])
 
       innerArgv = applyMiddleware(innerArgv, middlewares)
 


Test patch:
diff --git a/test/middleware.js b/test/middleware.js
index 0dfae92..a19a9fd 100644
--- a/test/middleware.js
+++ b/test/middleware.js
@@ -140,4 +140,25 @@ describe('middleware', () => {
         .parse()
     })
   })
+
+  // see: https://github.com/yargs/yargs/issues/1281
+  it("doesn't modify globalMiddleware array when executing middleware", () => {
+    let count = 0
+    yargs('bar')
+      .middleware((argv) => {
+        count++
+      })
+      .command('foo', 'foo command', () => {}, () => {}, [
+        () => {
+          count++
+        }
+      ])
+      .command('bar', 'bar command', () => {}, () => {}, [
+        () => {
+          count++
+        }
+      ])
+      .parse()
+    count.should.equal(2)
+  })
 })
Repository: yargs/yargs
Pull request #1361 (2019-06-11 01:52:45)

docs: fix emphasis of note to .parserConfiguration
tiny fix to a Markdown syntax snafu


Patch:
diff --git a/docs/api.md b/docs/api.md
index 386845d..0d0589c 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1193,7 +1193,7 @@ for details of this object
 
 For additional configuration options, see [yargs-parser's configuration](https://github.com/yargs/yargs-parser#configuration).
 
-_Note: configuraton should be top level keys on the `obj` passed to `parserConfiguration`, not populated under the _configuration_ key, as in `yargs-parser`.
+_Note: configuraton should be top level keys on the `obj` passed to `parserConfiguration`, not populated under the configuration key, as in `yargs-parser`._
 
 <a name="pkg-conf"></a>
 .pkgConf(key, [cwd])
diff --git a/lib/validation.js b/lib/validation.js
index e9bbb12..5cbe964 100644
--- a/lib/validation.js
+++ b/lib/validation.js
@@ -102,7 +102,7 @@ module.exports = function validation (yargs, usage, y18n) {
       }
     })
 
-    if (commandKeys.length > 0) {
+    if ((currentContext.commands.length > 0) || (commandKeys.length > 0)) {
       argv._.slice(currentContext.commands.length).forEach((key) => {
         if (commandKeys.indexOf(key) === -1) {
           unknown.push(key)


Test patch:
diff --git a/test/validation.js b/test/validation.js
index f704816..bd0bd1d 100644
--- a/test/validation.js
+++ b/test/validation.js
@@ -335,6 +335,18 @@ describe('validation tests', () => {
         .parse()
     })
 
+    it('fails in strict mode with extra positionals', (done) => {
+      yargs(['kangaroo', 'jumping', 'fast'])
+        .command('kangaroo <status>', 'kangaroo handlers')
+        .strict()
+        .fail((msg) => {
+          msg.should.equal('Unknown argument: fast')
+          return done()
+        })
+        .parse()
+      expect.fail('no parsing failure')
+    })
+
     it('does not fail in strict mode when no commands configured', () => {
       const argv = yargs('koala')
         .demand(1)
Repository: yargs/yargs
Pull request #1383 (2019-07-29 05:13:23)

Don't alter the user supplied script name
### Context
We have a central script (`./tvui`) in the root of our repository that is used to manage everything. It is executed directly, not through `yarn` or `npm-scripts`.

### Problem
Using `yargs.scriptName('./tvui')` results in just `tvui` being shown in all of the commands/examples. This seems to happen due to the `path.basename` call in [`lib/usage.js#154`](https://github.com/yargs/yargs/blob/e3981fd3a5f65427b4d8daae7331f956c4d2d70d/lib/usage.js#L154).

### Fix
Track that the script name was set using the `scriptName` function and don't perform a `path.basename` on it.


Patch:
diff --git a/lib/usage.js b/lib/usage.js
index ded4fc4..98d1508 100644
--- a/lib/usage.js
+++ b/lib/usage.js
@@ -151,7 +151,7 @@ module.exports = function usage (yargs, y18n) {
     normalizeAliases()
 
     // handle old demanded API
-    const base$0 = path.basename(yargs.$0)
+    const base$0 = yargs.customScriptName ? yargs.$0 : path.basename(yargs.$0)
     const demandedOptions = yargs.getDemandedOptions()
     const demandedCommands = yargs.getDemandedCommands()
     const groups = yargs.getGroups()
diff --git a/yargs.js b/yargs.js
index e9eae4b..67f9d11 100644
--- a/yargs.js
+++ b/yargs.js
@@ -37,7 +37,8 @@ function Yargs (processArgs, cwd, parentRequire) {
 
   if (!cwd) cwd = process.cwd()
 
-  self.scriptName = function scriptName (scriptName) {
+  self.scriptName = function (scriptName) {
+    self.customScriptName = true
     self.$0 = scriptName
     return self
   }


Test patch:
diff --git a/test/usage.js b/test/usage.js
index 4d21153..20be98b 100644
--- a/test/usage.js
+++ b/test/usage.js
@@ -1250,6 +1250,24 @@ describe('usage tests', () => {
       r.errors.should.have.length(0)
       r.exit.should.equal(true)
     })
+
+    it('should not alter the user supplied scriptName', () => {
+      const r = checkUsage(() => yargs(['--help'])
+        .scriptName('./custom')
+        .command('command')
+        .parse()
+      )
+      r.logs.join('\n').split(/\n+/).should.deep.equal([
+        './custom [command]',
+        'Commands:',
+        '  ./custom command',
+        'Options:',
+        '  --help     Show help                                                 [boolean]',
+        '  --version  Show version number                                       [boolean]'
+      ])
+      r.errors.should.have.length(0)
+      r.exit.should.equal(true)
+    })
   })
 
   it('should succeed when rebase', () => {
Repository: yargs/yargs
Pull request #1424 (2019-09-14 05:56:51)

Fix promise check to accept any spec conform object
I came across this problem when I was creating a CLI tool which uses [NodeGit](https://www.nodegit.org/) internally. NodeGit is using its own fork of es6 promises and so yargs failed to handle my async code because it didn't return an instance of `Promise`. But yargs should accept all promises as long as they are spec conform, regardless if its an native promise, a polyfill, a bluebird promise or any custom implementation.

So, I fixed the code to look for thenable objects instead of making an instanceof check.

micha149: 😞Pipeline failed because of an timeout… Can somebody rebuild it?
mleguen: Travis CI build restarted

Patch:
diff --git a/lib/is-promise.js b/lib/is-promise.js
index 0516def..271d93b 100644
--- a/lib/is-promise.js
+++ b/lib/is-promise.js
@@ -1,3 +1,3 @@
 module.exports = function isPromise (maybePromise) {
-  return maybePromise instanceof Promise
+  return !!maybePromise && !!maybePromise.then && (typeof maybePromise.then === 'function')
 }


Test patch:
diff --git a/test/is-promise.js b/test/is-promise.js
new file mode 100644
index 0000000..40f8662
--- /dev/null
+++ b/test/is-promise.js
@@ -0,0 +1,34 @@
+'use strict'
+/* global describe, it */
+
+const { expect } = require('chai')
+const isPromise = require('../lib/is-promise')
+
+describe('isPromise', () => {
+  it('returns `false` on non promise value', () => {
+    expect(isPromise('hello there.')).to.be.equal(false)
+  })
+
+  it('returns `true` on es6 promise', () => {
+    const esPromise = new Promise(() => {})
+    expect(isPromise(esPromise)).to.be.equal(true)
+  })
+
+  it('returns `true` on some other thenable', () => {
+    const thenable = { then: () => {} }
+    expect(isPromise(thenable)).to.be.equal(true)
+  })
+
+  it('returns `false` if some falsy value is passed', () => {
+    expect(isPromise(null)).to.be.equal(false)
+  })
+
+  it('returns `false` if passed object has no `then` property', () => {
+    expect(isPromise({})).to.be.equal(false)
+  })
+
+  it('returns `false` if `then` is not a function', () => {
+    const obj = { then: 4711 }
+    expect(isPromise(obj)).to.be.equal(false)
+  })
+})
Repository: yargs/yargs
Pull request #1483 (2019-11-19 02:58:57)

fix: temporary fix for libraries that call Object.freeze()
see: https://github.com/babel/babel/pull/10733, #1482 


Patch:
diff --git a/yargs.js b/yargs.js
index f901734..e7b412a 100644
--- a/yargs.js
+++ b/yargs.js
@@ -1190,9 +1190,15 @@ function Yargs (processArgs, cwd, parentRequire) {
   // we temporarily populate '--' rather than _, with arguments
   // after the '--' directive. After the parse, we copy these back.
   self._copyDoubleDash = function (argv) {
-    if (!argv._) return argv
+    if (!argv._ || !argv['--']) return argv
     argv._.push.apply(argv._, argv['--'])
-    delete argv['--']
+
+    // TODO(bcoe): refactor command parsing such that this delete is not
+    // necessary: https://github.com/yargs/yargs/issues/1482
+    try {
+      delete argv['--']
+    } catch (_err) {}
+
     return argv
   }
 


Test patch:
diff --git a/test/yargs.js b/test/yargs.js
index aa3e6fa..2700318 100644
--- a/test/yargs.js
+++ b/test/yargs.js
@@ -2339,4 +2339,20 @@ describe('yargs dsl tests', () => {
         })
     })
   })
+
+  // see: https://github.com/babel/babel/pull/10733
+  it('should not fail if command handler freezes object', () => {
+    const argv = yargs()
+      .command('cmd', 'a command', (yargs) => {
+        yargs.parserConfiguration({ 'populate--': true })
+      }, (argv) => {
+        Object.freeze(argv)
+        argv._.should.eql(['cmd'])
+        argv['--'].should.eql(['foo'])
+      }).parse(['cmd', '--', 'foo'])
+    argv._.should.eql(['cmd', 'foo'])
+    // This should actually not be undefined, once we fix
+    // #1482.
+    argv['--'].should.eql(['foo'])
+  })
 })
Repository: yargs/yargs
Pull request #1485 (2019-11-19 03:29:22)

fix: addresses bug caused by delete being called on frozen object
see: https://github.com/babel/babel/pull/10733


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b1b58a0..343ffc9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,12 @@
 
 All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
 
+### 14.2.2
+
+### Bug Fixes
+
+* temporary fix for libraries that call Object.freeze() ([#1483](https://www.github.com/yargs/yargs/issues/1483)) ([99c2dc8](https://www.github.com/yargs/yargs/commit/99c2dc850e67c606644f8b0c0bca1a59c87dcbcd))
+
 ### [14.2.1](https://github.com/yargs/yargs/compare/v14.2.0...v14.2.1) (2019-10-30)
 
 
diff --git a/package.json b/package.json
index 3b8843c..525e916 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
 {
   "name": "yargs",
-  "version": "14.2.1",
+  "version": "14.2.2",
   "description": "yargs the modern, pirate-themed, successor to optimist.",
   "main": "./index.js",
   "contributors": [
diff --git a/yargs.js b/yargs.js
index 5cb663c..8863988 100644
--- a/yargs.js
+++ b/yargs.js
@@ -1191,9 +1191,15 @@ function Yargs (processArgs, cwd, parentRequire) {
   // we temporarily populate '--' rather than _, with arguments
   // after the '--' directive. After the parse, we copy these back.
   self._copyDoubleDash = function (argv) {
-    if (!argv._) return argv
+    if (!argv._ || !argv['--']) return argv
     argv._.push.apply(argv._, argv['--'])
-    delete argv['--']
+
+    // TODO(bcoe): refactor command parsing such that this delete is not
+    // necessary: https://github.com/yargs/yargs/issues/1482
+    try {
+      delete argv['--']
+    } catch (_err) {}
+
     return argv
   }
 


Test patch:
diff --git a/test/yargs.js b/test/yargs.js
index 5ceb6f8..7c93d94 100644
--- a/test/yargs.js
+++ b/test/yargs.js
@@ -2327,4 +2327,20 @@ describe('yargs dsl tests', () => {
         })
     })
   })
+
+  // see: https://github.com/babel/babel/pull/10733
+  it('should not fail if command handler freezes object', () => {
+    const argv = yargs()
+      .command('cmd', 'a command', (yargs) => {
+        yargs.parserConfiguration({ 'populate--': true })
+      }, (argv) => {
+        Object.freeze(argv)
+        argv._.should.eql(['cmd'])
+        argv['--'].should.eql(['foo'])
+      }).parse(['cmd', '--', 'foo'])
+    argv._.should.eql(['cmd', 'foo'])
+    // This should actually not be undefined, once we fix
+    // #1482.
+    argv['--'].should.eql(['foo'])
+  })
 })
Repository: yargs/yargs
Pull request #1493 (2019-11-27 14:49:23)

fix: show 2 dashes on help for single digit option key or alias
To be coherent with what yargs/parser considers as an option single dash key, do not display '-1' but '--1' when '1' is used as an option key or an alias.

See #1454 

bcoe: fixes: #1454

Patch:
diff --git a/lib/usage.js b/lib/usage.js
index 92bf378..0dd1501 100644
--- a/lib/usage.js
+++ b/lib/usage.js
@@ -272,7 +272,7 @@ module.exports = function usage (yargs, y18n) {
             // for the special positional group don't
             // add '--' or '-' prefix.
             if (groupName === self.getPositionalGroupName()) return sw
-            else return (sw.length > 1 ? '--' : '-') + sw
+            else return (/^[^0-9]$/.test(sw) ? '-' : '--') + sw
           })
           .join(', ')
 


Test patch:
diff --git a/test/usage.js b/test/usage.js
index ea25240..1875cf1 100644
--- a/test/usage.js
+++ b/test/usage.js
@@ -1121,6 +1121,51 @@ describe('usage tests', () => {
       ])
     })
 
+    it('should use 2 dashes for 1-digit key usage', () => {
+      const r = checkUsage(() => yargs(['--help'])
+        .option('1', {
+          type: 'boolean',
+          description: 'Negative one'
+        })
+        .wrap(null)
+        .parse()
+      )
+      r.should.have.property('result')
+      r.result.should.have.property('_').with.length(0)
+      r.should.have.property('exit').and.equal(true)
+      r.should.have.property('errors').with.length(0)
+      r.should.have.property('logs')
+      r.logs.join('\n').split(/\n+/).should.deep.equal([
+        'Options:',
+        '  --1        Negative one  [boolean]',
+        '  --help     Show help  [boolean]',
+        '  --version  Show version number  [boolean]'
+      ])
+    })
+
+    it('should use 2 dashes for 1-digit alias usage', () => {
+      const r = checkUsage(() => yargs(['--help'])
+        .option('negativeone', {
+          alias: '1',
+          type: 'boolean',
+          description: 'Negative one'
+        })
+        .wrap(null)
+        .parse()
+      )
+      r.should.have.property('result')
+      r.result.should.have.property('_').with.length(0)
+      r.should.have.property('exit').and.equal(true)
+      r.should.have.property('errors').with.length(0)
+      r.should.have.property('logs')
+      r.logs.join('\n').split(/\n+/).should.deep.equal([
+        'Options:',
+        '  --help              Show help  [boolean]',
+        '  --version           Show version number  [boolean]',
+        '  --negativeone, --1  Negative one  [boolean]'
+      ])
+    })
+
     describe('when exitProcess is false', () => {
       it('should not validate arguments (required argument)', () => {
         const r = checkUsage(() => yargs(['--help'])
Repository: yargs/yargs
Pull request #1495 (2019-11-27 17:09:23)

fix getCompletion() no longer working for options
getCompletion() throws when completing an option, as it needs `parsed.aliases`, which is lost (unfreezed) when calling `.parse()` with arguments.

See #1434 

This is a side effect of fixing `.parse()` to be able to call it several times, a few months ago.

This PR provides `parsed` to completion before unfreezing it.


Patch:
diff --git a/lib/completion.js b/lib/completion.js
index 3f3bf16..8c2363e 100644
--- a/lib/completion.js
+++ b/lib/completion.js
@@ -8,6 +8,11 @@ module.exports = function completion (yargs, usage, command) {
     completionKey: 'get-yargs-completions'
   }
 
+  let aliases
+  self.setParsed = function setParsed (parsed) {
+    aliases = parsed.aliases
+  }
+
   const zshShell = (process.env.SHELL && process.env.SHELL.indexOf('zsh') !== -1) ||
     (process.env.ZSH_NAME && process.env.ZSH_NAME.indexOf('zsh') !== -1)
   // get a list of completion commands.
@@ -16,7 +21,6 @@ module.exports = function completion (yargs, usage, command) {
     const completions = []
     const current = args.length ? args[args.length - 1] : ''
     const argv = yargs.parse(args, true)
-    const aliases = yargs.parsed.aliases
     const parentCommands = yargs.getContext().commands
 
     // a custom completion function can be provided
diff --git a/yargs.js b/yargs.js
index e7b412a..9ccb304 100644
--- a/yargs.js
+++ b/yargs.js
@@ -581,6 +581,7 @@ function Yargs (processArgs, cwd, parentRequire) {
     if (parseFn) exitProcess = false
 
     const parsed = self._parseArgs(args, shortCircuit)
+    completion.setParsed(self.parsed)
     if (parseFn) parseFn(exitError, parsed, output)
     unfreeze()
 


Test patch:
diff --git a/test/completion.js b/test/completion.js
index 4324fc5..a2036af 100644
--- a/test/completion.js
+++ b/test/completion.js
@@ -358,10 +358,25 @@ describe('Completion', () => {
               })
             })
         })
-
         r.logs.should.include('apple')
         r.logs.should.include('foo')
       })
+      it('returns default completion to callback for options', () => {
+        process.env.SHELL = '/bin/bash'
+        const r = checkUsage(() => {
+          yargs()
+            .option('apple')
+            .option('foo')
+            .completion()
+            .getCompletion(['$0', '-'], (completions) => {
+              ;(completions || []).forEach((completion) => {
+                console.log(completion)
+              })
+            })
+        })
+        r.logs.should.include('--apple')
+        r.logs.should.include('--foo')
+      })
     })
   })