github.com/ipld/go-ipld-prime@v0.21.0/testutil/indent.go (about) 1 package testutil 2 3 import "bytes" 4 5 // Dedent strips leading tabs from every line of a string, taking a hint of 6 // how many tabs should be stripped from the number of consecutive tabs found 7 // on the first non-empty line. Dedent also strips one leading blank 8 // line if it contains nothing but the linebreak. 9 // 10 // If later lines have fewer leading tab characters than the depth we intuited 11 // from the first line, then stripping will still only remove tab characters. 12 // 13 // Roughly, Dedent is "Do What I Mean" to normalize a heredoc string 14 // that contains leading indentation to make it congruent with the 15 // surrounding source code. 16 func Dedent(s string) string { 17 // Originally from: https://github.com/warpfork/go-wish/blob/master/indent.go 18 // Forked here to reduce dependencies in go-ipld-prime. 19 return string(DedentBytes([]byte(s))) 20 } 21 22 // DedentBytes is identically to Dedent, but works on a byte slice. 23 func DedentBytes(bs []byte) []byte { 24 lines := bytes.SplitAfter(bs, []byte{'\n'}) 25 buf := bytes.Buffer{} 26 if len(lines[0]) == 1 && lines[0][0] == '\n' { 27 lines = lines[1:] 28 } 29 if len(lines) == 0 { 30 return []byte{} 31 } 32 depth := 0 33 for _, r := range lines[0] { 34 depth++ 35 if r != '\t' { 36 depth-- 37 break 38 } 39 } 40 for _, line := range lines { 41 for i, r := range line { 42 if i < depth && r == '\t' { 43 continue 44 } 45 buf.Write(line[i:]) 46 break 47 } 48 } 49 return buf.Bytes() 50 }