codeowners.go (1658B)
1 // Copyright 2019 The Hugo 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 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hugolib
15
16 import (
17 "io"
18 "os"
19 "path"
20
21 "github.com/gohugoio/hugo/config"
22 "github.com/gohugoio/hugo/resources/page"
23 "github.com/hairyhenderson/go-codeowners"
24 "github.com/spf13/afero"
25 )
26
27 var afs = afero.NewOsFs()
28
29 func findCodeOwnersFile(dir string) (io.Reader, error) {
30 for _, p := range []string{".", "docs", ".github", ".gitlab"} {
31 f := path.Join(dir, p, "CODEOWNERS")
32
33 _, err := afs.Stat(f)
34 if err != nil {
35 if os.IsNotExist(err) {
36 continue
37 }
38 return nil, err
39 }
40
41 return afs.Open(f)
42 }
43
44 return nil, nil
45 }
46
47 type codeownerInfo struct {
48 owners *codeowners.Codeowners
49 }
50
51 func (c *codeownerInfo) forPage(p page.Page) []string {
52 return c.owners.Owners(p.File().Filename())
53 }
54
55 func newCodeOwners(cfg config.Provider) (*codeownerInfo, error) {
56 workingDir := cfg.GetString("workingDir")
57
58 r, err := findCodeOwnersFile(workingDir)
59 if err != nil || r == nil {
60 return nil, err
61 }
62
63 owners, err := codeowners.FromReader(r, workingDir)
64 if err != nil {
65 return nil, err
66 }
67
68 return &codeownerInfo{owners: owners}, nil
69 }