diff --git a/command/help.go b/command/help.go index 04121785f..78bb16f7c 100644 --- a/command/help.go +++ b/command/help.go @@ -3,6 +3,7 @@ package command import ( "bytes" "fmt" + "regexp" "strings" "github.com/cli/cli/utils" @@ -27,9 +28,7 @@ func rootUsageFunc(command *cobra.Command) error { flagUsages := command.LocalFlags().FlagUsages() if flagUsages != "" { command.Println("\n\nFlags:") - for _, l := range strings.Split(strings.Trim(dedent(flagUsages), "\n\r"), "\n") { - command.Println(" " + l) - } + command.Print(indent(dedent(flagUsages), " ")) } return nil } @@ -144,10 +143,7 @@ Read the manual at https://cli.github.com/manual`}) if e.Title != "" { // If there is a title, add indentation to each line in the body fmt.Fprintln(out, utils.Bold(e.Title)) - - for _, l := range strings.Split(strings.Trim(e.Body, "\n\r"), "\n") { - fmt.Fprintln(out, " "+l) - } + fmt.Fprint(out, indent(e.Body, " ")) } else { // If there is no title print the body as is fmt.Fprintln(out, e.Body) @@ -162,6 +158,15 @@ func rpad(s string, padding int) string { return fmt.Sprintf(template, s) } +var lineRE = regexp.MustCompile(`(?m)^`) + +func indent(s, indent string) string { + if len(strings.TrimSpace(s)) == 0 { + return s + } + return lineRE.ReplaceAllLiteralString(s, indent) +} + func dedent(s string) string { lines := strings.Split(s, "\n") minIndent := -1 diff --git a/command/help_test.go b/command/help_test.go index 64c412ab2..e07542928 100644 --- a/command/help_test.go +++ b/command/help_test.go @@ -44,3 +44,47 @@ func TestDedent(t *testing.T) { } } } + +func Test_indent(t *testing.T) { + type args struct { + s string + indent string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "empty", + args: args{ + s: "", + indent: "--", + }, + want: "", + }, + { + name: "blank", + args: args{ + s: "\n", + indent: "--", + }, + want: "\n", + }, + { + name: "indent", + args: args{ + s: "one\ntwo\nthree", + indent: "--", + }, + want: "--one\n--two\n--three", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := indent(tt.args.s, tt.args.indent); got != tt.want { + t.Errorf("indent() = %q, want %q", got, tt.want) + } + }) + } +}