@@ -13,10 +13,12 @@ import (
13
13
14
14
"golang.org/x/tools/go/analysis"
15
15
"golang.org/x/tools/gopls/internal/bug"
16
+ "golang.org/x/tools/gopls/internal/lsp/analysis/embeddirective"
16
17
"golang.org/x/tools/gopls/internal/lsp/analysis/fillstruct"
17
18
"golang.org/x/tools/gopls/internal/lsp/analysis/undeclaredname"
18
19
"golang.org/x/tools/gopls/internal/lsp/protocol"
19
20
"golang.org/x/tools/gopls/internal/span"
21
+ "golang.org/x/tools/internal/imports"
20
22
)
21
23
22
24
type (
@@ -41,6 +43,7 @@ const (
41
43
ExtractFunction = "extract_function"
42
44
ExtractMethod = "extract_method"
43
45
InvertIfCondition = "invert_if_condition"
46
+ AddEmbedImport = "add_embed_import"
44
47
)
45
48
46
49
// suggestedFixes maps a suggested fix command id to its handler.
@@ -52,6 +55,7 @@ var suggestedFixes = map[string]SuggestedFixFunc{
52
55
ExtractMethod : singleFile (extractMethod ),
53
56
InvertIfCondition : singleFile (invertIfCondition ),
54
57
StubMethods : stubSuggestedFixFunc ,
58
+ AddEmbedImport : addEmbedImport ,
55
59
}
56
60
57
61
// singleFile calls analyzers that expect inputs for a single file
@@ -138,3 +142,50 @@ func ApplyFix(ctx context.Context, fix string, snapshot Snapshot, fh FileHandle,
138
142
}
139
143
return edits , nil
140
144
}
145
+
146
+ // fixedByImportingEmbed returns true if diag can be fixed by addEmbedImport.
147
+ func fixedByImportingEmbed (diag * Diagnostic ) bool {
148
+ if diag == nil {
149
+ return false
150
+ }
151
+ return diag .Message == embeddirective .MissingImportMessage
152
+ }
153
+
154
+ // addEmbedImport adds a missing embed "embed" import with blank name.
155
+ func addEmbedImport (ctx context.Context , snapshot Snapshot , fh FileHandle , rng protocol.Range ) (* token.FileSet , * analysis.SuggestedFix , error ) {
156
+ pkg , pgf , err := NarrowestPackageForFile (ctx , snapshot , fh .URI ())
157
+ if err != nil {
158
+ return nil , nil , fmt .Errorf ("narrow pkg: %w" , err )
159
+ }
160
+
161
+ // Like source.AddImport, but with _ as Name and using our pgf.
162
+ protoEdits , err := ComputeOneImportFixEdits (snapshot , pgf , & imports.ImportFix {
163
+ StmtInfo : imports.ImportInfo {
164
+ ImportPath : "embed" ,
165
+ Name : "_" ,
166
+ },
167
+ FixType : imports .AddImport ,
168
+ })
169
+ if err != nil {
170
+ return nil , nil , fmt .Errorf ("compute edits: %w" , err )
171
+ }
172
+
173
+ var edits []analysis.TextEdit
174
+ for _ , e := range protoEdits {
175
+ start , end , err := pgf .RangePos (e .Range )
176
+ if err != nil {
177
+ return nil , nil , fmt .Errorf ("map range: %w" , err )
178
+ }
179
+ edits = append (edits , analysis.TextEdit {
180
+ Pos : start ,
181
+ End : end ,
182
+ NewText : []byte (e .NewText ),
183
+ })
184
+ }
185
+
186
+ fix := & analysis.SuggestedFix {
187
+ Message : "Add embed import" ,
188
+ TextEdits : edits ,
189
+ }
190
+ return pkg .FileSet (), fix , nil
191
+ }
0 commit comments