Repository: yargs/yargs (js)

Issue:
Call the wrong command handler in some situation
I'm not sure if this is a bug...

I just add two commands:

```javascript
// cli.js
#!/usr/bin/env node
var yargs = require('yargs');
yargs.command('foo', 'the foo command', {}, function(argv) {
  console.log('command foo--', argv);
});
yargs.command('bar', 'the bar command', {}, function(argv){
  console.log('command bar--', argv);
});
console.log(yargs.parse(process.argv.slice(2)));
```

```bash
$ ./cli.js foo
```

It call command foo's handler, and print: `command foo-- { _: [ 'foo' ], '$0': 'cli.js' }`.

```bash
$ ./cli.js bar foo
```

***It also call command foo's handler! But I think it should call command bar's handler.***

And I dig into the source code, <https://github.com/yargs/yargs/blob/master/yargs.js#L645>:

```javascript
if (~argv._.indexOf(cmd) && cmd !== completionCommand) {
  setPlaceholderKeys(argv)
  return command.runCommand(cmd, self, parsed)
}
```

Why `argv._.indexOf(cmd)` not is `argv._[0] === cmd`?

Pull request description:
fix: we now respect the order of _ when applying commands
We were applying commands in the order that handlers were defined, rather than the order of `_`, fixes #514 

Patch:
diff --git a/yargs.js b/yargs.js
index 5b4807f..4aa4b3b 100644
--- a/yargs.js
+++ b/yargs.js
@@ -647,8 +647,8 @@ function Yargs (processArgs, cwd, parentRequire) {
     // if there's a handler associated with a
     // command defer processing to it.
     var handlerKeys = command.getCommands()
-    for (var i = 0, cmd; (cmd = handlerKeys[i]) !== undefined; i++) {
-      if (~argv._.indexOf(cmd) && cmd !== completionCommand) {
+    for (var i = 0, cmd; (cmd = argv._[i]) !== undefined; i++) {
+      if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
         setPlaceholderKeys(argv)
         return command.runCommand(cmd, self, parsed)
       }


Test patch:
diff --git a/test/command.js b/test/command.js
index 965942a..890fb8f 100644
--- a/test/command.js
+++ b/test/command.js
@@ -455,4 +455,20 @@ describe('Command', function () {
       ])
     })
   })
+
+  // addresses https://github.com/yargs/yargs/issues/514.
+  it('respects order of positional arguments when matching commands', function () {
+    var output = []
+    yargs('bar foo')
+      .command('foo', 'foo command', function (yargs) {
+        output.push('foo')
+      })
+      .command('bar', 'bar command', function (yargs) {
+        output.push('bar')
+      })
+      .argv
+
+    output.should.include('bar')
+    output.should.not.include('foo')
+  })
 })