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.
16 "golang.org/x/tools/internal/span"
17 "golang.org/x/tools/internal/testenv"
20 func (r *runner) Format(t *testing.T, spn span.Span) {
23 filename := uri.Filename()
24 expect := string(r.data.Golden(tag, filename, func() ([]byte, error) {
25 cmd := exec.Command("gofmt", filename)
26 contents, _ := cmd.Output() // ignore error, sometimes we have intentionally ungofmt-able files
27 contents = []byte(r.Normalize(fixFileHeader(string(contents))))
31 //TODO: our error handling differs, for now just skip unformattable files
32 t.Skip("Unformattable file")
34 got, _ := r.NormalizeGoplsCmd(t, "format", filename)
36 t.Errorf("format failed for %s expected:\n%s\ngot:\n%s", filename, expect, got)
38 // now check we can build a valid unified diff
39 unified, _ := r.NormalizeGoplsCmd(t, "format", "-d", filename)
40 checkUnified(t, filename, expect, unified)
43 var unifiedHeader = regexp.MustCompile(`^diff -u.*\n(---\s+\S+\.go\.orig)\s+[\d-:. ]+(\n\+\+\+\s+\S+\.go)\s+[\d-:. ]+(\n@@)`)
45 func fixFileHeader(s string) string {
46 match := unifiedHeader.FindStringSubmatch(s)
50 return strings.Join(append(match[1:], s[len(match[0]):]), "")
53 func checkUnified(t *testing.T, filename string, expect string, patch string) {
54 testenv.NeedsTool(t, "patch")
55 if strings.Count(patch, "\n+++ ") > 1 {
56 // TODO(golang/go/#34580)
57 t.Skip("multi-file patch tests not supported yet")
63 temp, err := ioutil.TempFile("", "applied")
68 defer os.Remove(temp.Name())
69 cmd := exec.Command("patch", "-u", "-p0", "-o", temp.Name(), filename)
70 cmd.Stdin = bytes.NewBuffer([]byte(patch))
71 msg, err := cmd.CombinedOutput()
73 t.Errorf("failed applying patch to %s: %v\ngot:\n%s\npatch:\n%s", filename, err, msg, patch)
76 out, err := ioutil.ReadFile(temp.Name())
78 t.Errorf("failed reading patched output for %s: %v\n", filename, err)
83 if expect != applied {
84 t.Errorf("apply unified gave wrong result for %s expected:\n%s\ngot:\n%s\npatch:\n%s", filename, expect, applied, patch)