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