Skip to content
This repository was archived by the owner on Jan 31, 2024. It is now read-only.

Commit 059a5b1

Browse files
committed
x/text: update for go modules support. Updates #24661
1 parent 342b2e1 commit 059a5b1

File tree

7 files changed

+95
-101
lines changed

7 files changed

+95
-101
lines changed

cmd/gotext/common.go

Lines changed: 0 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,6 @@ package main
66

77
import (
88
"fmt"
9-
"go/build"
10-
"go/parser"
11-
12-
"golang.org/x/tools/go/loader"
13-
)
14-
15-
const (
16-
extractFile = "extracted.gotext.json"
17-
outFile = "out.gotext.json"
18-
gotextSuffix = ".gotext.json"
199
)
2010

2111
// NOTE: The command line tool already prefixes with "gotext:".
@@ -28,22 +18,3 @@ var (
2818
}
2919
errorf = fmt.Errorf
3020
)
31-
32-
// TODO: still used. Remove when possible.
33-
func loadPackages(conf *loader.Config, args []string) (*loader.Program, error) {
34-
if len(args) == 0 {
35-
args = []string{"."}
36-
}
37-
38-
conf.Build = &build.Default
39-
conf.ParserMode = parser.ParseComments
40-
41-
// Use the initial packages from the command line.
42-
args, err := conf.FromArgs(args, false)
43-
if err != nil {
44-
return nil, wrap(err, "loading packages failed")
45-
}
46-
47-
// Load, parse and type-check the whole program.
48-
return conf.Load()
49-
}

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module golang.org/x/text
22

3-
require golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e
3+
require golang.org/x/tools v0.0.0-20190807223507-b346f7fd45de

go.sum

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,10 @@
1+
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
2+
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
3+
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
4+
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
5+
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
16
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e h1:FDhOuMEY4JVRztM/gsbk+IKUQ8kj74bxZrgw87eMMVc=
27
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
8+
golang.org/x/tools v0.0.0-20190807223507-b346f7fd45de h1:VNumCimp/Bwk6fRqgPHkjiUPZ/vzlpi23/kQTuQ4gBA=
9+
golang.org/x/tools v0.0.0-20190807223507-b346f7fd45de/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
10+
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

message/pipeline/extract.go

Lines changed: 52 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,8 @@ import (
2121
fmtparser "golang.org/x/text/internal/format"
2222
"golang.org/x/tools/go/callgraph"
2323
"golang.org/x/tools/go/callgraph/cha"
24-
"golang.org/x/tools/go/loader"
24+
"golang.org/x/tools/go/packages"
2525
"golang.org/x/tools/go/ssa"
26-
"golang.org/x/tools/go/ssa/ssautil"
2726
)
2827

2928
const debug = false
@@ -49,8 +48,7 @@ func Extract(c *Config) (*State, error) {
4948
x.extractMessages()
5049

5150
return &State{
52-
Config: *c,
53-
program: x.iprog,
51+
Config: *c,
5452
Extracted: Messages{
5553
Language: c.SourceLanguage,
5654
Messages: x.messages,
@@ -59,8 +57,8 @@ func Extract(c *Config) (*State, error) {
5957
}
6058

6159
type extracter struct {
62-
conf loader.Config
63-
iprog *loader.Program
60+
conf packages.Config
61+
pkgs []*packages.Package
6462
prog *ssa.Program
6563
callGraph *callgraph.Graph
6664

@@ -72,17 +70,20 @@ type extracter struct {
7270

7371
func newExtracter(c *Config) (x *extracter, err error) {
7472
x = &extracter{
75-
conf: loader.Config{},
73+
conf: packages.Config{
74+
Fset: token.NewFileSet(),
75+
},
7676
globals: map[token.Pos]*constData{},
7777
funcs: map[token.Pos]*callData{},
7878
}
7979

80-
x.iprog, err = loadPackages(&x.conf, c.Packages)
80+
prog, pkgs, err := loadPackages(&x.conf, c.Packages)
8181
if err != nil {
8282
return nil, wrap(err, "")
8383
}
84+
x.prog = prog
85+
x.pkgs = pkgs
8486

85-
x.prog = ssautil.CreateProgram(x.iprog, ssa.GlobalDebug|ssa.BareInits)
8687
x.prog.Build()
8788

8889
x.callGraph = cha.CallGraph(x.prog)
@@ -100,26 +101,46 @@ func (x *extracter) globalData(pos token.Pos) *constData {
100101
}
101102

102103
func (x *extracter) seedEndpoints() error {
103-
pkgInfo := x.iprog.Package("golang.org/x/text/message")
104-
if pkgInfo == nil {
105-
return errors.New("pipeline: golang.org/x/text/message is not imported")
104+
var pkg *packages.Package
105+
imports := ""
106+
for _, p := range x.pkgs {
107+
for k := range p.Imports {
108+
imports = imports + k + "\n"
109+
}
110+
if p2, ok := p.Imports["golang.org/x/text/message"]; ok {
111+
pkg = p2
112+
break
113+
}
114+
}
115+
if pkg == nil {
116+
return errors.New("pipeline: golang.org/x/text/message is not imported.\n" + imports)
117+
}
118+
119+
var typ *types.Pointer
120+
for _, typeAndVal := range pkg.TypesInfo.Types {
121+
if typeAndVal.Type.String() == "golang.org/x/text/message.Printer" {
122+
typ = types.NewPointer(typeAndVal.Type)
123+
break
124+
}
125+
}
126+
127+
if typ == nil {
128+
return errors.New("pipeline: golang.org/x/text/message.Printer was not found")
106129
}
107-
pkg := x.prog.Package(pkgInfo.Pkg)
108-
typ := types.NewPointer(pkg.Type("Printer").Type())
109130

110131
x.processGlobalVars()
111132

112-
x.handleFunc(x.prog.LookupMethod(typ, pkg.Pkg, "Printf"), &callData{
133+
x.handleFunc(x.prog.LookupMethod(typ, pkg.Types, "Printf"), &callData{
113134
formatPos: 1,
114135
argPos: 2,
115136
isMethod: true,
116137
})
117-
x.handleFunc(x.prog.LookupMethod(typ, pkg.Pkg, "Sprintf"), &callData{
138+
x.handleFunc(x.prog.LookupMethod(typ, pkg.Types, "Sprintf"), &callData{
118139
formatPos: 1,
119140
argPos: 2,
120141
isMethod: true,
121142
})
122-
x.handleFunc(x.prog.LookupMethod(typ, pkg.Pkg, "Fprintf"), &callData{
143+
x.handleFunc(x.prog.LookupMethod(typ, pkg.Types, "Fprintf"), &callData{
123144
formatPos: 2,
124145
argPos: 3,
125146
isMethod: true,
@@ -488,14 +509,14 @@ func (x *extracter) visitArgs(fd *callData, v ssa.Value) {
488509
// print returns Go syntax for the specified node.
489510
func (x *extracter) print(n ast.Node) string {
490511
var buf bytes.Buffer
491-
format.Node(&buf, x.conf.Fset, n)
512+
_ = format.Node(&buf, x.conf.Fset, n)
492513
return buf.String()
493514
}
494515

495516
type packageExtracter struct {
496517
f *ast.File
497518
x *extracter
498-
info *loader.PackageInfo
519+
pkg *packages.Package
499520
cmap ast.CommentMap
500521
}
501522

@@ -508,14 +529,13 @@ func (px packageExtracter) getComment(n ast.Node) string {
508529
}
509530

510531
func (x *extracter) extractMessages() {
511-
prog := x.iprog
512532
files := []packageExtracter{}
513-
for _, info := range x.iprog.AllPackages {
514-
for _, f := range info.Files {
533+
for _, pkg := range x.pkgs {
534+
for _, f := range pkg.Syntax {
515535
// Associate comments with nodes.
516536
px := packageExtracter{
517-
f, x, info,
518-
ast.NewCommentMap(prog.Fset, f, f.Comments),
537+
f, x, pkg,
538+
ast.NewCommentMap(pkg.Fset, f, f.Comments),
519539
}
520540
files = append(files, px)
521541
}
@@ -609,13 +629,13 @@ func (px packageExtracter) handleCall(call *ast.CallExpr) bool {
609629
func (px packageExtracter) getArguments(data *callData) []argument {
610630
arguments := []argument{}
611631
x := px.x
612-
info := px.info
632+
pkg := px.pkg
613633
if data.callArgsStart() >= 0 {
614634
args := data.expr.Args[data.callArgsStart():]
615635
for i, arg := range args {
616636
expr := x.print(arg)
617637
val := ""
618-
if v := info.Types[arg].Value; v != nil {
638+
if v := pkg.TypesInfo.Types[arg].Value; v != nil {
619639
val = v.ExactString()
620640
switch arg.(type) {
621641
case *ast.BinaryExpr, *ast.UnaryExpr:
@@ -624,12 +644,12 @@ func (px packageExtracter) getArguments(data *callData) []argument {
624644
}
625645
arguments = append(arguments, argument{
626646
ArgNum: i + 1,
627-
Type: info.Types[arg].Type.String(),
628-
UnderlyingType: info.Types[arg].Type.Underlying().String(),
647+
Type: pkg.TypesInfo.Types[arg].Type.String(),
648+
UnderlyingType: pkg.TypesInfo.Types[arg].Type.Underlying().String(),
629649
Expr: expr,
630650
Value: val,
631651
Comment: px.getComment(arg),
632-
Position: posString(&x.conf, info.Pkg, arg.Pos()),
652+
Position: posString(&x.conf, pkg.Types, arg.Pos()),
633653
// TODO report whether it implements
634654
// interfaces plural.Interface,
635655
// gender.Interface.
@@ -675,7 +695,7 @@ func (px packageExtracter) addMessage(
675695
case fmtparser.StatusBadArgNum, fmtparser.StatusMissingArg:
676696
arg = &argument{
677697
ArgNum: p.ArgNum,
678-
Position: posString(&x.conf, px.info.Pkg, pos),
698+
Position: posString(&x.conf, px.pkg.Types, pos),
679699
}
680700
name, arg.UnderlyingType = verbToPlaceholder(p.Text(), p.ArgNum)
681701
}
@@ -704,11 +724,11 @@ func (px packageExtracter) addMessage(
704724
// TODO(fix): this doesn't get the before comment.
705725
Comment: comment,
706726
Placeholders: ph.slice,
707-
Position: posString(&x.conf, px.info.Pkg, pos),
727+
Position: posString(&x.conf, px.pkg.Types, pos),
708728
})
709729
}
710730

711-
func posString(conf *loader.Config, pkg *types.Package, pos token.Pos) string {
731+
func posString(conf *packages.Config, pkg *types.Package, pos token.Pos) string {
712732
p := conf.Fset.Position(pos)
713733
file := fmt.Sprintf("%s:%d:%d", filepath.Base(p.Filename), p.Line, p.Column)
714734
return filepath.Join(pkg.Path(), file)

message/pipeline/generate.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import (
2020
"golang.org/x/text/internal/catmsg"
2121
"golang.org/x/text/internal/gen"
2222
"golang.org/x/text/language"
23-
"golang.org/x/tools/go/loader"
23+
"golang.org/x/tools/go/packages"
2424
)
2525

2626
var transRe = regexp.MustCompile(`messages\.(.*)\.json`)
@@ -34,26 +34,24 @@ func (s *State) Generate() error {
3434
path = "."
3535
}
3636
isDir := path[0] == '.'
37-
prog, err := loadPackages(&loader.Config{}, []string{path})
37+
_, pkgs, err := loadPackages(&packages.Config{}, []string{path})
3838
if err != nil {
3939
return wrap(err, "could not load package")
4040
}
41-
pkgs := prog.InitialPackages()
4241
if len(pkgs) != 1 {
4342
return errorf("more than one package selected: %v", pkgs)
4443
}
45-
pkg := pkgs[0].Pkg.Name()
4644

4745
cw, err := s.generate()
4846
if err != nil {
4947
return err
5048
}
5149
if !isDir {
5250
gopath := build.Default.GOPATH
53-
path = filepath.Join(gopath, filepath.FromSlash(pkgs[0].Pkg.Path()))
51+
path = filepath.Join(gopath, filepath.FromSlash(pkgs[0].PkgPath))
5452
}
5553
path = filepath.Join(path, s.Config.GenFile)
56-
cw.WriteGoFile(path, pkg) // TODO: WriteGoFile should return error.
54+
cw.WriteGoFile(path, pkgs[0].Name) // TODO: WriteGoFile should return error.
5755
return err
5856
}
5957

message/pipeline/pipeline.go

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@ import (
1111
"bytes"
1212
"encoding/json"
1313
"fmt"
14-
"go/build"
15-
"go/parser"
1614
"io/ioutil"
1715
"log"
1816
"os"
@@ -25,7 +23,9 @@ import (
2523
"golang.org/x/text/internal"
2624
"golang.org/x/text/language"
2725
"golang.org/x/text/runes"
28-
"golang.org/x/tools/go/loader"
26+
"golang.org/x/tools/go/packages"
27+
"golang.org/x/tools/go/ssa"
28+
"golang.org/x/tools/go/ssa/ssautil"
2929
)
3030

3131
const (
@@ -125,7 +125,6 @@ type State struct {
125125
Config Config
126126

127127
Package string
128-
program *loader.Program
129128

130129
Extracted Messages `json:"messages"`
131130

@@ -403,20 +402,19 @@ func warnf(format string, args ...interface{}) {
403402
log.Printf(format, args...)
404403
}
405404

406-
func loadPackages(conf *loader.Config, args []string) (*loader.Program, error) {
405+
func loadPackages(conf *packages.Config, args []string) (*ssa.Program, []*packages.Package, error) {
407406
if len(args) == 0 {
408407
args = []string{"."}
409408
}
410409

411-
conf.Build = &build.Default
412-
conf.ParserMode = parser.ParseComments
413-
414-
// Use the initial packages from the command line.
415-
args, err := conf.FromArgs(args, false)
410+
conf.Mode = packages.LoadAllSyntax
411+
pkgs, err := packages.Load(conf, args...)
416412
if err != nil {
417-
return nil, wrap(err, "loading packages failed")
413+
packages.PrintErrors(pkgs)
414+
return nil, nil, err
418415
}
419416

420-
// Load, parse and type-check the whole program.
421-
return conf.Load()
417+
prog, _ := ssautil.Packages(pkgs, 0)
418+
419+
return prog, pkgs, nil
422420
}

0 commit comments

Comments
 (0)