From a839ceaf308edfa7765742a32ef176a589e8c507 Mon Sep 17 00:00:00 2001 From: mappu Date: Thu, 16 Apr 2020 18:38:21 +1200 Subject: [PATCH] node: add heuristic for breaking array/map literals onto multiple lines --- node.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/node.go b/node.go index e651955..9b84ada 100644 --- a/node.go +++ b/node.go @@ -2024,6 +2024,8 @@ func (this *conversionState) convertArrayLiteralCommon(items []node.Node) (strin // TODO support unpack operator (...) + nChars := 0 + isMapType := false for idx, itm_ := range items { itm, ok := itm_.(*expr.ArrayItem) @@ -2057,16 +2059,26 @@ func (this *conversionState) convertArrayLiteralCommon(items []node.Node) (strin return "", parseErr{itm, err} } entries = append(entries, kv+`: `+vv+`,`) + + nChars += len(kv) + len(vv) + 4 // assume an extra trailing space } else { entries = append(entries, vv+`,`) + nChars += len(vv) + 2 } } + // Heuristic decision whether to break array literal onto multiple lines + // We have to do this because gofmt does not care about long lines otherwise + maybeNewline := " " + if nChars > 60 { + maybeNewline = "\n" + } + if isMapType { - return `map[` + keyType.AsGoString() + `]` + valType.AsGoString() + `{` + strings.Join(entries, " ") + `}`, nil + return `map[` + keyType.AsGoString() + `]` + valType.AsGoString() + `{` + maybeNewline + strings.Join(entries, maybeNewline) + maybeNewline + `}`, nil } else { - return `[]` + valType.AsGoString() + `{` + strings.Join(entries, " ") + `}`, nil + return `[]` + valType.AsGoString() + `{` + maybeNewline + strings.Join(entries, maybeNewline) + maybeNewline + `}`, nil } }