-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
314 lines (264 loc) · 6.61 KB
/
main.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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/urfave/cli"
)
// TODO:
// merge import; support appending;
var spiderImplTemplate = `package {{.PackageName}}
import (
"github.com/jiandahao/goscrapy"
)
// {{.Name}} spider
type {{.Name}} struct{}
// Name returns the spider name
func (s *{{.Name}}) Name() string {
return "{{.Name}}"
}
// StartRequests returns start requests. These request will be push into spider scheduler
// at initialized time
func (s *{{.Name}}) StartRequests() []*goscrapy.Request {
return nil
}
// URLMatcher returns the url matcher
func (s *{{.Name}}) URLMatcher() goscrapy.URLMatcher {
return goscrapy.NewStaticStringMatcher("https://www.example.com")
}
// Parse parse response
func (s *{{.Name}}) Parse(ctx *goscrapy.Context) (*goscrapy.Items, []*goscrapy.Request, error) {
return nil, nil, nil
}
`
var projImplTemplate = `package main
import (
"os"
"os/signal"
"syscall"
"github.com/jiandahao/goscrapy"
"github.com/jiandahao/goutils/logger"
)
func main() {
eng := goscrapy.New(
goscrapy.SetConcurrency(1),
goscrapy.UseLogger(logger.NewDefaultLogger("debug")),
goscrapy.MaxCrawlingDepth(3),
)
eng.RegisterSipders(/*add your own spiders here*/)
eng.RegisterPipelines(/*add your own pipelines here*/)
go eng.Start()
defer eng.Stop()
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
}
`
// SpiderConfig spider config
type SpiderConfig struct {
Name string
PackageName string
}
func main() {
app := cli.NewApp()
app.Name = "goscrapy-cli"
app.Usage = "Tools for auto-generating your own goscrapy project"
app.Version = "v1.0.0"
app.UsageText = "goscrapy-cli [command] [command options] [arguments...]"
app.Commands = []cli.Command{
CreateCommand(),
}
if err := app.Run(os.Args); err != nil {
fmt.Println(err)
}
}
// CreateCommand returns command using to create project / spider code
func CreateCommand() cli.Command {
return cli.Command{
Name: "create",
Usage: "create goscrapy project / spiders",
Subcommands: []cli.Command{
CreateProjectCommand(),
CreateSpiderCommand(),
CreatePipelineCommand(),
},
}
}
// CreateProjectCommand returns command using to create goscrapy project
func CreateProjectCommand() cli.Command {
return cli.Command{
Name: "project",
Usage: "create your goscrapy project",
Flags: []cli.Flag{
cli.StringFlag{
Name: "n",
Usage: "specified your project name",
},
cli.StringFlag{
Name: "o",
Usage: "specified output directory to store new generated project",
},
},
Action: func(ctx *cli.Context) error {
projName := ctx.String("n")
output := ctx.String("o")
if !strings.HasSuffix(output, ".go") {
output = fmt.Sprintf("%s/%s/main.go", strings.TrimSuffix(output, "/"), projName)
}
fmt.Printf("creating project [%s] at %s ", projName, output)
fd, err := openFile(output)
if err != nil {
return err
}
defer fd.Close()
if _, err := fd.WriteString(projImplTemplate); err != nil {
return err
}
return nil
},
}
}
// CreateSpiderCommand returns command using to generate spider
func CreateSpiderCommand() cli.Command {
return cli.Command{
Name: "spider",
Usage: "create your goscrapy spider",
Flags: []cli.Flag{
cli.StringFlag{
Name: "o",
Usage: "specified output path",
Value: "./",
},
cli.StringFlag{
Name: "n",
Usage: "specified spider name",
Value: "DefaultSpider",
},
cli.StringFlag{
Name: "pkg",
Usage: "package name",
Value: "main",
},
},
Action: func(ctx *cli.Context) error {
output := ctx.String("o")
spiderName := strings.Title(ctx.String("n"))
pkgName := ctx.String("pkg")
if !strings.HasSuffix(output, ".go") {
output = fmt.Sprintf("%s/%s.go", strings.TrimSuffix(output, "/"), strings.ToLower(spiderName))
}
fmt.Printf("creating spider [%s:%s] at %s", pkgName, spiderName, output)
fd, err := openFile(output)
if err != nil {
return err
}
defer fd.Close()
tmpl, err := template.New("spider").Parse(spiderImplTemplate)
if err != nil {
return err
}
return tmpl.Execute(fd, &SpiderConfig{
Name: spiderName,
PackageName: pkgName,
})
},
}
}
var pipelineTempl = `package {{.Package}}
import (
"github.com/jiandahao/goscrapy"
)
// {{.Name}} a simple pipeline
type {{.Name}} struct{}
// Name returns pipeline's name, it's the identity of pipeline, make sure every
// pipeline has it's own unique name
func (p *{{.Name}}) Name() string {
return "simple_pipeline"
}
// ItemList declares all items that this pipeline cares about.
func (p *{{.Name}}) ItemList() []string {
return []string{ {{.ItemList}} }
}
// Handle handle items
func (p *{{.Name}}) Handle(item *goscrapy.Items) error {
if item == nil {
return nil
}
return nil
}
`
// PipelineConfig pipeline config
type PipelineConfig struct {
Name string
Package string
ItemList string
}
// CreatePipelineCommand create pipeline command
func CreatePipelineCommand() cli.Command {
return cli.Command{
Name: "pipeline",
Usage: "create you own pipeline to handle structure data from spiders",
Flags: []cli.Flag{
cli.StringFlag{
Name: "o",
Usage: "specified output path",
Value: "./",
},
cli.StringFlag{
Name: "n",
Usage: "specified pipeline name",
Value: "DefaultPipeline",
},
cli.StringFlag{
Name: "pkg",
Usage: "package name",
Value: "main",
},
cli.StringSliceFlag{
Name: "item",
Usage: "specified all items this pipeline cares about",
},
},
Action: func(ctx *cli.Context) error {
output := ctx.String("o")
name := strings.Title(ctx.String("n"))
pkgName := ctx.String("pkg")
itemList := ctx.StringSlice("item")
if !strings.HasSuffix(output, ".go") {
output = fmt.Sprintf("%s/%s.go", strings.TrimSuffix(output, "/"), strings.ToLower(name))
}
fmt.Printf("creating pipeline [%s:%s] at %s", pkgName, name, output)
fd, err := openFile(output)
if err != nil {
return err
}
defer fd.Close()
tmpl, err := template.New("pipeline").Parse(pipelineTempl)
if err != nil {
return err
}
return tmpl.Execute(fd, &PipelineConfig{
Name: name,
Package: pkgName,
ItemList: "\"" + strings.Join(itemList, "\", \"") + "\"",
})
},
}
}
func openFile(filePath string) (*os.File, error) {
dir := filepath.Dir(filePath)
_, err := os.Stat(dir)
if os.IsNotExist(err) {
err = os.MkdirAll(dir, os.ModePerm)
if err != nil {
return nil, err
}
}
fd, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
if err != nil {
return nil, err
}
return fd, nil
}