x/tools/cmd/godoc: Fix incorrectly indented literals in examples
godoc formats function examples for text or HTML output by
stripping the surrounding braces and un-indenting by replacing
"\n " with "\n". This modifies the content of string literals,
resulting in misleading examples.
This change introduces a function, replaceLeadingIndentation, which
unindents more carefully. It removes the first level of indentation
only outside of string literals. For plain text output, it adds custom
indentation at the beginning of every line including string literals.
Fixes golang/go#18446
Change-Id: I52a7f5756bdb69c8a66f031452dd35eab947ec1f
Reviewed-on: https://go-review.googlesource.com/36544
Run-TryBot: Jay Conrod <jayconrod@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Alan Donovan <adonovan@google.com>
diff --git a/godoc/godoc_test.go b/godoc/godoc_test.go
index b347305..0c32f39 100644
--- a/godoc/godoc_test.go
+++ b/godoc/godoc_test.go
@@ -8,6 +8,7 @@
"go/ast"
"go/parser"
"go/token"
+ "strings"
"testing"
)
@@ -190,3 +191,29 @@
}
}
}
+
+func TestReplaceLeadingIndentation(t *testing.T) {
+ oldIndent := strings.Repeat(" ", 2)
+ newIndent := strings.Repeat(" ", 4)
+ tests := []struct {
+ src, want string
+ }{
+ {" foo\n bar\n baz", " foo\n bar\n baz"},
+ {" '`'\n '`'\n", " '`'\n '`'\n"},
+ {" '\\''\n '`'\n", " '\\''\n '`'\n"},
+ {" \"`\"\n \"`\"\n", " \"`\"\n \"`\"\n"},
+ {" `foo\n bar`", " `foo\n bar`"},
+ {" `foo\\`\n bar", " `foo\\`\n bar"},
+ {" '\\`'`foo\n bar", " '\\`'`foo\n bar"},
+ {
+ " if true {\n foo := `One\n \tTwo\nThree`\n }\n",
+ " if true {\n foo := `One\n \tTwo\n Three`\n }\n",
+ },
+ }
+ for _, tc := range tests {
+ if got := replaceLeadingIndentation(tc.src, oldIndent, newIndent); got != tc.want {
+ t.Errorf("replaceLeadingIndentation:\n%v\n---\nhave:\n%v\n---\nwant:\n%v\n",
+ tc.src, got, tc.want)
+ }
+ }
+}