forked from skelterjohn/gorf
/
pkg.go
140 lines (111 loc) · 2.52 KB
/
pkg.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// Copyright 2011 John Asmuth. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
//"go/ast"
"code.google.com/p/rog-go/exp/go/ast"
"path/filepath"
"code.google.com/p/rog-go/exp/go/types"
)
func PkgCmd(args []string) (err error) {
if len(args) != 2 {
return MakeErr("Usage: gorf [flags] pkg <path> <new name>")
}
path, newname := filepath.Clean(args[0]), args[1]
if !IsLegalIdentifier(newname) {
return MakeErr("New name %s is not a legal identifier", newname)
}
err = ScanAllForImports(LocalRoot)
if err != nil {
return
}
PreloadImportedBy(path)
defer func() {
if err != nil {
UndoCmd([]string{})
}
}()
if PackageTops[path] == nil {
return MakeErr("No local package found in %s", path)
}
pkg := LocalImporter(path)
oldname := pkg.Name
for fpath, file := range pkg.Files {
file.Name.Name = newname
err = RewriteSource(fpath, file)
if err != nil {
return
}
}
for _, ip := range ImportedBy[QuotePath(path)] {
ipkg := LocalImporter(ip)
if ipkg == nil {
return MakeErr("Problem getting package in %s", ip)
}
for fpath, file := range ipkg.Files {
uniqueName := GetUniqueIdent([]*ast.File{file}, newname)
if uniqueName != newname {
fmt.Printf("In %s: possible conflict with %s, using %s instead\n", fpath, newname, uniqueName)
}
pc := PkgChanger {
path:path,
oldname:oldname,
newname:uniqueName,
pkgname:newname,
}
ast.Walk(&pc, file)
if pc.Updated {
RewriteSource(fpath, file)
}
}
}
return
}
type PkgChanger struct {
path string
oldname, newname string
pkgname string
Renamed bool
Updated bool
}
func (this *PkgChanger) Visit(node ast.Node) ast.Visitor {
if this.Renamed {
return nil
}
if node == nil {
return this
}
switch n := node.(type) {
case *ast.ImportSpec:
if string(n.Path.Value) == QuotePath(this.path) {
if n.Name != nil {
this.Renamed = true
return nil
}
if n.Name == nil && this.newname != this.pkgname {
n.Name = &ast.Ident {
Name : this.newname,
NamePos : n.Pos(),
}
this.Updated = true
}
}
case *ast.Ident:
if n.Name == this.oldname {
obj, typ := types.ExprType(n, LocalImporter)
if obj == nil {
n.Name = this.newname
this.Updated = true
}
if obj != nil {
if typ.Kind == ast.Pkg && obj.Name == this.oldname {
n.Name = this.newname
this.Updated = true
}
}
}
}
return this
}