src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/testutil/dedent.go (about)

     1  package testutil
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // Dedent removes an optional leading newline, and removes the indentation
     9  // present in the first line from all subsequent non-empty lines.
    10  //
    11  // Dedent panics if any non-empty line does not start with the same indentation
    12  // as the first line.
    13  func Dedent(text string) string {
    14  	lines := strings.Split(strings.TrimPrefix(text, "\n"), "\n")
    15  	line0 := lines[0]
    16  	indent := line0[:len(line0)-len(strings.TrimLeft(lines[0], " \t"))]
    17  	for i, line := range lines {
    18  		if !strings.HasPrefix(line, indent) && line != "" {
    19  			panic(fmt.Sprintf("line %d is not empty but doesn't start with %q", i, indent))
    20  		}
    21  		lines[i] = strings.TrimPrefix(line, indent)
    22  	}
    23  	return strings.Join(lines, "\n")
    24  }