Debian Codegraph @

refactor/rename/rename_test.go

raw symbols SCIP
1 // Copyright 2014 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 rename
6
7 import (
8 "bytes"
9 "fmt"
10 "go/build"
11 "go/token"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "runtime"
17 "strings"
18 "testing"
19
20 "golang.org/x/tools/go/buildutil"
21 "golang.org/x/tools/internal/testenv"
22 )
23
24 // TODO(adonovan): test reported source positions, somehow.
25
26 func TestConflicts(t *testing.T) {
27 defer func(savedWriteFile func(string, []byte) error, savedReportError func(token.Position, string)) {
28 writeFile = savedWriteFile
29 reportError = savedReportError
30 }(writeFile, reportError)
31 writeFile = func(string, []byte) error { return nil }
32
33 var ctxt *build.Context
34 for _, test := range []struct {
35 ctxt *build.Context // nil => use previous
36 offset, from, to string // values of the -offset/-from and -to flags
37 want string // regexp to match conflict errors, or "OK"
38 }{
39 // init() checks
40 {
41 ctxt: fakeContext(map[string][]string{
42 "fmt": {`package fmt; type Stringer interface { String() }`},
43 "main": {`
44 package main
45
46 import foo "fmt"
47
48 var v foo.Stringer
49
50 func f() { v.String(); f() }
51 `,
52 `package main; var w int`},
53 }),
54 from: "main.v", to: "init",
55 want: `you cannot have a var at package level named "init"`,
56 },
57 {
58 from: "main.f", to: "init",
59 want: `renaming this func "f" to "init" would make it a package initializer.*` +
60 `but references to it exist`,
61 },
62 {
63 from: "/go/src/main/0.go::foo", to: "init",
64 want: `"init" is not a valid imported package name`,
65 },
66
67 // Export checks
68 {
69 from: "fmt.Stringer", to: "stringer",
70 want: `renaming this type "Stringer" to "stringer" would make it unexported.*` +
71 `breaking references from packages such as "main"`,
72 },
73 {
74 from: "(fmt.Stringer).String", to: "string",
75 want: `renaming this method "String" to "string" would make it unexported.*` +
76 `breaking references from packages such as "main"`,
77 },
78
79 // Lexical scope checks
80 {
81 // file/package conflict, same file
82 from: "main.v", to: "foo",
83 want: `renaming this var "v" to "foo" would conflict.*` +
84 `with this imported package name`,
85 },
86 {
87 // file/package conflict, same file
88 from: "main::foo", to: "v",
89 want: `renaming this imported package name "foo" to "v" would conflict.*` +
90 `with this package member var`,
91 },
92 {
93 // file/package conflict, different files
94 from: "main.w", to: "foo",
95 want: `renaming this var "w" to "foo" would conflict.*` +
96 `with this imported package name`,
97 },
98 {
99 // file/package conflict, different files
100 from: "main::foo", to: "w",
101 want: `renaming this imported package name "foo" to "w" would conflict.*` +
102 `with this package member var`,
103 },
104 {
105 ctxt: main(`
106 package main
107
108 var x, z int
109
110 func f(y int) {
111 print(x)
112 print(y)
113 }
114
115 func g(w int) {
116 print(x)
117 x := 1
118 print(x)
119 }`),
120 from: "main.x", to: "y",
121 want: `renaming this var "x" to "y".*` +
122 `would cause this reference to become shadowed.*` +
123 `by this intervening var definition`,
124 },
125 {
126 from: "main.g::x", to: "w",
127 want: `renaming this var "x" to "w".*` +
128 `conflicts with var in same block`,
129 },
130 {
131 from: "main.f::y", to: "x",
132 want: `renaming this var "y" to "x".*` +
133 `would shadow this reference.*` +
134 `to the var declared here`,
135 },
136 {
137 from: "main.g::w", to: "x",
138 want: `renaming this var "w" to "x".*` +
139 `conflicts with var in same block`,
140 },
141 {
142 from: "main.z", to: "y", want: "OK",
143 },
144
145 // Label checks
146 {
147 ctxt: main(`
148 package main
149
150 func f() {
151 foo:
152 goto foo
153 bar:
154 goto bar
155 func(x int) {
156 wiz:
157 goto wiz
158 }(0)
159 }
160 `),
161 from: "main.f::foo", to: "bar",
162 want: `renaming this label "foo" to "bar".*` +
163 `would conflict with this one`,
164 },
165 {
166 from: "main.f::foo", to: "wiz", want: "OK",
167 },
168 {
169 from: "main.f::wiz", to: "x", want: "OK",
170 },
171 {
172 from: "main.f::x", to: "wiz", want: "OK",
173 },
174 {
175 from: "main.f::wiz", to: "foo", want: "OK",
176 },
177
178 // Struct fields
179 {
180 ctxt: main(`
181 package main
182
183 type U struct { u int }
184 type V struct { v int }
185
186 func (V) x() {}
187
188 type W (struct {
189 U
190 V
191 w int
192 })
193
194 func f() {
195 var w W
196 print(w.u) // NB: there is no selection of w.v
197 var _ struct { yy, zz int }
198 }
199 `),
200 // field/field conflict in named struct declaration
201 from: "(main.W).U", to: "w",
202 want: `renaming this field "U" to "w".*` +
203 `would conflict with this field`,
204 },
205 {
206 // rename type used as embedded field
207 // => rename field
208 // => field/field conflict
209 // This is an entailed renaming;
210 // it would be nice if we checked source positions.
211 from: "main.U", to: "w",
212 want: `renaming this field "U" to "w".*` +
213 `would conflict with this field`,
214 },
215 {
216 // field/field conflict in unnamed struct declaration
217 from: "main.f::zz", to: "yy",
218 want: `renaming this field "zz" to "yy".*` +
219 `would conflict with this field`,
220 },
221
222 // Now we test both directions of (u,v) (u,w) (v,w) (u,x) (v,x).
223 // Too bad we don't test position info...
224 {
225 // field/field ambiguity at same promotion level ('from' selection)
226 from: "(main.U).u", to: "v",
227 want: `renaming this field "u" to "v".*` +
228 `would make this reference ambiguous.*` +
229 `with this field`,
230 },
231 {
232 // field/field ambiguity at same promotion level ('to' selection)
233 from: "(main.V).v", to: "u",
234 want: `renaming this field "v" to "u".*` +
235 `would make this reference ambiguous.*` +
236 `with this field`,
237 },
238 {
239 // field/method conflict at different promotion level ('from' selection)
240 from: "(main.U).u", to: "w",
241 want: `renaming this field "u" to "w".*` +
242 `would change the referent of this selection.*` +
243 `of this field`,
244 },
245 {
246 // field/field shadowing at different promotion levels ('to' selection)
247 from: "(main.W).w", to: "u",
248 want: `renaming this field "w" to "u".*` +
249 `would shadow this selection.*` +
250 `of the field declared here`,
251 },
252 {
253 from: "(main.V).v", to: "w",
254 want: "OK", // since no selections are made ambiguous
255 },
256 {
257 from: "(main.W).w", to: "v",
258 want: "OK", // since no selections are made ambiguous
259 },
260 {
261 // field/method ambiguity at same promotion level ('from' selection)
262 from: "(main.U).u", to: "x",
263 want: `renaming this field "u" to "x".*` +
264 `would make this reference ambiguous.*` +
265 `with this method`,
266 },
267 {
268 // field/field ambiguity at same promotion level ('to' selection)
269 from: "(main.V).x", to: "u",
270 want: `renaming this method "x" to "u".*` +
271 `would make this reference ambiguous.*` +
272 `with this field`,
273 },
274 {
275 // field/method conflict at named struct declaration
276 from: "(main.V).v", to: "x",
277 want: `renaming this field "v" to "x".*` +
278 `would conflict with this method`,
279 },
280 {
281 // field/method conflict at named struct declaration
282 from: "(main.V).x", to: "v",
283 want: `renaming this method "x" to "v".*` +
284 `would conflict with this field`,
285 },
286
287 // Methods
288 {
289 ctxt: main(`
290 package main
291 type C int
292 func (C) f()
293 func (C) g()
294 type D int
295 func (*D) f()
296 func (*D) g()
297 type I interface { f(); g() }
298 type J interface { I; h() }
299 var _ I = new(D)
300 var _ interface {f()} = C(0)
301 `),
302 from: "(main.I).f", to: "g",
303 want: `renaming this interface method "f" to "g".*` +
304 `would conflict with this method`,
305 },
306 {
307 from: `("main".I).f`, to: "h", // NB: exercises quoted import paths too
308 want: `renaming this interface method "f" to "h".*` +
309 `would conflict with this method.*` +
310 `in named interface type "J"`,
311 },
312 {
313 // type J interface { h; h() } is not a conflict, amusingly.
314 from: "main.I", to: "h",
315 want: `OK`,
316 },
317 {
318 from: "(main.J).h", to: "f",
319 want: `renaming this interface method "h" to "f".*` +
320 `would conflict with this method`,
321 },
322 {
323 from: "(main.C).f", to: "e",
324 want: `renaming this method "f" to "e".*` +
325 `would make main.C no longer assignable to interface{f..}.*` +
326 `(rename interface{f..}.f if you intend to change both types)`,
327 },
328 {
329 from: "(main.D).g", to: "e",
330 want: `renaming this method "g" to "e".*` +
331 `would make \*main.D no longer assignable to interface I.*` +
332 `(rename main.I.g if you intend to change both types)`,
333 },
334 {
335 from: "(main.I).f", to: "e",
336 want: `OK`,
337 },
338 // Indirect C/I method coupling via another concrete type D.
339 {
340 ctxt: main(`
341 package main
342 type I interface { f() }
343 type C int
344 func (C) f()
345 type D struct{C}
346 var _ I = D{}
347 `),
348 from: "(main.C).f", to: "F",
349 want: `renaming this method "f" to "F".*` +
350 `would make main.D no longer assignable to interface I.*` +
351 `(rename main.I.f if you intend to change both types)`,
352 },
353 // Renaming causes promoted method to become shadowed; C no longer satisfies I.
354 {
355 ctxt: main(`
356 package main
357 type I interface { f() }
358 type C struct { I }
359 func (C) g() int
360 var _ I = C{}
361 `),
362 from: "main.I.f", to: "g",
363 want: `renaming this method "f" to "g".*` +
364 `would change the g method of main.C invoked via interface main.I.*` +
365 `from \(main.I\).g.*` +
366 `to \(main.C\).g`,
367 },
368 // Renaming causes promoted method to become ambiguous; C no longer satisfies I.
369 {
370 ctxt: main(`
371 package main
372 type I interface{f()}
373 type C int
374 func (C) f()
375 type D int
376 func (D) g()
377 type E struct{C;D}
378 var _ I = E{}
379 `),
380 from: "main.I.f", to: "g",
381 want: `renaming this method "f" to "g".*` +
382 `would make the g method of main.E invoked via interface main.I ambiguous.*` +
383 `with \(main.D\).g`,
384 },
385 } {
386 var conflicts []string
387 reportError = func(posn token.Position, message string) {
388 conflicts = append(conflicts, message)
389 }
390 if test.ctxt != nil {
391 ctxt = test.ctxt
392 }
393 err := Main(ctxt, test.offset, test.from, test.to)
394 var prefix string
395 if test.offset == "" {
396 prefix = fmt.Sprintf("-from %q -to %q", test.from, test.to)
397 } else {
398 prefix = fmt.Sprintf("-offset %q -to %q", test.offset, test.to)
399 }
400 if err == ConflictError {
401 got := strings.Join(conflicts, "\n")
402 if false {
403 t.Logf("%s: %s", prefix, got)
404 }
405 pattern := "(?s:" + test.want + ")" // enable multi-line matching
406 if !regexp.MustCompile(pattern).MatchString(got) {
407 t.Errorf("%s: conflict does not match pattern:\n"+
408 "Conflict:\t%s\n"+
409 "Pattern: %s",
410 prefix, got, test.want)
411 }
412 } else if err != nil {
413 t.Errorf("%s: unexpected error: %s", prefix, err)
414 } else if test.want != "OK" {
415 t.Errorf("%s: unexpected success, want conflicts matching:\n%s",
416 prefix, test.want)
417 }
418 }
419 }
420
421 func TestInvalidIdentifiers(t *testing.T) {
422 ctxt := fakeContext(map[string][]string{
423 "main": {`
424 package main
425
426 func f() { }
427 `}})
428
429 for _, test := range []struct {
430 from, to string // values of the -offset/-from and -to flags
431 want string // expected error message
432 }{
433 {
434 from: "main.f", to: "_",
435 want: `-to "_": not a valid identifier`,
436 },
437 {
438 from: "main.f", to: "123",
439 want: `-to "123": not a valid identifier`,
440 },
441 {
442 from: "main.f", to: "for",
443 want: `-to "for": not a valid identifier`,
444 },
445 {
446 from: "switch", to: "v",
447 want: `-from "switch": invalid expression`,
448 },
449 } {
450 err := Main(ctxt, "", test.from, test.to)
451 prefix := fmt.Sprintf("-from %q -to %q", test.from, test.to)
452 if err == nil {
453 t.Errorf("%s: expected error %q", prefix, test.want)
454 } else if err.Error() != test.want {
455 t.Errorf("%s: unexpected error\nwant: %s\n got: %s", prefix, test.want, err.Error())
456 }
457 }
458 }
459
460 func TestRewrites(t *testing.T) {
461 defer func(savedWriteFile func(string, []byte) error) {
462 writeFile = savedWriteFile
463 }(writeFile)
464
465 var ctxt *build.Context
466 for _, test := range []struct {
467 ctxt *build.Context // nil => use previous
468 offset, from, to string // values of the -from/-offset and -to flags
469 want map[string]string // contents of updated files
470 alias bool // requires materialized aliases
471 }{
472 // Elimination of renaming import.
473 {
474 ctxt: fakeContext(map[string][]string{
475 "foo": {`package foo; type T int`},
476 "main": {`package main
477
478 import foo2 "foo"
479
480 var _ foo2.T
481 `},
482 }),
483 from: "main::foo2", to: "foo",
484 want: map[string]string{
485 "/go/src/main/0.go": `package main
486
487 import "foo"
488
489 var _ foo.T
490 `,
491 },
492 },
493 // Introduction of renaming import.
494 {
495 ctxt: fakeContext(map[string][]string{
496 "foo": {`package foo; type T int`},
497 "main": {`package main
498
499 import "foo"
500
501 var _ foo.T
502 `},
503 }),
504 offset: "/go/src/main/0.go:#36", to: "foo2", // the "foo" in foo.T
505 want: map[string]string{
506 "/go/src/main/0.go": `package main
507
508 import foo2 "foo"
509
510 var _ foo2.T
511 `,
512 },
513 },
514 // Renaming of package-level member.
515 {
516 from: "foo.T", to: "U",
517 want: map[string]string{
518 "/go/src/main/0.go": `package main
519
520 import "foo"
521
522 var _ foo.U
523 `,
524 "/go/src/foo/0.go": `package foo
525
526 type U int
527 `,
528 },
529 },
530 // Rename package-level func plus doc
531 {
532 ctxt: main(`package main
533
534 // Foo is a no-op.
535 // Calling Foo does nothing.
536 func Foo() {
537 }
538 `),
539 from: "main.Foo", to: "FooBar",
540 want: map[string]string{
541 "/go/src/main/0.go": `package main
542
543 // FooBar is a no-op.
544 // Calling FooBar does nothing.
545 func FooBar() {
546 }
547 `,
548 },
549 },
550 // Rename method plus doc
551 {
552 ctxt: main(`package main
553
554 type Foo struct{}
555
556 // Bar does nothing.
557 func (Foo) Bar() {
558 }
559 `),
560 from: "main.Foo.Bar", to: "Baz",
561 want: map[string]string{
562 "/go/src/main/0.go": `package main
563
564 type Foo struct{}
565
566 // Baz does nothing.
567 func (Foo) Baz() {
568 }
569 `,
570 },
571 },
572 // Rename type spec plus doc
573 {
574 ctxt: main(`package main
575
576 type (
577 // Test but not Testing.
578 Test struct{}
579 )
580 `),
581 from: "main.Test", to: "Type",
582 want: map[string]string{
583 "/go/src/main/0.go": `package main
584
585 type (
586 // Type but not Testing.
587 Type struct{}
588 )
589 `,
590 },
591 },
592 // Rename type in gen decl plus doc
593 {
594 ctxt: main(`package main
595
596 // T is a test type.
597 type T struct{}
598 `),
599 from: "main.T", to: "Type",
600 want: map[string]string{
601 "/go/src/main/0.go": `package main
602
603 // Type is a test type.
604 type Type struct{}
605 `,
606 },
607 },
608 // Rename value spec with doc
609 {
610 ctxt: main(`package main
611
612 const (
613 // C is the speed of light.
614 C = 2.998e8
615 )
616 `),
617 from: "main.C", to: "Lightspeed",
618 want: map[string]string{
619 "/go/src/main/0.go": `package main
620
621 const (
622 // Lightspeed is the speed of light.
623 Lightspeed = 2.998e8
624 )
625 `,
626 },
627 },
628 // Rename value inside gen decl with doc
629 {
630 ctxt: main(`package main
631
632 var out *string
633 `),
634 from: "main.out", to: "discard",
635 want: map[string]string{
636 "/go/src/main/0.go": `package main
637
638 var discard *string
639 `,
640 },
641 },
642 // Rename field plus doc
643 {
644 ctxt: main(`package main
645
646 type Struct struct {
647 // Field is a struct field.
648 Field string
649 }
650 `),
651 from: "main.Struct.Field", to: "Foo",
652 want: map[string]string{
653 "/go/src/main/0.go": `package main
654
655 type Struct struct {
656 // Foo is a struct field.
657 Foo string
658 }
659 `,
660 },
661 },
662 // Label renamings.
663 {
664 ctxt: main(`package main
665 func f() {
666 loop:
667 loop := 0
668 go func() {
669 loop:
670 goto loop
671 }()
672 loop++
673 goto loop
674 }
675 `),
676 offset: "/go/src/main/0.go:#25", to: "loop2", // def of outer label "loop"
677 want: map[string]string{
678 "/go/src/main/0.go": `package main
679
680 func f() {
681 loop2:
682 loop := 0
683 go func() {
684 loop:
685 goto loop
686 }()
687 loop++
688 goto loop2
689 }
690 `,
691 },
692 },
693 {
694 offset: "/go/src/main/0.go:#70", to: "loop2", // ref to inner label "loop"
695 want: map[string]string{
696 "/go/src/main/0.go": `package main
697
698 func f() {
699 loop:
700 loop := 0
701 go func() {
702 loop2:
703 goto loop2
704 }()
705 loop++
706 goto loop
707 }
708 `,
709 },
710 },
711 // Renaming of type used as embedded field.
712 {
713 ctxt: main(`package main
714
715 type T int
716 type U struct { T }
717
718 var _ = U{}.T
719 `),
720 from: "main.T", to: "T2",
721 want: map[string]string{
722 "/go/src/main/0.go": `package main
723
724 type T2 int
725 type U struct{ T2 }
726
727 var _ = U{}.T2
728 `,
729 },
730 },
731 // Renaming of embedded field.
732 {
733 ctxt: main(`package main
734
735 type T int
736 type U struct { T }
737
738 var _ = U{}.T
739 `),
740 offset: "/go/src/main/0.go:#58", to: "T2", // T in "U{}.T"
741 want: map[string]string{
742 "/go/src/main/0.go": `package main
743
744 type T2 int
745 type U struct{ T2 }
746
747 var _ = U{}.T2
748 `,
749 },
750 },
751 // Renaming of pointer embedded field.
752 {
753 ctxt: main(`package main
754
755 type T int
756 type U struct { *T }
757
758 var _ = U{}.T
759 `),
760 offset: "/go/src/main/0.go:#59", to: "T2", // T in "U{}.T"
761 want: map[string]string{
762 "/go/src/main/0.go": `package main
763
764 type T2 int
765 type U struct{ *T2 }
766
767 var _ = U{}.T2
768 `,
769 },
770 },
771 // Renaming of embedded field alias.
772 {
773 alias: true,
774 ctxt: main(`package main
775
776 type T int
777 type A = T
778 type U struct{ A }
779
780 var _ = U{}.A
781 var a A
782 `),
783 offset: "/go/src/main/0.go:#68", to: "A2", // A in "U{}.A"
784 want: map[string]string{
785 "/go/src/main/0.go": `package main
786
787 type T int
788 type A2 = T
789 type U struct{ A2 }
790
791 var _ = U{}.A2
792 var a A2
793 `,
794 },
795 },
796 // Renaming of embedded field pointer to alias.
797 {
798 alias: true,
799 ctxt: main(`package main
800
801 type T int
802 type A = T
803 type U struct{ *A }
804
805 var _ = U{}.A
806 var a A
807 `),
808 offset: "/go/src/main/0.go:#69", to: "A2", // A in "U{}.A"
809 want: map[string]string{
810 "/go/src/main/0.go": `package main
811
812 type T int
813 type A2 = T
814 type U struct{ *A2 }
815
816 var _ = U{}.A2
817 var a A2
818 `,
819 },
820 },
821 // Renaming of alias
822 {
823 ctxt: main(`package main
824
825 type A = int
826
827 func _() A {
828 return A(0)
829 }
830 `),
831 offset: "/go/src/main/0.go:#49", to: "A2", // A in "A(0)"
832 want: map[string]string{
833 "/go/src/main/0.go": `package main
834
835 type A2 = int
836
837 func _() A2 {
838 return A2(0)
839 }
840 `,
841 },
842 },
843
844 // Lexical scope tests.
845 {
846 ctxt: main(`package main
847
848 var y int
849
850 func f() {
851 print(y)
852 y := ""
853 print(y)
854 }
855 `),
856 from: "main.y", to: "x",
857 want: map[string]string{
858 "/go/src/main/0.go": `package main
859
860 var x int
861
862 func f() {
863 print(x)
864 y := ""
865 print(y)
866 }
867 `,
868 },
869 },
870 {
871 from: "main.f::y", to: "x",
872 want: map[string]string{
873 "/go/src/main/0.go": `package main
874
875 var y int
876
877 func f() {
878 print(y)
879 x := ""
880 print(x)
881 }
882 `,
883 },
884 },
885 // Renaming of typeswitch vars (a corner case).
886 {
887 ctxt: main(`package main
888
889 func f(z interface{}) {
890 switch y := z.(type) {
891 case int:
892 print(y)
893 default:
894 print(y)
895 }
896 }
897 `),
898 offset: "/go/src/main/0.go:#46", to: "x", // def of y
899 want: map[string]string{
900 "/go/src/main/0.go": `package main
901
902 func f(z interface{}) {
903 switch x := z.(type) {
904 case int:
905 print(x)
906 default:
907 print(x)
908 }
909 }
910 `},
911 },
912 {
913 offset: "/go/src/main/0.go:#81", to: "x", // ref of y in case int
914 want: map[string]string{
915 "/go/src/main/0.go": `package main
916
917 func f(z interface{}) {
918 switch x := z.(type) {
919 case int:
920 print(x)
921 default:
922 print(x)
923 }
924 }
925 `},
926 },
927 {
928 offset: "/go/src/main/0.go:#102", to: "x", // ref of y in default case
929 want: map[string]string{
930 "/go/src/main/0.go": `package main
931
932 func f(z interface{}) {
933 switch x := z.(type) {
934 case int:
935 print(x)
936 default:
937 print(x)
938 }
939 }
940 `},
941 },
942
943 // Renaming of embedded field that is a qualified reference.
944 // (Regression test for bug 8924.)
945 {
946 ctxt: fakeContext(map[string][]string{
947 "foo": {`package foo; type T int`},
948 "main": {`package main
949
950 import "foo"
951
952 type _ struct{ *foo.T }
953 `},
954 }),
955 offset: "/go/src/main/0.go:#48", to: "U", // the "T" in *foo.T
956 want: map[string]string{
957 "/go/src/foo/0.go": `package foo
958
959 type U int
960 `,
961 "/go/src/main/0.go": `package main
962
963 import "foo"
964
965 type _ struct{ *foo.U }
966 `,
967 },
968 },
969
970 // Renaming of embedded field that is a qualified reference with the '-from' flag.
971 // (Regression test for bug 12038.)
972 {
973 ctxt: fakeContext(map[string][]string{
974 "foo": {`package foo; type T int`},
975 "main": {`package main
976
977 import "foo"
978
979 type V struct{ *foo.T }
980 `},
981 }),
982 from: "(main.V).T", to: "U", // the "T" in *foo.T
983 want: map[string]string{
984 "/go/src/foo/0.go": `package foo
985
986 type U int
987 `,
988 "/go/src/main/0.go": `package main
989
990 import "foo"
991
992 type V struct{ *foo.U }
993 `,
994 },
995 },
996 {
997 ctxt: fakeContext(map[string][]string{
998 "foo": {`package foo; type T int`},
999 "main": {`package main
1000
1001 import "foo"
1002
1003 type V struct{ foo.T }
1004 `},
1005 }),
1006 from: "(main.V).T", to: "U", // the "T" in *foo.T
1007 want: map[string]string{
1008 "/go/src/foo/0.go": `package foo
1009
1010 type U int
1011 `,
1012 "/go/src/main/0.go": `package main
1013
1014 import "foo"
1015
1016 type V struct{ foo.U }
1017 `,
1018 },
1019 },
1020
1021 // Interface method renaming.
1022 {
1023 ctxt: fakeContext(map[string][]string{
1024 "main": {`
1025 package main
1026 type I interface {
1027 f()
1028 }
1029 type J interface { f(); g() }
1030 type A int
1031 func (A) f()
1032 type B int
1033 func (B) f()
1034 func (B) g()
1035 type C int
1036 func (C) f()
1037 func (C) g()
1038 var _, _ I = A(0), B(0)
1039 var _, _ J = B(0), C(0)
1040 `,
1041 },
1042 }),
1043 offset: "/go/src/main/0.go:#34", to: "F", // abstract method I.f
1044 want: map[string]string{
1045 "/go/src/main/0.go": `package main
1046
1047 type I interface {
1048 F()
1049 }
1050 type J interface {
1051 F()
1052 g()
1053 }
1054 type A int
1055
1056 func (A) F()
1057
1058 type B int
1059
1060 func (B) F()
1061 func (B) g()
1062
1063 type C int
1064
1065 func (C) F()
1066 func (C) g()
1067
1068 var _, _ I = A(0), B(0)
1069 var _, _ J = B(0), C(0)
1070 `,
1071 },
1072 },
1073 {
1074 offset: "/go/src/main/0.go:#59", to: "F", // abstract method J.f
1075 want: map[string]string{
1076 "/go/src/main/0.go": `package main
1077
1078 type I interface {
1079 F()
1080 }
1081 type J interface {
1082 F()
1083 g()
1084 }
1085 type A int
1086
1087 func (A) F()
1088
1089 type B int
1090
1091 func (B) F()
1092 func (B) g()
1093
1094 type C int
1095
1096 func (C) F()
1097 func (C) g()
1098
1099 var _, _ I = A(0), B(0)
1100 var _, _ J = B(0), C(0)
1101 `,
1102 },
1103 },
1104 {
1105 offset: "/go/src/main/0.go:#64", to: "G", // abstract method J.g
1106 want: map[string]string{
1107 "/go/src/main/0.go": `package main
1108
1109 type I interface {
1110 f()
1111 }
1112 type J interface {
1113 f()
1114 G()
1115 }
1116 type A int
1117
1118 func (A) f()
1119
1120 type B int
1121
1122 func (B) f()
1123 func (B) G()
1124
1125 type C int
1126
1127 func (C) f()
1128 func (C) G()
1129
1130 var _, _ I = A(0), B(0)
1131 var _, _ J = B(0), C(0)
1132 `,
1133 },
1134 },
1135 // Indirect coupling of I.f to C.f from D->I assignment and anonymous field of D.
1136 {
1137 ctxt: fakeContext(map[string][]string{
1138 "main": {`
1139 package main
1140 type I interface {
1141 f()
1142 }
1143 type C int
1144 func (C) f()
1145 type D struct{C}
1146 var _ I = D{}
1147 `,
1148 },
1149 }),
1150 offset: "/go/src/main/0.go:#34", to: "F", // abstract method I.f
1151 want: map[string]string{
1152 "/go/src/main/0.go": `package main
1153
1154 type I interface {
1155 F()
1156 }
1157 type C int
1158
1159 func (C) F()
1160
1161 type D struct{ C }
1162
1163 var _ I = D{}
1164 `,
1165 },
1166 },
1167 // Interface embedded in struct. No conflict if C need not satisfy I.
1168 {
1169 ctxt: fakeContext(map[string][]string{
1170 "main": {`
1171 package main
1172 type I interface {
1173 f()
1174 }
1175 type C struct{I}
1176 func (C) g() int
1177 var _ int = C{}.g()
1178 `,
1179 },
1180 }),
1181 offset: "/go/src/main/0.go:#34", to: "g", // abstract method I.f
1182 want: map[string]string{
1183 "/go/src/main/0.go": `package main
1184
1185 type I interface {
1186 g()
1187 }
1188 type C struct{ I }
1189
1190 func (C) g() int
1191
1192 var _ int = C{}.g()
1193 `,
1194 },
1195 },
1196 // A type assertion causes method coupling iff signatures match.
1197 {
1198 ctxt: fakeContext(map[string][]string{
1199 "main": {`package main
1200 type I interface{
1201 f()
1202 }
1203 type J interface{
1204 f()
1205 }
1206 var _ = I(nil).(J)
1207 `,
1208 },
1209 }),
1210 offset: "/go/src/main/0.go:#32", to: "g", // abstract method I.f
1211 want: map[string]string{
1212 "/go/src/main/0.go": `package main
1213
1214 type I interface {
1215 g()
1216 }
1217 type J interface {
1218 g()
1219 }
1220
1221 var _ = I(nil).(J)
1222 `,
1223 },
1224 },
1225 // Impossible type assertion: no method coupling.
1226 {
1227 ctxt: fakeContext(map[string][]string{
1228 "main": {`package main
1229 type I interface{
1230 f()
1231 }
1232 type J interface{
1233 f()int
1234 }
1235 var _ = I(nil).(J)
1236 `,
1237 },
1238 }),
1239 offset: "/go/src/main/0.go:#32", to: "g", // abstract method I.f
1240 want: map[string]string{
1241 "/go/src/main/0.go": `package main
1242
1243 type I interface {
1244 g()
1245 }
1246 type J interface {
1247 f() int
1248 }
1249
1250 var _ = I(nil).(J)
1251 `,
1252 },
1253 },
1254 // Impossible type assertion: no method coupling C.f<->J.f.
1255 {
1256 ctxt: fakeContext(map[string][]string{
1257 "main": {`package main
1258 type I interface{
1259 f()
1260 }
1261 type C int
1262 func (C) f()
1263 type J interface{
1264 f()int
1265 }
1266 var _ = I(C(0)).(J)
1267 `,
1268 },
1269 }),
1270 offset: "/go/src/main/0.go:#32", to: "g", // abstract method I.f
1271 want: map[string]string{
1272 "/go/src/main/0.go": `package main
1273
1274 type I interface {
1275 g()
1276 }
1277 type C int
1278
1279 func (C) g()
1280
1281 type J interface {
1282 f() int
1283 }
1284
1285 var _ = I(C(0)).(J)
1286 `,
1287 },
1288 },
1289 // Progress after "soft" type errors (Go issue 14596).
1290 {
1291 ctxt: fakeContext(map[string][]string{
1292 "main": {`package main
1293
1294 func main() {
1295 var unused, x int
1296 print(x)
1297 }
1298 `,
1299 },
1300 }),
1301 offset: "/go/src/main/0.go:#54", to: "y", // var x
1302 want: map[string]string{
1303 "/go/src/main/0.go": `package main
1304
1305 func main() {
1306 var unused, y int
1307 print(y)
1308 }
1309 `,
1310 },
1311 },
1312 } {
1313 if test.ctxt != nil {
1314 ctxt = test.ctxt
1315 }
1316
1317 got := make(map[string]string)
1318 writeFile = func(filename string, content []byte) error {
1319 got[filepath.ToSlash(filename)] = string(content)
1320 return nil
1321 }
1322
1323 err := Main(ctxt, test.offset, test.from, test.to)
1324 var prefix string
1325 if test.offset == "" {
1326 prefix = fmt.Sprintf("-from %q -to %q", test.from, test.to)
1327 } else {
1328 prefix = fmt.Sprintf("-offset %q -to %q", test.offset, test.to)
1329 }
1330 if err != nil {
1331 t.Errorf("%s: unexpected error: %s", prefix, err)
1332 continue
1333 }
1334
1335 for file, wantContent := range test.want {
1336 gotContent, ok := got[file]
1337 delete(got, file)
1338 if !ok {
1339 t.Errorf("%s: file %s not rewritten", prefix, file)
1340 continue
1341 }
1342 if gotContent != wantContent {
1343 t.Errorf("%s: rewritten file %s does not match expectation; got <<<%s>>>\n"+
1344 "want <<<%s>>>", prefix, file, gotContent, wantContent)
1345 }
1346 }
1347 // got should now be empty
1348 for file := range got {
1349 t.Errorf("%s: unexpected rewrite of file %s", prefix, file)
1350 }
1351 }
1352 }
1353
1354 func TestDiff(t *testing.T) {
1355 switch runtime.GOOS {
1356 case "windows":
1357 if os.Getenv("GO_BUILDER_NAME") != "" {
1358 if _, err := exec.LookPath(DiffCmd); err != nil {
1359 t.Skipf("diff tool non-existent for %s on builders", runtime.GOOS)
1360 }
1361 }
1362 case "plan9":
1363 t.Skipf("plan9 diff tool doesn't support -u flag")
1364 }
1365 testenv.NeedsTool(t, DiffCmd)
1366 testenv.NeedsTool(t, "go") // to locate the package to be renamed
1367
1368 defer func() {
1369 Diff = false
1370 stdout = os.Stdout
1371 }()
1372 Diff = true
1373 stdout = new(bytes.Buffer)
1374
1375 // Set up a fake GOPATH in a temporary directory,
1376 // and ensure we're in GOPATH mode.
1377 tmpdir, err := os.MkdirTemp("", "TestDiff")
1378 if err != nil {
1379 t.Fatal(err)
1380 }
1381 defer os.RemoveAll(tmpdir)
1382 buildCtx := build.Default
1383 buildCtx.GOPATH = tmpdir
1384
1385 pkgDir := filepath.Join(tmpdir, "src", "example.com", "rename")
1386 if err := os.MkdirAll(pkgDir, 0777); err != nil {
1387 t.Fatal(err)
1388 }
1389
1390 prevWD, err := os.Getwd()
1391 if err != nil {
1392 t.Fatal(err)
1393 }
1394 defer os.Chdir(prevWD)
1395
1396 if err := os.Chdir(pkgDir); err != nil {
1397 t.Fatal(err)
1398 }
1399
1400 const modFile = `module example.com/rename
1401
1402 go 1.15
1403 `
1404 if err := os.WriteFile(filepath.Join(pkgDir, "go.mod"), []byte(modFile), 0644); err != nil {
1405 t.Fatal(err)
1406 }
1407
1408 const goFile = `package rename
1409
1410 func justHereForTestingDiff() {
1411 justHereForTestingDiff()
1412 }
1413 `
1414 if err := os.WriteFile(filepath.Join(pkgDir, "rename_test.go"), []byte(goFile), 0644); err != nil {
1415 t.Fatal(err)
1416 }
1417
1418 if err := Main(&buildCtx, "", `"example.com/rename".justHereForTestingDiff`, "Foo"); err != nil {
1419 t.Fatal(err)
1420 }
1421
1422 // NB: there are tabs in the string literal!
1423 if !strings.Contains(stdout.(fmt.Stringer).String(), `
1424 -func justHereForTestingDiff() {
1425 - justHereForTestingDiff()
1426 +func Foo() {
1427 + Foo()
1428 }
1429 `) {
1430 t.Errorf("unexpected diff:\n<<%s>>", stdout)
1431 }
1432 }
1433
1434 // ---------------------------------------------------------------------
1435
1436 // Simplifying wrapper around buildutil.FakeContext for packages whose
1437 // filenames are sequentially numbered (%d.go). pkgs maps a package
1438 // import path to its list of file contents.
1439 func fakeContext(pkgs map[string][]string) *build.Context {
1440 pkgs2 := make(map[string]map[string]string)
1441 for path, files := range pkgs {
1442 filemap := make(map[string]string)
1443 for i, contents := range files {
1444 filemap[fmt.Sprintf("%d.go", i)] = contents
1445 }
1446 pkgs2[path] = filemap
1447 }
1448 return buildutil.FakeContext(pkgs2)
1449 }
1450
1451 // helper for single-file main packages with no imports.
1452 func main(content string) *build.Context {
1453 return fakeContext(map[string][]string{"main": {content}})
1454 }