go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/config_service/internal/common/gitiles.go (about) 1 // Copyright 2023 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package common 16 17 import ( 18 "net/url" 19 "strings" 20 21 "go.chromium.org/luci/common/api/gitiles" 22 "go.chromium.org/luci/common/errors" 23 cfgcommonpb "go.chromium.org/luci/common/proto/config" 24 ) 25 26 // ValidateGitilesLocation validate cfgcommonpb.GitilesLocation proto. 27 func ValidateGitilesLocation(loc *cfgcommonpb.GitilesLocation) error { 28 switch { 29 case loc == nil: 30 return errors.New("not specified") 31 case !strings.HasPrefix(loc.GetRef(), "refs/"): 32 return errors.New("ref must start with 'refs/'") 33 case strings.HasPrefix(loc.GetPath(), "/"): 34 return errors.New("path must not start with '/'") 35 default: 36 return errors.Annotate(validateGitilesRepo(loc.GetRepo()), "repo").Err() 37 } 38 } 39 40 func validateGitilesRepo(repo string) error { 41 if repo == "" { 42 return errors.New("not specified") 43 } 44 switch u, err := url.Parse(repo); { 45 case err != nil: 46 return errors.Annotate(err, "invalid repo url").Err() 47 case strings.HasPrefix(u.Path, "/a/"): 48 return errors.New("must not have '/a/' prefix of a path component") 49 case strings.HasSuffix(u.Path, ".git"): 50 return errors.New("must not end with '.git'") 51 case strings.HasSuffix(u.Path, "/"): 52 return errors.New("must not end with '/'") 53 default: 54 return gitiles.ValidateRepoURL(repo) 55 } 56 }