github.com/bazelbuild/bazel-gazelle@v0.36.1-0.20240520142334-61b277ba6fed/language/go/modules.go (about) 1 /* Copyright 2018 The Bazel Authors. All rights reserved. 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 16 package golang 17 18 import ( 19 "bytes" 20 "fmt" 21 "os" 22 "path/filepath" 23 "strings" 24 25 "github.com/bazelbuild/bazel-gazelle/language" 26 ) 27 28 func importReposFromModules(args language.ImportReposArgs) language.ImportReposResult { 29 // run go list in the dir where go.mod is located 30 data, err := goListModules(filepath.Dir(args.Path)) 31 if err != nil { 32 return language.ImportReposResult{Error: processGoListError(err, data)} 33 } 34 35 pathToModule, err := extractModules(data) 36 if err != nil { 37 return language.ImportReposResult{Error: err} 38 } 39 40 // Load sums from go.sum. Ideally, they're all there. 41 goSumPath := filepath.Join(filepath.Dir(args.Path), "go.sum") 42 data, _ = os.ReadFile(goSumPath) 43 lines := bytes.Split(data, []byte("\n")) 44 for _, line := range lines { 45 line = bytes.TrimSpace(line) 46 fields := bytes.Fields(line) 47 if len(fields) != 3 { 48 continue 49 } 50 path, version, sum := string(fields[0]), string(fields[1]), string(fields[2]) 51 if strings.HasSuffix(version, "/go.mod") { 52 continue 53 } 54 if mod, ok := pathToModule[path+"@"+version]; ok { 55 mod.Sum = sum 56 } 57 } 58 59 pathToModule, err = fillMissingSums(pathToModule) 60 if err != nil { 61 return language.ImportReposResult{Error: fmt.Errorf("finding module sums: %v", err)} 62 } 63 64 return language.ImportReposResult{Gen: toRepositoryRules(pathToModule)} 65 }