knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/upgrade/shell/project.go (about) 1 /* 2 Copyright 2020 The Knative Authors 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 17 package shell 18 19 import ( 20 "errors" 21 "fmt" 22 "path" 23 "regexp" 24 "runtime" 25 ) 26 27 var ( 28 // ErrCantGetCaller is raised when we can't calculate a caller of NewProjectLocation. 29 ErrCantGetCaller = errors.New("can't get caller") 30 31 // ErrCallerNotAllowed is raised when user tries to use this shell-out package 32 // outside of allowed places. This package is deprecated from start and was 33 // introduced to allow rewriting of shell code to Golang in small chunks. 34 ErrCallerNotAllowed = errors.New("don't try use knative.dev/pkg/test/upgrade/shell package outside of allowed places") 35 ) 36 37 // NewProjectLocation creates a ProjectLocation that is used to calculate 38 // relative paths within the project. 39 func NewProjectLocation(pathToRoot string) (ProjectLocation, error) { 40 pc, filename, _, ok := runtime.Caller(1) 41 if !ok { 42 return nil, ErrCantGetCaller 43 } 44 funcName := runtime.FuncForPC(pc).Name() 45 err := isCallsiteAllowed(funcName) 46 if err != nil { 47 return nil, err 48 } 49 return &callerLocation{ 50 caller: filename, 51 pathToRoot: pathToRoot, 52 }, nil 53 } 54 55 // RootPath return a path to root of the project. 56 func (c *callerLocation) RootPath() string { 57 return path.Join(path.Dir(c.caller), c.pathToRoot) 58 } 59 60 // callerLocation holds a caller Go file, and a relative location to a project 61 // root directory. This information can be used to calculate relative paths and 62 // properly source shell scripts. 63 type callerLocation struct { 64 caller string 65 pathToRoot string 66 } 67 68 func isCallsiteAllowed(funcName string) error { 69 validPaths := []string{ 70 "knative.+/test/upgrade", 71 "knative(:?\\.dev/|-)pkg/test/upgrade/shell", 72 } 73 for _, validPath := range validPaths { 74 r := regexp.MustCompile(validPath) 75 if loc := r.FindStringIndex(funcName); loc != nil { 76 return nil 77 } 78 } 79 return fmt.Errorf("%w, tried using from: %s", 80 ErrCallerNotAllowed, funcName) 81 }