Debian Codegraph @

pkg/mod/mod.go

raw symbols SCIP
1 // Copyright (c) Bartłomiej Płotka @bwplotka
2 // Licensed under the Apache License 2.0.
3
4 package mod
5
6 import (
7 "io"
8 "os"
9
10 "github.com/efficientgo/core/errcapture"
11 "github.com/efficientgo/core/errors"
12 "golang.org/x/mod/modfile"
13 "golang.org/x/mod/module"
14 )
15
16 // File represents .mod file for Go Module use.
17 type File struct {
18 path string
19
20 f *os.File
21 m *modfile.File
22 }
23
24 // OpenFile opens mod file for edits in place.
25 // It's a caller responsibility to Close the file when not using anymore.
26 func OpenFile(modFile string) (_ *File, err error) {
27 f, err := os.OpenFile(modFile, os.O_RDWR, os.ModePerm)
28 if err != nil {
29 return nil, err
30 }
31 defer func() {
32 if err != nil {
33 errcapture.Do(&err, f.Close, "close")
34 }
35 }()
36
37 mf := &File{f: f, path: modFile}
38 return mf, mf.Reload()
39 }
40
41 // OpenFileForRead opens mod file for reads.
42 // It's a caller responsibility to Close the file when not using anymore.
43 func OpenFileForRead(modFile string) (_ FileForRead, err error) {
44 f, err := os.OpenFile(modFile, os.O_RDONLY, os.ModePerm)
45 if err != nil {
46 return nil, err
47 }
48 defer func() {
49 if err != nil {
50 errcapture.Do(&err, f.Close, "close")
51 }
52 }()
53
54 mf := &File{f: f, path: modFile}
55 return mf, mf.Reload()
56 }
57
58 type FileForRead interface {
59 Reload() error
60 Filepath() string
61
62 Module() (path string, comment string)
63 Comments() (comments []string)
64 GoVersion() string
65 RequireDirectives() []RequireDirective
66 ReplaceDirectives() []ReplaceDirective
67 ExcludeDirectives() []ExcludeDirective
68 RetractDirectives() []RetractDirective
69
70 Close() error
71 }
72
73 // Reload re-parses module file from the latest state on the disk.
74 func (mf *File) Reload() (err error) {
75 if _, err := mf.f.Seek(0, 0); err != nil {
76 return errors.Wrap(err, "seek")
77 }
78
79 mf.m, err = parseModFileOrReader(mf.path, mf.f)
80 return err
81 }
82
83 func (mf *File) Filepath() string {
84 return mf.path
85 }
86
87 // Close closes file.
88 // TODO(bwplotka): Ensure other methods will return error on use after Close.
89 func (mf *File) Close() error {
90 return mf.f.Close()
91 }
92
93 func (mf *File) Module() (path string, comment string) {
94 if mf.m.Module == nil {
95 return "", ""
96 }
97 if len(mf.m.Module.Syntax.Comment().Suffix) > 0 {
98 comment = mf.m.Module.Syntax.Comment().Suffix[0].Token[3:]
99 }
100 return mf.m.Module.Mod.Path, comment
101 }
102
103 func (mf *File) SetModule(path string, comment string) error {
104 if err := mf.m.AddModuleStmt(path); err != nil {
105 return err
106 }
107
108 mf.m.Module.Syntax.Suffix = append(mf.m.Module.Syntax.Suffix, modfile.Comment{Suffix: true, Token: "// " + comment})
109
110 return mf.flush()
111 }
112
113 func (mf *File) Comments() (comments []string) {
114 for _, e := range mf.m.Syntax.Stmt {
115 for _, c := range e.Comment().Before {
116 comments = append(comments, c.Token[3:])
117 }
118 }
119 return comments
120 }
121
122 func (mf *File) AddComment(comment string) error {
123 mf.m.AddComment("// " + comment)
124
125 return mf.flush()
126 }
127
128 // GoVersion returns a semver string containing the value of of the go directive.
129 // For example, it will return "1.2.3" if the go.mod file contains the line "go 1.2.3".
130 // If no go directive is found, it returns "1.0" because:
131 // 1. "1.0" is a valid semver string, so it's always safe to parse this value using semver.MustParse().
132 // 2. The semantics of the absence of a go directive in a go.mod file means all versions of Go should be able to compile it.
133 func (mf *File) GoVersion() string {
134 if mf.m.Go == nil {
135 return "1.0"
136 }
137 return mf.m.Go.Version
138 }
139
140 func (mf *File) SetGoVersion(version string) error {
141 if err := mf.m.AddGoStmt(version); err != nil {
142 return err
143 }
144
145 return mf.flush()
146 }
147
148 // Flush saves all changes made to parsed syntax and reloads the parsed file.
149 func (mf *File) flush() error {
150 mf.m.Cleanup()
151 newB := modfile.Format(mf.m.Syntax)
152 if err := mf.f.Truncate(0); err != nil {
153 return errors.Wrap(err, "truncate")
154 }
155 if _, err := mf.f.Seek(0, 0); err != nil {
156 return errors.Wrap(err, "seek")
157 }
158 if _, err := mf.f.Write(newB); err != nil {
159 return errors.Wrap(err, "write")
160 }
161 // Reload, so syntax gets rebuilt. It might change due to format.
162 return mf.Reload()
163 }
164
165 type RequireDirective struct {
166 Module module.Version
167 Indirect bool
168
169 // ExtraSuffixComment represents comment (without '// ') after potential indirect comment
170 // that can contain additional information.
171 ExtraSuffixComment string
172 }
173
174 func (mf *File) RequireDirectives() []RequireDirective {
175 ret := make([]RequireDirective, len(mf.m.Require))
176 for i, r := range mf.m.Require {
177 ret[i] = RequireDirective{
178 Module: r.Mod,
179 Indirect: r.Indirect,
180 }
181 if len(r.Syntax.Suffix) > 0 {
182 ret[i].ExtraSuffixComment = r.Syntax.Suffix[0].Token[3:]
183 if r.Indirect {
184 ret[i].ExtraSuffixComment = r.Syntax.Suffix[0].Token[11:]
185 }
186 }
187 }
188 return ret
189 }
190
191 // SetRequireDirectives removes all require statements and set to the given ones.
192 func (mf *File) SetRequireDirectives(directives ...RequireDirective) (err error) {
193 for _, r := range mf.m.Require {
194 _ = mf.m.DropRequire(r.Mod.Path)
195 }
196 mf.m.Require = mf.m.Require[:0]
197
198 for i, d := range directives {
199 mf.m.AddNewRequire(d.Module.Path, d.Module.Version, d.Indirect)
200
201 if len(d.ExtraSuffixComment) > 0 {
202 r := mf.m.Require[i]
203 // TODO(bwplotka): How it works with indirect on ?
204 r.Syntax.Suffix = append(r.Syntax.Suffix[:0], modfile.Comment{Suffix: true, Token: "// " + d.ExtraSuffixComment})
205 }
206 }
207 return mf.flush()
208 }
209
210 type ReplaceDirective struct {
211 Old module.Version
212 New module.Version
213 }
214
215 func (mf *File) ReplaceDirectives() []ReplaceDirective {
216 ret := make([]ReplaceDirective, len(mf.m.Replace))
217 for i, r := range mf.m.Replace {
218 ret[i] = ReplaceDirective{
219 Old: r.Old,
220 New: r.New,
221 }
222 }
223 return ret
224 }
225
226 // SetReplaceDirectives removes all replace statements and set to the given ones.
227 func (mf *File) SetReplaceDirectives(directives ...ReplaceDirective) (err error) {
228 for _, r := range mf.m.Replace {
229 _ = mf.m.DropReplace(r.Old.Path, r.Old.Version)
230 }
231 mf.m.Replace = mf.m.Replace[:0]
232
233 // TODO(bwplotka): Backup before malformation?
234 for _, d := range directives {
235 if err := mf.m.AddReplace(d.Old.Path, d.Old.Version, d.New.Path, d.New.Version); err != nil {
236 return err
237 }
238 }
239 return mf.flush()
240 }
241
242 type ExcludeDirective struct {
243 Module module.Version
244 }
245
246 func (mf *File) ExcludeDirectives() []ExcludeDirective {
247 ret := make([]ExcludeDirective, len(mf.m.Exclude))
248 for i, r := range mf.m.Exclude {
249 ret[i] = ExcludeDirective{
250 Module: r.Mod,
251 }
252 }
253 return ret
254 }
255
256 // SetExcludeDirectives removes all replace statements and set to the given ones.
257 func (mf *File) SetExcludeDirectives(directives ...ExcludeDirective) (err error) {
258 for _, r := range mf.m.Exclude {
259 _ = mf.m.DropExclude(r.Mod.Path, r.Mod.Version)
260 }
261 mf.m.Exclude = mf.m.Exclude[:0]
262
263 // TODO(bwplotka): Backup before malformation?
264 for _, d := range directives {
265 if err := mf.m.AddExclude(d.Module.Path, d.Module.Version); err != nil {
266 return err
267 }
268 }
269 return mf.flush()
270 }
271
272 type VersionInterval = modfile.VersionInterval
273
274 type RetractDirective struct {
275 VersionInterval
276 Rationale string
277 }
278
279 func (mf *File) RetractDirectives() []RetractDirective {
280 ret := make([]RetractDirective, len(mf.m.Retract))
281 for i, r := range mf.m.Retract {
282 ret[i] = RetractDirective{
283 VersionInterval: r.VersionInterval,
284 Rationale: r.Rationale,
285 }
286 }
287 return ret
288 }
289
290 // SetRetractDirectives removes all replace statements and set to the given ones.
291 func (mf *File) SetRetractDirectives(directives ...RetractDirective) (err error) {
292 for _, r := range mf.m.Retract {
293 _ = mf.m.DropRetract(r.VersionInterval)
294 }
295 mf.m.Retract = mf.m.Retract[:0]
296
297 for _, d := range directives {
298 if err := mf.m.AddRetract(d.VersionInterval, d.Rationale); err != nil {
299 return err
300 }
301 }
302 return mf.flush()
303 }
304
305 // parseModFileOrReader parses any module file or reader allowing to read it's content.
306 func parseModFileOrReader(modFile string, r io.Reader) (*modfile.File, error) {
307 b, err := readAllFileOrReader(modFile, r)
308 if err != nil {
309 return nil, errors.Wrap(err, "read")
310 }
311
312 m, err := modfile.Parse(modFile, b, nil)
313 if err != nil {
314 return nil, errors.Wrap(err, "parse")
315 }
316 return m, nil
317 }
318
319 func readAllFileOrReader(file string, r io.Reader) (b []byte, err error) {
320 if r != nil {
321 return io.ReadAll(r)
322 }
323 return os.ReadFile(file)
324 }