github.com/stackb/rules_proto@v0.0.0-20240221195024-5428336c51f1/cmd/gazelle/internal/wspace/finder_test.go (about) 1 /* 2 Copyright 2016 The Bazel Authors. All rights reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 package wspace 17 18 import ( 19 "io/ioutil" 20 "os" 21 "path/filepath" 22 "testing" 23 ) 24 25 func TestFind(t *testing.T) { 26 tmp, err := ioutil.TempDir(os.Getenv("TEST_TEMPDIR"), "") 27 if err != nil { 28 t.Fatal(err) 29 } 30 defer os.RemoveAll(tmp) 31 tmp, err = filepath.EvalSymlinks(tmp) // on macOS, TEST_TEMPDIR is a symlink 32 if err != nil { 33 t.Fatal(err) 34 } 35 if parent, err := FindRepoRoot(tmp); err == nil { 36 t.Skipf("WORKSPACE visible in parent %q of tmp %q", parent, tmp) 37 } 38 39 for _, tc := range []struct { 40 file, testdir string // file == "" ==> do not create file 41 shouldSucceed bool 42 }{ 43 {"", tmp, false}, 44 {filepath.Join(tmp, "WORKSPACE"), tmp, true}, 45 {filepath.Join(tmp, "WORKSPACE.bazel"), tmp, true}, 46 {filepath.Join(tmp, "WORKSPACE.bazel"), filepath.Join(tmp, "dir1"), true}, 47 // Test within a directory name WORKSPACE 48 {filepath.Join(tmp, "WORKSPACE"), filepath.Join(tmp, "dir1", "WORKSPACE", "dir2"), true}, 49 {filepath.Join(tmp, "WORKSPACE.bazel"), filepath.Join(tmp, "dir1", "WORKSPACE", "dir2"), true}, 50 // Test outside a workspace but within a directory named WORKSPACE 51 {filepath.Join(tmp, "WORKSPACE", "file.txt"), filepath.Join(tmp, "dir1"), false}, 52 {filepath.Join(tmp, "WORKSPACE", "file.txt"), filepath.Join(tmp, "WORKSPACE", "dir1"), false}, 53 } { 54 t.Run(tc.file, func(t *testing.T) { 55 if err := os.RemoveAll(tmp); err != nil { 56 t.Fatal(err) 57 } 58 59 if tc.file != "" { 60 // Create a WORKSPACE file 61 if err := os.MkdirAll(filepath.Dir(tc.file), 0o755); err != nil { 62 t.Fatal(err) 63 } 64 65 if err := ioutil.WriteFile(tc.file, nil, 0o755); err != nil { 66 t.Fatal(err) 67 } 68 } 69 70 // Create the testdir dir 71 if err := os.MkdirAll(tc.testdir, 0o755); err != nil { 72 t.Fatal(err) 73 } 74 75 // Look for the file 76 dir, err := FindRepoRoot(tc.testdir) 77 78 if !tc.shouldSucceed { 79 if err == nil { 80 t.Errorf("FindRoot(%q): got %v, wanted failure", tc.testdir, dir) 81 } 82 return 83 } 84 85 if err != nil { 86 t.Errorf("FindRoot(%q): got error %v, wanted %v", tc.testdir, err, tc.file) 87 } 88 89 file := FindWORKSPACEFile(dir) 90 if file != tc.file { 91 t.Errorf("FindWorkspaceFile(FindRoot(%q)): got %v, wanted %v", tc.testdir, file, tc.file) 92 } 93 }) 94 } 95 }