github.com/v2fly/tools@v0.100.0/internal/lsp/cmd/test/format.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package cmdtest 6 7 import ( 8 "bytes" 9 "io/ioutil" 10 "os" 11 "regexp" 12 "strings" 13 "testing" 14 15 exec "golang.org/x/sys/execabs" 16 17 "github.com/v2fly/tools/internal/span" 18 "github.com/v2fly/tools/internal/testenv" 19 ) 20 21 func (r *runner) Format(t *testing.T, spn span.Span) { 22 tag := "gofmt" 23 uri := spn.URI() 24 filename := uri.Filename() 25 expect := string(r.data.Golden(tag, filename, func() ([]byte, error) { 26 cmd := exec.Command("gofmt", filename) 27 contents, _ := cmd.Output() // ignore error, sometimes we have intentionally ungofmt-able files 28 contents = []byte(r.Normalize(fixFileHeader(string(contents)))) 29 return contents, nil 30 })) 31 if expect == "" { 32 //TODO: our error handling differs, for now just skip unformattable files 33 t.Skip("Unformattable file") 34 } 35 got, _ := r.NormalizeGoplsCmd(t, "format", filename) 36 if expect != got { 37 t.Errorf("format failed for %s expected:\n%s\ngot:\n%s", filename, expect, got) 38 } 39 // now check we can build a valid unified diff 40 unified, _ := r.NormalizeGoplsCmd(t, "format", "-d", filename) 41 checkUnified(t, filename, expect, unified) 42 } 43 44 var unifiedHeader = regexp.MustCompile(`^diff -u.*\n(---\s+\S+\.go\.orig)\s+[\d-:. ]+(\n\+\+\+\s+\S+\.go)\s+[\d-:. ]+(\n@@)`) 45 46 func fixFileHeader(s string) string { 47 match := unifiedHeader.FindStringSubmatch(s) 48 if match == nil { 49 return s 50 } 51 return strings.Join(append(match[1:], s[len(match[0]):]), "") 52 } 53 54 func checkUnified(t *testing.T, filename string, expect string, patch string) { 55 testenv.NeedsTool(t, "patch") 56 if strings.Count(patch, "\n+++ ") > 1 { 57 // TODO(golang/go/#34580) 58 t.Skip("multi-file patch tests not supported yet") 59 } 60 applied := "" 61 if patch == "" { 62 applied = expect 63 } else { 64 temp, err := ioutil.TempFile("", "applied") 65 if err != nil { 66 t.Fatal(err) 67 } 68 temp.Close() 69 defer os.Remove(temp.Name()) 70 cmd := exec.Command("patch", "-u", "-p0", "-o", temp.Name(), filename) 71 cmd.Stdin = bytes.NewBuffer([]byte(patch)) 72 msg, err := cmd.CombinedOutput() 73 if err != nil { 74 t.Errorf("failed applying patch to %s: %v\ngot:\n%s\npatch:\n%s", filename, err, msg, patch) 75 return 76 } 77 out, err := ioutil.ReadFile(temp.Name()) 78 if err != nil { 79 t.Errorf("failed reading patched output for %s: %v\n", filename, err) 80 return 81 } 82 applied = string(out) 83 } 84 if expect != applied { 85 t.Errorf("apply unified gave wrong result for %s expected:\n%s\ngot:\n%s\npatch:\n%s", filename, expect, applied, patch) 86 } 87 }