2019-04-07 21:08:47 -06:00
|
|
|
// Copyright 2019 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package cmd_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"os/exec"
|
2019-04-26 10:45:14 -06:00
|
|
|
"regexp"
|
2019-04-07 21:08:47 -06:00
|
|
|
"strings"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"golang.org/x/tools/internal/lsp/cmd"
|
|
|
|
"golang.org/x/tools/internal/lsp/tests"
|
|
|
|
"golang.org/x/tools/internal/tool"
|
|
|
|
)
|
|
|
|
|
|
|
|
var formatModes = [][]string{
|
|
|
|
[]string{},
|
|
|
|
[]string{"-d"},
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *runner) Format(t *testing.T, data tests.Formats) {
|
|
|
|
for _, spn := range data {
|
|
|
|
for _, mode := range formatModes {
|
2019-04-26 10:45:14 -06:00
|
|
|
tag := "gofmt" + strings.Join(mode, "")
|
2019-04-07 21:08:47 -06:00
|
|
|
uri := spn.URI()
|
2019-06-06 11:51:00 -06:00
|
|
|
filename := uri.Filename()
|
2019-04-07 21:08:47 -06:00
|
|
|
args := append(mode, filename)
|
2019-05-01 17:16:03 -06:00
|
|
|
expect := string(r.data.Golden(tag, filename, func() ([]byte, error) {
|
2019-04-07 21:08:47 -06:00
|
|
|
cmd := exec.Command("gofmt", args...)
|
2019-05-01 17:16:03 -06:00
|
|
|
contents, _ := cmd.Output() // ignore error, sometimes we have intentionally ungofmt-able files
|
2019-04-29 12:57:27 -06:00
|
|
|
contents = []byte(normalizePaths(r.data, fixFileHeader(string(contents))))
|
2019-05-01 17:16:03 -06:00
|
|
|
return contents, nil
|
2019-04-07 21:08:47 -06:00
|
|
|
}))
|
|
|
|
if expect == "" {
|
|
|
|
//TODO: our error handling differs, for now just skip unformattable files
|
|
|
|
continue
|
|
|
|
}
|
2019-05-17 08:51:19 -06:00
|
|
|
app := cmd.New(r.data.Config.Dir, r.data.Config.Env)
|
2019-04-07 21:08:47 -06:00
|
|
|
got := captureStdOut(t, func() {
|
2019-05-07 11:54:07 -06:00
|
|
|
tool.Main(context.Background(), app, append([]string{"-remote=internal", "format"}, args...))
|
2019-04-07 21:08:47 -06:00
|
|
|
})
|
2019-04-29 12:57:27 -06:00
|
|
|
got = normalizePaths(r.data, got)
|
2019-04-07 21:08:47 -06:00
|
|
|
// check the first two lines are the expected file header
|
|
|
|
if expect != got {
|
|
|
|
t.Errorf("format failed with %#v expected:\n%s\ngot:\n%s", args, expect, got)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-26 10:45:14 -06:00
|
|
|
var unifiedHeader = regexp.MustCompile(`^diff -u.*\n(---\s+\S+\.go\.orig)\s+[\d-:. ]+(\n\+\+\+\s+\S+\.go)\s+[\d-:. ]+(\n@@)`)
|
|
|
|
|
|
|
|
func fixFileHeader(s string) string {
|
|
|
|
match := unifiedHeader.FindStringSubmatch(s)
|
|
|
|
if match == nil {
|
|
|
|
return s
|
2019-04-07 21:08:47 -06:00
|
|
|
}
|
2019-04-26 10:45:14 -06:00
|
|
|
return strings.Join(append(match[1:], s[len(match[0]):]), "")
|
2019-04-07 21:08:47 -06:00
|
|
|
}
|