From 68f3c66d07afcdbb1b57ba7189ca0ec050d452e5 Mon Sep 17 00:00:00 2001
From: spf13 <steve.francia@gmail.com>
Date: Tue, 24 Sep 2013 13:15:30 -0400
Subject: [PATCH] Proper handling of flag error messages. Fixing test that
 wasn't passing.

---
 cobra_test.go | 15 +++++++++------
 command.go    |  9 +++++----
 2 files changed, 14 insertions(+), 10 deletions(-)

diff --git a/cobra_test.go b/cobra_test.go
index c22a32a4..142768d9 100644
--- a/cobra_test.go
+++ b/cobra_test.go
@@ -215,18 +215,21 @@ func TestChildCommandFlags(t *testing.T) {
 	}
 
 	// Testing with flag only existing on child
+	buf2 := new(bytes.Buffer)
 	c = initialize()
+	c.SetOutput(buf2)
 	cmdEcho.AddCommand(cmdTimes)
 	c.AddCommand(cmdPrint, cmdEcho)
 	c.SetArgs(strings.Split("echo -j 99 -i77 one two", " "))
 	err := c.Execute()
-	_ = err
-	//c.DebugFlags()
 
-	// TODO figure out why this isn't passing
-	//if err == nil {
-	//t.Errorf("invalid flag should generate error")
-	//}
+	if err == nil {
+		t.Errorf("invalid flag should generate error")
+	}
+
+	if !strings.Contains(buf2.String(), "intone=123") {
+		t.Errorf("Wrong error message displayed, \n %s", buf.String())
+	}
 
 }
 
diff --git a/command.go b/command.go
index 06dc73a5..457853d1 100644
--- a/command.go
+++ b/command.go
@@ -336,10 +336,11 @@ func (c *Command) ParseFlags(args []string) (err error) {
 	if err != nil {
 		return err
 	}
-	if c.flagErrorBuf != nil {
-		//fmt.Println(c.flagErrorBuf.String())
-		return nil
-		//return fmt.Errorf("%s", c.flagErrorBuf.String())
+	// The upstream library adds spaces to the error
+	// response regardless of success.
+	// Handling it here until fixing upstream
+	if len(strings.TrimSpace(c.flagErrorBuf.String())) > 1 {
+		return fmt.Errorf("%s", c.flagErrorBuf.String())
 	}
 	return nil
 }