From 6e57528ade4c045edb91dac8af1c4a3ab30fa738 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 7 Jul 2017 16:16:50 +0000 Subject: [PATCH] imports: fix reading from stdin on Windows Don't panic when reading from stdin on Windows. This is a regression from https://golang.org/cl/43454 Also fix some weird behavior with stdin processing I noticed during reviewing the code: don't allow the -w (write) flag, and adust the filename shown with the -d (diff) flag. Fixes golang/go#20941 Change-Id: I73d0a1dc74c919238a3bb72823585bbf1b7daba1 Reviewed-on: https://go-review.googlesource.com/47810 Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot Reviewed-by: Brad Jones Reviewed-by: Brad Fitzpatrick --- cmd/goimports/goimports.go | 7 +++++++ imports/fix.go | 10 ++++++---- imports/fix_test.go | 11 +++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/cmd/goimports/goimports.go b/cmd/goimports/goimports.go index b722c6a2..16e30834 100644 --- a/cmd/goimports/goimports.go +++ b/cmd/goimports/goimports.go @@ -144,12 +144,19 @@ func processFile(filename string, in io.Reader, out io.Writer, argType argumentT fmt.Fprintln(out, filename) } if *write { + if argType == fromStdin { + // filename is "" + return errors.New("can't use -w on stdin") + } err = ioutil.WriteFile(filename, res, 0) if err != nil { return err } } if *doDiff { + if argType == fromStdin { + filename = "stdin.go" // because .orig looks silly + } data, err := diff(src, res, filename) if err != nil { return fmt.Errorf("computing diff: %s", err) diff --git a/imports/fix.go b/imports/fix.go index f26414a5..ac7f4b00 100644 --- a/imports/fix.go +++ b/imports/fix.go @@ -254,10 +254,12 @@ func fixImports(fset *token.FileSet, f *ast.File, filename string) (added []stri results := make(chan result) for pkgName, symbols := range refs { go func(pkgName string, symbols map[string]bool) { - sibling := packageInfo.Imports[pkgName] - if sibling.Path != "" { - results <- result{ipath: sibling.Path, name: sibling.Alias} - return + if packageInfo != nil { + sibling := packageInfo.Imports[pkgName] + if sibling.Path != "" { + results <- result{ipath: sibling.Path, name: sibling.Alias} + return + } } ipath, rename, err := findImport(pkgName, symbols, filename) r := result{ipath: ipath, err: err} diff --git a/imports/fix_test.go b/imports/fix_test.go index 2026d5c9..ffab3907 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -1803,3 +1803,14 @@ func TestShouldTraverse(t *testing.T) { } } } + +// Issue 20941: this used to panic on Windows. +func TestProcessStdin(t *testing.T) { + got, err := Process("", []byte("package main\nfunc main() {\n\tfmt.Println(123)\n}\n"), nil) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(got), `"fmt"`) { + t.Errorf("expected fmt import; got: %s", got) + } +}