Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
209 lines (187 loc) · 5.79 KB
/
Copy pathmain.go
File metadata and controls
209 lines (187 loc) · 5.79 KB
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Command argtyper fills missing parameter types from the literal values passed
// into local method, constructor and function calls.
package main
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/rectorphp/argtyper/internal/aggregate"
"github.com/rectorphp/argtyper/internal/apply"
"github.com/rectorphp/argtyper/internal/collect"
"github.com/rectorphp/argtyper/internal/diff"
"github.com/rectorphp/argtyper/internal/finder"
"github.com/rectorphp/argtyper/internal/inherit"
"github.com/rectorphp/argtyper/internal/phpast"
"github.com/rectorphp/argtyper/internal/symbols"
)
const usage = `Usage: argtyper add-types [project-path] [--dry] [--literals] [--objects]
Find literal values passed into local method/function calls and add them as
parameter type declarations. Defaults to the current directory.
--dry Print the diff of the types that would be added, without writing.
--literals Only add string types with a @param 'a'|'b' literal docblock.
--objects Only add object types.
--literals and --objects can be combined.`
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, "Error: "+err.Error())
os.Exit(1)
}
}
func run(args []string) error {
if len(args) == 0 || args[0] != "add-types" {
fmt.Println(usage)
if len(args) == 0 {
return nil
}
return fmt.Errorf("unknown command %q", args[0])
}
dry := false
options := apply.Options{}
projectPath := ""
for _, arg := range args[1:] {
switch {
case arg == "--dry":
dry = true
case arg == "--literals":
options.Literals = true
case arg == "--objects":
options.Objects = true
case strings.HasPrefix(arg, "-"):
fmt.Println(usage)
return fmt.Errorf("unknown option %q", arg)
case projectPath != "":
fmt.Println(usage)
return fmt.Errorf("only one project path is allowed, got %q and %q", projectPath, arg)
default:
projectPath = arg
}
}
if projectPath == "" {
projectPath = "."
}
files, err := finder.PHPFiles(projectPath)
if err != nil {
return err
}
fmt.Printf("Code dirs found in %q: %v\n\n", projectPath, finder.CodeDirectories(projectPath))
// gather project symbols (enums, constants) so argument values that
// reference them resolve to a type just like literals do, and build the
// inheritance table from the project and its vendor directory, so a method
// that overrides an ancestor (including one in vendor) is left alone. Each
// project file is parsed once for both; per-file tables merge in file order.
type scanned struct {
symbols *symbols.Table
inheritance *inherit.Table
}
scans, err := progressMap("scanning", files, func(_ string, src []byte) (scanned, error) {
result := scanned{symbols.New(), inherit.New()}
if root, err := phpast.Parse(src); err == nil && root != nil {
result.symbols.Collect(root)
result.inheritance.Collect(root)
}
return result, nil
})
if err != nil {
return err
}
table := symbols.New()
inheritance := inherit.New()
for _, scan := range scans {
table.Merge(scan.symbols)
inheritance.Merge(scan.inheritance)
}
vendorFiles, err := finder.VendorPHPFiles(projectPath)
if err != nil {
return err
}
vendorInheritances, err := progressMap("parsing", vendorFiles, func(_ string, src []byte) (*inherit.Table, error) {
vendorInheritance := inherit.New()
vendorInheritance.CollectSource(src)
return vendorInheritance, nil
})
if err != nil {
return err
}
for _, vendorInheritance := range vendorInheritances {
inheritance.Merge(vendorInheritance)
}
// 1. collect literal argument types across the whole project
fmt.Println("1. Collecting argument types...")
fileRecords, err := progressMap("collecting", files, func(path string, src []byte) ([]collect.Record, error) {
records := collect.FromSource(src, table)
if relative, err := filepath.Rel(projectPath, path); err == nil && finder.IsTest(relative) {
for i := range records {
records[i].InTest = true
}
}
return records, nil
})
if err != nil {
return err
}
var records []collect.Record
for _, recordsOfFile := range fileRecords {
records = append(records, recordsOfFile...)
}
// a call on a child class counts for the parent method it inherits
for i, record := range records {
if !record.IsFunction && record.Class != "" {
records[i].Class = inheritance.DeclaringClass(record.Class, record.Name)
}
}
resolvedCount := 0
for _, record := range records {
if record.Type != "" {
resolvedCount++
}
}
fmt.Printf(" Found %d arg types\n\n", resolvedCount)
types := aggregate.Resolve(records)
// 2. add the resolved types to parameter declarations
if dry {
fmt.Println("2. Types that would be added (dry run)...")
} else {
fmt.Println("2. Adding types to parameters...")
}
type applied struct {
added []string
patch string
}
applies, err := progressMap("applying", files, func(file string, src []byte) (applied, error) {
output, added, changed := apply.Source(src, types, table, inheritance, options)
if !changed {
return applied{}, nil
}
if dry {
result := applied{added: added}
if patch, ok := diff.Lines(file, string(src), output); ok {
result.patch = patch
}
return result, nil
}
return applied{added: added}, os.WriteFile(file, []byte(output), 0o644)
})
if err != nil {
return err
}
var addedTypes []string
for _, result := range applies {
addedTypes = append(addedTypes, result.added...)
if result.patch != "" {
fmt.Print(colorizePatch(result.patch))
}
}
if len(addedTypes) == 0 {
fmt.Println(" No new types added. Is your code that good?")
return nil
}
printOverview(addedTypes)
if dry {
fmt.Printf("\n Dry run: %s types would be added\n", paint(ansiBold, strconv.Itoa(len(addedTypes))))
return nil
}
fmt.Printf("\n %s\n", paint(ansiBold+ansiGreen, fmt.Sprintf("Finished! Added %d new types", len(addedTypes))))
return nil
}