github.com/blend/go-sdk@v1.20220411.3/codeowners/parse_go_comments.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package codeowners 9 10 import ( 11 "bufio" 12 "bytes" 13 "go/parser" 14 "go/token" 15 "os" 16 "strings" 17 ) 18 19 // ParseGoComments parses a files comments. 20 func ParseGoComments(repoRoot, sourcePath, linePrefix string) (*Source, error) { 21 contents, err := os.ReadFile(sourcePath) 22 if err != nil { 23 return nil, err 24 } 25 fset := token.NewFileSet() 26 fileAst, err := parser.ParseFile(fset, sourcePath, contents, parser.ImportsOnly|parser.ParseComments) 27 if err != nil { 28 return nil, err 29 } 30 31 var owners []string 32 var corpus, line string 33 for _, commentGroup := range fileAst.Comments { 34 corpus = commentGroup.Text() 35 scanner := bufio.NewScanner(bytes.NewBufferString(corpus)) 36 // scan the corpus lines for `//github:codeowners prefixes` 37 for scanner.Scan() { 38 line = strings.TrimSpace(scanner.Text()) 39 if strings.HasPrefix(line, linePrefix) { 40 owners = append(owners, strings.Fields(strings.TrimPrefix(line, linePrefix))...) 41 } 42 } 43 } 44 45 if len(owners) == 0 { 46 return nil, nil 47 } 48 repoSourcePath, err := MakeRepositoryAbsolute(repoRoot, sourcePath) 49 if err != nil { 50 return nil, err 51 } 52 pathGlob, err := MakeRepositoryAbsolute(repoRoot, sourcePath) 53 if err != nil { 54 return nil, err 55 } 56 return &Source{ 57 Source: repoSourcePath, 58 Paths: []Path{ 59 { 60 PathGlob: pathGlob, 61 Owners: owners, 62 }, 63 }, 64 }, nil 65 }