From 193b182195dad17ec904d4851f33e3ee3696bf07 Mon Sep 17 00:00:00 2001 From: Frank Schroeder Date: Tue, 24 Nov 2015 00:19:32 +0100 Subject: [PATCH] Issue #195: Compile mousetrap only on Windows * Create command_win.go and command_notwin.go for windows only code * Move call to mousetrap hook into separate preExecHook() function --- cobra.go | 8 -------- command.go | 12 +++--------- command_notwin.go | 5 +++++ command_win.go | 26 ++++++++++++++++++++++++++ 4 files changed, 34 insertions(+), 17 deletions(-) create mode 100644 command_notwin.go create mode 100644 command_win.go diff --git a/cobra.go b/cobra.go index 20957cdd..7c8da2b4 100644 --- a/cobra.go +++ b/cobra.go @@ -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{}) { diff --git a/command.go b/command.go index f5fa34e2..560f71e3 100644 --- a/command.go +++ b/command.go @@ -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 diff --git a/command_notwin.go b/command_notwin.go new file mode 100644 index 00000000..073dd353 --- /dev/null +++ b/command_notwin.go @@ -0,0 +1,5 @@ +// +build !windows + +package cobra + +var preExecHookFn func(*Command) = nil diff --git a/command_win.go b/command_win.go new file mode 100644 index 00000000..4b0eaa1b --- /dev/null +++ b/command_win.go @@ -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) + } +}