From fde815f6a176987f8361abb08f8dc8b60b6e5385 Mon Sep 17 00:00:00 2001 From: Roger Peppe Date: Thu, 12 Apr 2018 12:43:24 +0100 Subject: [PATCH] godoc.org-compatible ast package Change the dump code so that it hides the values of variable definitions if they're large. This means that godoc.org should be able to deal with the output, and the godoc output is readable without needing to read through a huge struct literal definition. Other approaches might be to always generate an extra variable (seems unnecessary) or to pass to writer explicitly to the dump methods rather than swapping s.w out temporarily. The former seems unnecessarily intrusive to the usual output; the latter seemed unnecessarily intrusive to the source itself. YMMV. --- ast/stdast.go | 3 ++- dump/dump.go | 14 ++++++++++++++ dump/dump_test.go | 23 +++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/ast/stdast.go b/ast/stdast.go index b0b23d6..8ad08e0 100644 --- a/ast/stdast.go +++ b/ast/stdast.go @@ -4677,7 +4677,8 @@ var p1 = &Source{ } // StdAst is the AST for the standard library. -var StdAst = &DesugaredObject{ +var StdAst = _StdAst +var _StdAst = &DesugaredObject{ NodeBase: NodeBase{ loc: LocationRange{ FileName: "", diff --git a/dump/dump.go b/dump/dump.go index 8b24fe3..a9249ec 100644 --- a/dump/dump.go +++ b/dump/dump.go @@ -184,7 +184,21 @@ func (s *dumpState) dump(value interface{}) { if v.Kind() == reflect.Ptr && v.IsNil() { printNil(s.w) } else { + // Replace the writer with a temporary buffer so that + // we can see how big the output is. If it's too big, + // we use an intermediate value so that godoc output + // isn't swamped by the literal. + oldWriter := s.w + buf := new(bytes.Buffer) + s.w = buf s.dumpVal(v) + s.w = oldWriter + if buf.Len() > 100 { + s.w.Write([]byte("_" + s.config.VariableName)) + s.newline() + s.w.Write([]byte("var _" + s.config.VariableName + " = ")) + } + s.w.Write(buf.Bytes()) } s.newline() } diff --git a/dump/dump_test.go b/dump/dump_test.go index 6c516a8..99b9881 100644 --- a/dump/dump_test.go +++ b/dump/dump_test.go @@ -454,3 +454,26 @@ var Obj = &struct { Foo *Zeo; Bar *Zeo }{ } } } + +func TestSdumpLargeDefinition(t *testing.T) { + type largeStruct struct { + ABCDEFGHIJKLMNOBQRSTUVWXYZ0 int + ABCDEFGHIJKLMNOBQRSTUVWXYZ1 int + ABCDEFGHIJKLMNOBQRSTUVWXYZ2 int + ABCDEFGHIJKLMNOBQRSTUVWXYZ3 int + ABCDEFGHIJKLMNOBQRSTUVWXYZ4 int + } + got := Sdump(&largeStruct{1, 2, 3, 4, 5}) + want := `var Obj = _Obj +var _Obj = &largeStruct{ + ABCDEFGHIJKLMNOBQRSTUVWXYZ0: int(1), + ABCDEFGHIJKLMNOBQRSTUVWXYZ1: int(2), + ABCDEFGHIJKLMNOBQRSTUVWXYZ2: int(3), + ABCDEFGHIJKLMNOBQRSTUVWXYZ3: int(4), + ABCDEFGHIJKLMNOBQRSTUVWXYZ4: int(5), +} +` + if got != want { + t.Errorf("got : \n%#v\n, want : \n%#v", got, want) + } +}