Debian Codegraph @

hugolib/gitinfo.go

raw
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 "bytes"
18 "fmt"
19 "io"
20 "os"
21 "path/filepath"
22 "strings"
23 "sync"
24
25 "github.com/bep/gitmap"
26 "github.com/gohugoio/hugo/cache/filecache"
27 "github.com/gohugoio/hugo/common/hashing"
28 "github.com/gohugoio/hugo/common/hexec"
29 "github.com/gohugoio/hugo/common/loggers"
30 "github.com/gohugoio/hugo/deps"
31 "github.com/gohugoio/hugo/modules"
32 "github.com/gohugoio/hugo/resources/page"
33 "github.com/gohugoio/hugo/source"
34 )
35
36 type gitInfo struct {
37 contentDir string
38 repo *gitmap.GitRepo
39
40 // Per-module git repos keyed by module dir.
41 moduleRepoLoaders map[string]func() (*gitmap.GitRepo, error)
42
43 logger loggers.Logger
44 }
45
46 func (g *gitInfo) forPage(p page.Page) *source.GitInfo {
47 if p.File() == nil {
48 return nil
49 }
50
51 mod := p.File().FileInfo().Meta().Module
52 if mod != nil && mod.IsGoMod() {
53 mm := mod.(modules.Module)
54 if loadRepo, ok := g.moduleRepoLoaders[mm.Dir()]; ok {
55 repo, err := loadRepo()
56 if err != nil {
57 g.logger.Warnf("Failed to load git repo for module %s: %v", mm.Path(), err)
58 return nil
59 }
60 return g.gitInfoFromModuleRepo(p, mm, repo)
61 }
62 }
63
64 // Fall back to local git info.
65 if g.repo == nil {
66 return nil
67 }
68 name := strings.TrimPrefix(filepath.ToSlash(p.File().Filename()), g.contentDir)
69 name = strings.TrimPrefix(name, "/")
70 gi, found := g.repo.Files[name]
71 if !found {
72 return nil
73 }
74 return gi
75 }
76
77 func (g *gitInfo) gitInfoFromModuleRepo(p page.Page, mod modules.Module, repo *gitmap.GitRepo) *source.GitInfo {
78 filename := filepath.ToSlash(p.File().Filename())
79 modDir := filepath.ToSlash(mod.Dir())
80 filePath := strings.TrimPrefix(filename, modDir)
81 filePath = strings.TrimPrefix(filePath, "/")
82
83 // If the module's go.mod lives in a subdirectory of the git repo,
84 // the blobless clone keys files by their path relative to the repo root,
85 // so we need to prepend the subdir.
86 if subdir := strings.Trim(mod.Origin().Subdir, "/"); subdir != "" {
87 filePath = subdir + "/" + filePath
88 }
89
90 gi, found := repo.Files[filePath]
91 if !found {
92 return nil
93 }
94 return gi
95 }
96
97 // isGitModule returns true if the module has a git VCS origin.
98 func isGitModule(m modules.Module) bool {
99 origin := m.Origin()
100 return origin.VCS == "git" && origin.URL != ""
101 }
102
103 type gitInfoConfig struct {
104 Deps *deps.Deps
105 Modules modules.Modules
106 GitInfoCache *filecache.Cache
107 Logger loggers.Logger
108 }
109
110 func newGitInfo(cfg gitInfoConfig) (*gitInfo, error) {
111 g := &gitInfo{
112 moduleRepoLoaders: make(map[string]func() (*gitmap.GitRepo, error)),
113 logger: cfg.Logger,
114 }
115
116 var hasGitModules bool
117 var projectIsGitModule bool
118
119 for _, mod := range cfg.Modules {
120 if !isGitModule(mod) {
121 continue
122 }
123 hasGitModules = true
124 if mod.Owner() == nil && !mod.Origin().IsZero() {
125 // TODO(bep) I'm not sure if this will ever be true. Needs some investigation,
126 // as I'm sure there will be cases where this could be useful.
127 projectIsGitModule = true
128 }
129 }
130
131 if hasGitModules {
132 if err := g.loadModuleRepos(cfg); err != nil {
133 return nil, err
134 }
135 }
136
137 if projectIsGitModule {
138 return g, nil
139 }
140
141 // Load local git repo info.
142 gitRepo, err := mapLocalRepo(cfg)
143 if err != nil {
144 if hasGitModules {
145 // We added GitInfo module support in Hugo v0.157.0 and need some real world experience,
146 // but for now, don't fail if the local repo is not a Git repo, but there are Git modules.
147 // I'm not sure we should even warn, but let's do that for now.
148 cfg.Logger.Warnf("Failed to read local Git log: %v", err)
149 return g, nil
150 }
151 return nil, err
152 }
153
154 g.contentDir = gitRepo.TopLevelAbsPath
155 g.repo = gitRepo
156
157 return g, nil
158 }
159
160 func (g *gitInfo) loadModuleRepos(cfg gitInfoConfig) error {
161 for _, mod := range cfg.Modules {
162 if !isGitModule(mod) {
163 continue
164 }
165
166 loadGitInfo := sync.OnceValues(func() (*gitmap.GitRepo, error) {
167 origin := mod.Origin()
168
169 cloneDir, err := ensureClone(cfg, origin)
170 if err != nil {
171 return nil, fmt.Errorf("failed to clone %s: %v", origin.URL, err)
172 }
173
174 repo, err := mapModuleRepo(cfg, cloneDir, origin.Hash)
175 if err != nil {
176 return nil, fmt.Errorf("failed to map git repo for module %s: %v", mod.Path(), err)
177 }
178 return repo, nil
179 })
180
181 g.moduleRepoLoaders[mod.Dir()] = loadGitInfo
182 }
183
184 return nil
185 }
186
187 // ensureClone ensures a blobless clone of the module's origin repo exists in the cache.
188 func ensureClone(cfg gitInfoConfig, origin modules.ModuleOrigin) (string, error) {
189 key := "repo_" + hashing.XxHashFromStringHexEncoded(origin.URL)
190 info, err := cfg.GitInfoCache.GetOrCreateInfo(key, func(id string) error {
191 cloneDir := cfg.GitInfoCache.AbsFilenameFromID(id)
192 if err := os.MkdirAll(cloneDir, 0o777); err != nil {
193 return err
194 }
195
196 var stderr bytes.Buffer
197 args := []any{
198 "clone",
199 "--filter=blob:none",
200 "--no-checkout",
201 origin.URL,
202 cloneDir,
203 hexec.WithStdout(io.Discard),
204 hexec.WithStderr(&stderr),
205 }
206
207 cfg.Logger.Infof("Cloning gitinfo for repo %s into cache", origin.URL)
208
209 cmd, err := cfg.Deps.ExecHelper.New("git", args...)
210 if err != nil {
211 return fmt.Errorf("git clone: %w", err)
212 }
213 if err := cmd.Run(); err != nil {
214 return fmt.Errorf("git clone %s: %w: %s", origin.URL, err, stderr.String())
215 }
216 return nil
217 })
218 if err != nil {
219 return "", err
220 }
221 return cfg.GitInfoCache.AbsFilenameFromID(info.Name), nil
222 }
223
224 func mapModuleRepo(cfg gitInfoConfig, repoDir, revision string) (*gitmap.GitRepo, error) {
225 opts := gitmap.Options{
226 Repository: repoDir,
227 Revision: revision,
228 GetGitCommandFunc: func(stdout, stderr io.Writer, args ...string) (gitmap.Runner, error) {
229 var argsv []any
230 for _, arg := range args {
231 argsv = append(argsv, arg)
232 }
233 argsv = append(
234 argsv,
235 hexec.WithStdout(stdout),
236 hexec.WithStderr(stderr),
237 )
238 return cfg.Deps.ExecHelper.New("git", argsv...)
239 },
240 }
241 return gitmap.Map(opts)
242 }
243
244 func mapLocalRepo(cfg gitInfoConfig) (*gitmap.GitRepo, error) {
245 opts := gitmap.Options{
246 Repository: cfg.Deps.Conf.BaseConfig().WorkingDir,
247 GetGitCommandFunc: func(stdout, stderr io.Writer, args ...string) (gitmap.Runner, error) {
248 var argsv []any
249 for _, arg := range args {
250 argsv = append(argsv, arg)
251 }
252 argsv = append(
253 argsv,
254 hexec.WithStdout(stdout),
255 hexec.WithStderr(stderr),
256 )
257 return cfg.Deps.ExecHelper.New("git", argsv...)
258 },
259 }
260 return gitmap.Map(opts)
261 }