Skip to content

Commit

Permalink
Issue spf13#195: Compile mousetrap only on Windows
Browse files Browse the repository at this point in the history
* Create command_win.go and command_notwin.go for windows only code
* Move call to mousetrap hook into separate preExecHook() function
magiconair committed Nov 24, 2015
1 parent b167d9b commit 193b182
Showing 4 changed files with 34 additions and 17 deletions.
8 changes: 0 additions & 8 deletions cobra.go
Original file line number Diff line number Diff line change
@@ -40,14 +40,6 @@ var initializers []func()
// Set this to true to enable it
var EnablePrefixMatching bool = false

// enables an information splash screen on Windows if the CLI is started from explorer.exe.
var EnableWindowsMouseTrap bool = true

var MousetrapHelpText string = `This is a command line tool
You need to open cmd.exe and run it from there.
`

//AddTemplateFunc adds a template function that's available to Usage and Help
//template generation.
func AddTemplateFunc(name string, tmplFunc interface{}) {
12 changes: 3 additions & 9 deletions command.go
Original file line number Diff line number Diff line change
@@ -21,11 +21,8 @@ import (
"io"
"os"
"path/filepath"
"runtime"
"strings"
"time"

"github.com/inconshreveable/mousetrap"
flag "github.com/spf13/pflag"
)

@@ -626,12 +623,9 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
return c.Root().ExecuteC()
}

if EnableWindowsMouseTrap && runtime.GOOS == "windows" {
if mousetrap.StartedByExplorer() {
c.Print(MousetrapHelpText)
time.Sleep(5 * time.Second)
os.Exit(1)
}
// windows hook
if preExecHookFn != nil {
preExecHookFn(c)
}

// initialize help as the last point possible to allow for user
5 changes: 5 additions & 0 deletions command_notwin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// +build !windows

package cobra

var preExecHookFn func(*Command) = nil
26 changes: 26 additions & 0 deletions command_win.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// +build windows

package cobra

import (
"os"
"time"

"github.com/inconshreveable/mousetrap"
)

var preExecHookFn = preExecHook

// enables an information splash screen on Windows if the CLI is started from explorer.exe.
var MousetrapHelpText string = `This is a command line tool
You need to open cmd.exe and run it from there.
`

func preExecHook(c *Command) {
if mousetrap.StartedByExplorer() {
c.Print(MousetrapHelpText)
time.Sleep(5 * time.Second)
os.Exit(1)
}
}

0 comments on commit 193b182

Please sign in to comment.