Debian Codegraph @

gopls/internal/golang/completion/newfile.go

raw symbols SCIP
1 // Copyright 2025 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package completion
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11
12 "golang.org/x/tools/gopls/internal/cache"
13 "golang.org/x/tools/gopls/internal/cache/parsego"
14 "golang.org/x/tools/gopls/internal/file"
15 "golang.org/x/tools/gopls/internal/golang"
16 "golang.org/x/tools/gopls/internal/protocol"
17 )
18
19 // NewFile returns a document change to complete an empty Go source file. Document change may be nil.
20 func NewFile(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) (*protocol.DocumentChange, error) {
21 if !snapshot.Options().NewGoFileHeader {
22 return nil, nil
23 }
24 content, err := fh.Content()
25 if err != nil {
26 return nil, err
27 }
28 if len(content) != 0 {
29 return nil, fmt.Errorf("file is not empty")
30 }
31 meta, err := snapshot.NarrowestMetadataForFile(ctx, fh.URI())
32 if err != nil {
33 return nil, err
34 }
35 var buf bytes.Buffer
36 // Copy the copyright header from the first existing file that has one.
37 for _, fileURI := range meta.GoFiles {
38 if fileURI == fh.URI() {
39 continue
40 }
41 fh, err := snapshot.ReadFile(ctx, fileURI)
42 if err != nil {
43 continue
44 }
45 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Header)
46 if err != nil {
47 continue
48 }
49 if group := golang.CopyrightComment(pgf.File); group != nil {
50 text, err := pgf.NodeText(group)
51 if err != nil {
52 continue
53 }
54 buf.Write(text)
55 buf.WriteString("\n\n")
56 break
57 }
58 }
59
60 pkgName, err := bestPackage(ctx, snapshot, fh.URI())
61 if err != nil {
62 return nil, err
63 }
64
65 fmt.Fprintf(&buf, "package %s\n", pkgName)
66 change := protocol.DocumentChangeEdit(fh, []protocol.TextEdit{{
67 Range: protocol.Range{}, // insert at start of file
68 NewText: buf.String(),
69 }})
70
71 return &change, nil
72 }