forked from scrapinghub/shubc
/
shubc.go
716 lines (629 loc) · 20.5 KB
/
shubc.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
package main
import (
"flag"
"fmt"
"github.com/scrapinghub/shubc/scrapinghub"
"log"
"os"
"os/user"
"path"
"path/filepath"
"regexp"
"strings"
"time"
)
var re_egg_pattern = regexp.MustCompile(`(.+?)-(\d+(?:\.\d)*)-?.*`)
type CmdFun func(conn *scrapinghub.Connection, args []string, flags *PFlags)
func dashes(n int) string {
s := ""
for i := 0; i < n; i++ {
s += "-"
}
return s
}
func print_out(flags *PFlags, format string, args ...interface{}) {
output := flags.Output
line := fmt.Sprintf(format, args...)
var out *os.File = os.Stdout
var err error
if output == "" {
fmt.Println(line)
return
}
out, err = os.OpenFile(output, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("Error writing output to file: %s\n", err)
} else {
fmt.Fprintln(out, line)
}
defer func() {
if err := out.Close(); err != nil {
panic(err)
}
}()
}
func find_apikey() string {
if os.Getenv("SH_APIKEY") != "" {
return os.Getenv("SH_APIKEY")
}
u, _ := user.Current()
scrapy_cfg := path.Join(u.HomeDir, "/.scrapy.cfg")
if st, err := os.Stat(scrapy_cfg); err == nil {
f, err := os.Open(scrapy_cfg)
if err != nil {
panic(err)
}
buf := make([]byte, st.Size())
n, err := f.Read(buf)
if err != nil {
panic(err)
}
s := string(buf[:n])
lines := strings.Split(s, "\n")
for _, l := range lines {
if strings.Index(l, "username") < 0 {
continue
}
result := strings.Split(l, "=")
return strings.TrimSpace(result[1])
}
}
return ""
}
// Returns a map given a list of ["key=value", ...] strings
func equality_list_to_map(data []string) map[string]string {
result := make(map[string]string)
for _, e := range data {
if strings.Index(e, "=") > 0 {
res := strings.Split(e, "=")
result[strings.TrimSpace(res[0])] = strings.TrimSpace(res[1])
}
}
return result
}
type PFlagsCSV struct {
IncludeHeaders bool
Fields string
}
type PFlags struct {
Count int
Offset int
Output string
AsJsonLines bool
AsCSV bool
CSVFlags PFlagsCSV
Tailing bool
Debug bool
}
/** Commands **/
func cmd_help() {
fmt.Println("shubc [options] <command> arg1 .. argN")
fmt.Println()
fmt.Println(" Options: ")
flag.PrintDefaults()
fmt.Println()
fmt.Println(" Commands: ")
fmt.Println(" Spiders API: ")
fmt.Println(" spiders <project_id> - list the spiders on project_id")
fmt.Println(" Jobs API: ")
fmt.Println(" schedule <project_id> <spider_name> [args] - schedule the spider <spider_name> with [args] in project <project_id>")
fmt.Println(" reschedule <job_id> - re-schedule the job `job_id` with the same arguments and tags")
fmt.Println(" jobs <project_id> [filters] - list the last 100 jobs on project_id")
fmt.Println(" jobinfo <job_id> - print information about the job with <job_id>")
fmt.Println(" update <job_id> [args] - update the job with <job_id> using the `args` given")
fmt.Println(" stop <job_id> - stop the job with <job_id>")
fmt.Println(" delete <job_id> - delete the job with <job_id>")
fmt.Println(" Items API: ")
fmt.Println(" items <job_id> - print to stdout the items for <job_id> (count & offset available)")
fmt.Println(" Logs API: ")
fmt.Println(" log <job_id> - print to stdout the log for the job `job_id` (count & offset available)")
fmt.Println(" Eggs API: ")
fmt.Println(" eggs-add <project_id> <path> [name=n version=v] - add the egg in `path` to the project `project_id`. By default it guess the name and version from `path`, but can be given using name=eggname and version=XXX.")
fmt.Println(" eggs-list <project_id> - list the eggs in `project_id`")
fmt.Println(" eggs-delete <project_id> <egg_name> - delete the egg `egg_name` in the project `project_id`")
fmt.Println(" Autoscraping API: ")
fmt.Println(" project-slybot <project_id> [spiders] - download the zip and write it to Stdout or o.zip if -o option is given")
fmt.Println(" Deploy API: ")
fmt.Println(" deploy <target> [project_id=<project_id>] [egg=<egg>] [version=<version>] - deploy `target` to Scrapinghub")
fmt.Println(" deploy-list-targets - list available targets to deploy")
fmt.Println(" build-egg - build egg but not deploy")
}
func cmd_spiders(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <project_id>\n")
}
project_id := args[0]
var spiders scrapinghub.Spiders
spider_list, err := spiders.List(conn, project_id)
if err != nil {
log.Fatalf("spiders error: %s\n", err)
} else {
print_out(flags, "| %30s | %10s | %20s |\n", "name", "type", "version")
print_out(flags, dashes(70))
for _, spider := range spider_list.Spiders {
print_out(flags, "| %30s | %10s | %20s |\n", spider["id"], spider["type"], spider["version"])
}
}
}
func cmd_jobs(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <project_id>\n")
}
project_id := args[0]
filters := equality_list_to_map(args[1:])
count := flags.Count
offset := flags.Offset
if flags.AsJsonLines {
ls := scrapinghub.LinesStream{Conn: conn, Count: count, Offset: offset}
ch_jobs, errch := ls.JobsAsJsonLines(project_id, filters)
for line := range ch_jobs {
fmt.Println(line)
}
for err := range errch {
log.Fatalf("jobs error: %s\n", err)
}
} else {
var jobs scrapinghub.Jobs
jobs_list, err := jobs.List(conn, project_id, count, filters)
if err != nil {
log.Fatalf("jobs error: %s", err)
}
outfmt := "| %10s | %25s | %12s | %10s | %10s | %10s | %20s |\n"
print_out(flags, outfmt, "id", "spider", "state", "items", "errors", "log lines", "started_time")
print_out(flags, dashes(106))
for _, j := range jobs_list.Jobs {
print_out(flags, "| %10s | %25s | %12s | %10d | %10d | %10d | %20s |\n", j.Id, j.Spider, j.State,
j.ItemsScraped, j.ErrorsCount, j.Logs, j.StartedTime)
}
}
}
func cmd_jobinfo(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <job_id>\n")
}
job_id := args[0]
var jobs scrapinghub.Jobs
jobinfo, err := jobs.JobInfo(conn, job_id)
if err != nil {
log.Fatalf("jobinfo error: %s\n", err)
} else {
outfmt := "| %-30s | %60s |\n"
print_out(flags, outfmt, "key", "value")
print_out(flags, dashes(97))
print_out(flags, outfmt, "id", jobinfo.Id)
print_out(flags, outfmt, "spider", jobinfo.Spider)
print_out(flags, outfmt, "spider_args", "")
for k, v := range jobinfo.SpiderArgs {
print_out(flags, outfmt, " ", fmt.Sprintf("%s = %s", k, v))
}
print_out(flags, outfmt, "spider_type", jobinfo.SpiderType)
print_out(flags, outfmt, "state", jobinfo.State)
print_out(flags, outfmt, "close_reason", jobinfo.CloseReason)
print_out(flags, dashes(97))
print_out(flags, outfmt, "responses_received", fmt.Sprintf("%d", jobinfo.ResponsesReceived))
print_out(flags, outfmt, "items_scraped", fmt.Sprintf("%d", jobinfo.ItemsScraped))
print_out(flags, outfmt, "errors_count", fmt.Sprintf("%d", jobinfo.ErrorsCount))
print_out(flags, outfmt, "logs", fmt.Sprintf("%d", jobinfo.Logs))
print_out(flags, dashes(97))
print_out(flags, outfmt, "started_time", jobinfo.StartedTime)
print_out(flags, outfmt, "updated_time", jobinfo.UpdatedTime)
print_out(flags, outfmt, "elapsed", fmt.Sprintf("%d", jobinfo.Elapsed))
print_out(flags, outfmt, "tags", " ")
for _, e := range jobinfo.Tags {
print_out(flags, outfmt, " ", e)
}
print_out(flags, outfmt, "priority", fmt.Sprintf("%d", jobinfo.Priority))
print_out(flags, outfmt, "version", jobinfo.Version)
print_out(flags, dashes(97))
}
}
func cmd_schedule(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 2 {
log.Fatalf("Missing arguments: <project_id> and <spider_name>\n")
}
var jobs scrapinghub.Jobs
project_id := args[0]
spider_name := args[1]
spider_args := equality_list_to_map(args[2:])
job_id, err := jobs.Schedule(conn, project_id, spider_name, spider_args)
if err != nil {
log.Fatalf("schedule error: %s\n", err)
} else {
fmt.Printf("Scheduled job: %s\n", job_id)
}
}
func cmd_jobs_stop(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <job_id>\n")
}
var jobs scrapinghub.Jobs
job_id := args[0]
err := jobs.Stop(conn, job_id)
if err != nil {
log.Fatalf("stop error: %s\n", err)
} else {
fmt.Printf("Stopped job: %s\n", job_id)
}
}
func cmd_jobs_update(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <job_id>\n")
}
var jobs scrapinghub.Jobs
job_id := args[0]
update_data := equality_list_to_map(args[1:])
err := jobs.Update(conn, job_id, update_data)
if err != nil {
log.Fatalf("update error: %s\n", err)
} else {
fmt.Printf("Updated job: %s\n", job_id)
}
}
func cmd_jobs_delete(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <job_id>\n")
}
var jobs scrapinghub.Jobs
job_id := args[0]
err := jobs.Delete(conn, job_id)
if err != nil {
log.Fatalf("delete error: %s\n", err)
} else {
fmt.Printf("Deleted job: %s\n", job_id)
}
}
func cmd_items(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <job_id>\n")
}
job_id := args[0]
count := flags.Count
offset := flags.Offset
ls := scrapinghub.LinesStream{Conn: conn, Count: count, Offset: offset}
if flags.AsJsonLines {
ch_lines, errch := ls.ItemsAsJsonLines(job_id)
for line := range ch_lines {
print_out(flags, line)
}
for err := range errch {
log.Fatalf("items error: %s\n", err)
}
} else if flags.AsCSV {
ch_lines, errch := ls.ItemsAsCSV(job_id, flags.CSVFlags.IncludeHeaders, flags.CSVFlags.Fields)
for line := range ch_lines {
print_out(flags, line)
}
for err := range errch {
log.Fatalf("items error: %s\n", err)
}
} else {
items, err := scrapinghub.RetrieveItems(conn, job_id, count, offset)
if err != nil {
log.Fatalf("items error: %s\n", err)
}
for i, e := range items {
print_out(flags, "Item %5d %s\n", i, dashes(129))
for k, v := range e {
//fmt.Printf("| %-33s | %100s |\n", k, fmt.Sprintf("%v", v))
print_out(flags, "| %-33s | %100s |\n", k, fmt.Sprintf("%v", v))
}
print_out(flags, dashes(140))
}
}
}
func cmd_as_project_slybot(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <project_id>\n")
}
project_id := args[0]
spiders := args[1:]
output := flags.Output
var out *os.File = os.Stdout
var err error
if output != "" {
out, err = os.Create(output)
if err != nil {
log.Fatalf("project slybot error: fail to write to file: %s\n", err)
}
}
defer func() {
if err := out.Close(); err != nil {
panic(err)
}
}()
err = scrapinghub.RetrieveSlybotProject(conn, project_id, spiders, out)
if err != nil {
log.Fatalf("project-slybot error: %s\n", err)
}
}
func cmd_log(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <job_id>\n")
}
job_id := args[0]
count := flags.Count
offset := flags.Offset
if flags.Tailing {
log_tailing(conn, job_id)
} else {
ls := scrapinghub.LinesStream{Conn: conn, Count: count, Offset: offset}
ch_lines, ch_err := ls.LogLines(job_id)
for line := range ch_lines {
print_out(flags, line)
}
for err := range ch_err {
log.Fatalf("log error: %s\n", err)
}
}
}
func log_tailing(conn *scrapinghub.Connection, job_id string) {
var jobs scrapinghub.Jobs
jobinfo, err := jobs.JobInfo(conn, job_id)
if err != nil {
log.Fatalf("%s\n", err)
}
// Number of log lines in the job
offset := jobinfo.Logs
if offset > 0 {
offset -= 1 // start one line before
}
count := 10 // ask for this lines in every call
ls := scrapinghub.LinesStream{Conn: conn, Count: count, Offset: offset}
for {
retrieved := 0
ch_lines, ch_err := ls.LogLines(job_id)
for line := range ch_lines {
retrieved++
fmt.Fprintf(os.Stdout, "%s\n", line)
}
for err := range ch_err {
log.Fatalf("%s\n", err)
}
ls.Offset += retrieved
time.Sleep(time.Second)
}
}
func cmd_reschedule(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <job_id>\n")
}
job_id := args[0]
var jobs scrapinghub.Jobs
new_job_id, err := jobs.Reschedule(conn, job_id)
if err != nil {
log.Fatalf("reschedule error: %s\n", err)
} else {
fmt.Printf("Re-scheduled job new id: %s\n", new_job_id)
}
}
func cmd_eggs_add(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 2 {
log.Fatalf("Missing arguments: <project_id> and <egg_path>\n")
}
project_id := args[0]
egg_path := args[1]
name_version := args[2:]
var egg_name string
var egg_ver string
if len(name_version) > 0 {
name_ver_map := equality_list_to_map(name_version)
egg_name = name_ver_map["name"]
egg_ver = name_ver_map["version"]
} else {
result := re_egg_pattern.FindStringSubmatch(filepath.Base(egg_path))
if len(result) <= 0 {
log.Fatalf("eggs-add error: Can't guess the name and version from egg path filename, provide it using name=<name> and version=<version> as parameters.\n")
}
egg_name = result[1]
egg_ver = result[2]
}
if egg_name == "" || egg_ver == "" {
log.Fatalf("Error: name and version are required\n")
}
var eggs scrapinghub.Eggs
eggdata, err := eggs.Add(conn, project_id, egg_name, egg_ver, egg_path)
if err != nil {
log.Fatalf("eggs-add error: %s\n", err)
}
fmt.Printf("Egg uploaded successfully! Project: %s, Egg name: %s, version: %s\n", project_id, eggdata.Name, eggdata.Version)
}
func cmd_eggs_list(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 1 {
log.Fatalf("Missing argument: <project_id>\n")
}
project_id := args[0]
var eggs scrapinghub.Eggs
egglist, err := eggs.List(conn, project_id)
if err != nil {
log.Fatalf("eggs-list error: %s\n", err)
}
fmt.Println(dashes(97))
outfmt := "| %-30s | %60s |\n"
fmt.Printf(outfmt, "Name", "Version")
fmt.Println(dashes(97))
for _, egg := range egglist {
fmt.Printf(outfmt, egg.Name, egg.Version)
}
fmt.Println(dashes(97))
}
func cmd_eggs_delete(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if len(args) < 2 {
log.Fatalf("Missing arguments: <project_id> and <egg_name>\n")
}
project_id := args[0]
egg_name := args[1]
var eggs scrapinghub.Eggs
err := eggs.Delete(conn, project_id, egg_name)
if err != nil {
log.Fatalf("eggs-delete error: %s\n", err)
}
fmt.Printf("Egg %s successfully deleted from project: %s\n", egg_name, project_id)
}
func cmd_deploy(conn *scrapinghub.Connection, args []string, flags *PFlags) {
var target_name, project_id, egg, version string
if len(args) > 0 {
if strings.Index(args[0], "=") < 0 {
target_name = args[0]
}
oargs := equality_list_to_map(args)
project_id = oargs["project_id"]
egg = oargs["egg"]
version = oargs["version"]
}
fmt.Println("Starting deploy ...")
if target_name == "" {
target_name = "default"
}
target, err := scrapinghub.Scrapy_cfg_target(target_name)
if err != nil {
log.Fatalf("deploy: error parsing scrapy.cfg, error desc: %s\n", err)
}
if project_id == "" {
project_id = target["project"]
}
if version == "" {
version = target["version"]
}
rver, err := scrapinghub.Scrapy_cfg_version(version)
if err != nil {
log.Fatalf("deploy: error parsing discovering version, error desc: %s\n", err)
}
fmt.Printf(" => target name: %s\n", target_name)
fmt.Printf(" => project id : %s\n", project_id)
fmt.Printf(" => version : %s\n", rver)
fmt.Println()
var tmpdir string = ""
if egg != "" {
fmt.Printf("Using egg: %s\n", egg)
} else {
fmt.Println("Building egg ...")
egg, tmpdir, err = scrapinghub.BuildEgg()
if err != nil {
log.Fatalf("deploy: error building egg, error desc: %s\n", err)
}
}
var deploy scrapinghub.DeployMessage
fmt.Println("Deploying to Scrapy Cloud ...")
_, err = deploy.UploadEgg(conn, target, project_id, rver, egg)
if err != nil {
log.Fatalf("deploy: error uploading egg, error desc: %s\n", err)
}
fmt.Println("\nSuccesfully deployed!")
if tmpdir != "" {
if !flags.Debug {
if err := os.RemoveAll(tmpdir); err != nil {
log.Fatalf("build-egg: can't remove tmpdir: %s", tmpdir)
}
} else {
fmt.Printf(" => Debug: logs and build directory: %s\n", tmpdir)
}
}
}
func cmd_deploy_list_targets(conn *scrapinghub.Connection, args []string, flags *PFlags) {
if !scrapinghub.Inside_scrapy_project() {
log.Fatal("list-targets: no Scrapy project found in this location")
}
for name, _ := range scrapinghub.Scrapy_cfg_targets() {
fmt.Println(name)
}
}
func cmd_deploy_build_egg(conn *scrapinghub.Connection, args []string, flags *PFlags) {
wdir, err := os.Getwd()
if err != nil {
log.Fatalf("build-egg: problem getting current working dir")
}
egg, tmpdir, err := scrapinghub.BuildEgg()
if err != nil {
log.Fatalf("build-egg: error building the egg: %s\n", err)
}
finalegg := filepath.Join(wdir, filepath.Base(egg))
if err := scrapinghub.CopyFile(egg, finalegg); err != nil {
log.Fatalf("build-egg: can't copy the egg from %s to %s. Error: \n", egg, finalegg, err)
}
fmt.Printf("Egg successfully build: %s\n", finalegg)
if !flags.Debug {
if err := os.RemoveAll(tmpdir); err != nil {
log.Fatalf("build-egg: can't remove tmpdir: %s", tmpdir)
}
} else {
fmt.Printf("Debug logs and build directory: %s\n", tmpdir)
}
}
func main() {
// Set loggin prefix & flags
log.SetPrefix("shubc: ")
log.SetFlags(0)
var gflags PFlags
var defaultApiUrl = "https://dash.scrapinghub.com/api"
apikey := flag.String("apikey", find_apikey(), "Scrapinghub api key")
apiurl := flag.String("apiurl", defaultApiUrl, "Scrapinghub API URL (can be changed to another uri for testing).")
count := flag.Int("count", 0, "Count for those commands that need a count limit")
offset := flag.Int("offset", 0, "Number of results to skip from the beginning")
output := flag.String("o", "", "Write output to a file instead of Stdout")
fjl := flag.Bool("jl", false, "If given, for command items and jobs will retrieve all the data writing to os.Stdout as JsonLines format")
fcsv := flag.Bool("csv", false, "If given, for command items, they will retrieve as CSV writing to os.Stdout")
fincheads := flag.Bool("include_headers", false, "When -csv given, include the headers of the CSV in the output")
fcsv_fields := flag.String("fields", "", "When -csv given, list of comma separated fields to include in the CSV")
tail := flag.Bool("tail", false, "The same that `tail -f` for command `log`")
debug := flag.Bool("debug", false, "debug mode for some commands (deploy: not remove debug dir)")
flag.Usage = cmd_help
flag.Parse()
// Set flags
gflags.Count = *count
gflags.Offset = *offset
gflags.Output = *output
gflags.AsJsonLines = *fjl
gflags.AsCSV = *fcsv
gflags.CSVFlags.IncludeHeaders = *fincheads
gflags.CSVFlags.Fields = *fcsv_fields
gflags.Tailing = *tail
gflags.Debug = *debug
commands := map[string]CmdFun{
"spiders": cmd_spiders,
"jobs": cmd_jobs,
"jobinfo": cmd_jobinfo,
"schedule": cmd_schedule,
"stop": cmd_jobs_stop,
"update": cmd_jobs_update,
"delete": cmd_jobs_delete,
"items": cmd_items,
"project-slybot": cmd_as_project_slybot,
"log": cmd_log,
"reschedule": cmd_reschedule,
"eggs-add": cmd_eggs_add,
"eggs-list": cmd_eggs_list,
"eggs-delete": cmd_eggs_delete,
"deploy": cmd_deploy,
"deploy-list-targets": cmd_deploy_list_targets,
"build-egg": cmd_deploy_build_egg,
}
if len(flag.Args()) <= 0 {
fmt.Fprintf(os.Stderr, "Usage: shubc [options] url\n")
} else {
// Create new connection
var conn scrapinghub.Connection
err := conn.New(*apikey)
if err != nil {
log.Fatalf("error creating scrapinghub.Connection: %s", err)
}
err = conn.SetAPIUrl(*apiurl)
if err != nil {
log.Fatalf("error setting api url: %s", err)
}
cmd := flag.Arg(0)
args := flag.Args()[1:]
if cmd == "help" {
cmd_help()
} else {
if cmd_func, ok := commands[cmd]; ok {
if *apikey == "" {
fmt.Println("No API Key given, neither through the option or in ~/.scrapy.cfg")
os.Exit(1)
}
cmd_func(&conn, args, &gflags)
} else {
log.Fatalf("'%s' command not found\n", cmd)
}
}
}
}