1// Copyright 2022 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 5package main 6 7import ( 8 "cmd/go/internal/base" 9 "os" 10 "strings" 11 "testing" 12) 13 14func TestChdir(t *testing.T) { 15 // We want -C to apply to every go subcommand. 16 // Test that every command either has a -C flag registered 17 // or has CustomFlags set. In the latter case, the command 18 // must be explicitly tested in TestScript/chdir. 19 script, err := os.ReadFile("testdata/script/chdir.txt") 20 if err != nil { 21 t.Fatal(err) 22 } 23 24 var walk func(string, *base.Command) 25 walk = func(name string, cmd *base.Command) { 26 if len(cmd.Commands) > 0 { 27 for _, sub := range cmd.Commands { 28 walk(name+" "+sub.Name(), sub) 29 } 30 return 31 } 32 if !cmd.Runnable() { 33 return 34 } 35 if cmd.CustomFlags { 36 if !strings.Contains(string(script), "# "+name+"\n") { 37 t.Errorf("%s has custom flags, not tested in testdata/script/chdir.txt", name) 38 } 39 return 40 } 41 f := cmd.Flag.Lookup("C") 42 if f == nil { 43 t.Errorf("%s has no -C flag", name) 44 } else if f.Usage != "AddChdirFlag" { 45 t.Errorf("%s has -C flag but not from AddChdirFlag", name) 46 } 47 } 48 walk("go", base.Go) 49} 50