-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
206 lines (180 loc) · 4.42 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
package main
import (
"regexp"
"bufio"
"encoding/json"
"flag"
"fmt"
suger "github.com/colinhb/suger/libsuger"
"io/ioutil"
"log"
"os"
"os/signal"
"time"
"strings"
)
func signalHandler(ch chan os.Signal) {
for sig := range ch {
log.Println("Caught signal:", sig)
os.Exit(0)
}
}
// Heredoc is a helper to do multi-line strings
func Heredoc(doc string) string {
// split into lines
lines := strings.Split(doc, "\n")
// trim first and last lines
if len(lines) < 3 {
return ""
}
lines = lines[1:len(lines)-1]
// reduce for min tab indent
var min string // accumulator
re := regexp.MustCompile(`^(\t*)\S+`) // submatch is 0+ tabs at start of line
for i := 0; i < len(lines); i++ {
tabs := re.FindStringSubmatch(lines[0])[1] // e.g. "\t\t\t"
if i == 0 { // init accumulator
min = tabs
continue
}
if len(tabs) < len(min) { // len() is ok - all runes are "\t"
min = tabs
}
}
// map in-place for unindent
for i, s := range lines {
lines[i] = strings.Replace(s, min, "", 1) // 1 replaces only left most occurance
}
// join lines and return
return strings.Join(lines, "\n")
}
func main() {
// handle ^C
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go signalHandler(ch)
usage := Heredoc(`
Usage of suger:
suger crawl [flags]
crawl classification database
suger scrape [flags]
scrape downloaded html files
(Use the -h flag for help with each subcommand.)
`)
// if no subcommand, give usage information
if len(os.Args) == 1 {
fmt.Println(usage)
return
}
// common flag vars
var htmlDir string
// crawl flag vars
var start int
var count int
var workers int
// scrape flag vars
var out string
// crawl flagset
crawlFlags := flag.NewFlagSet("crawl", flag.ExitOnError)
crawlFlags.IntVar(&start, "start", 1, "start at this result")
crawlFlags.IntVar(&count, "count", 25, "crawl this many results")
crawlFlags.StringVar(&htmlDir, "html", "html", "directory to write HTML files")
crawlFlags.IntVar(&workers, "workers", 1, "number of workers")
// scrape flagset
scrapeFlags := flag.NewFlagSet("scrape", flag.ExitOnError)
scrapeFlags.StringVar(&htmlDir, "html", "html", "directory to read HTML files")
scrapeFlags.StringVar(&out, "out", "out", "directory for output")
// switch on subcommand
switch os.Args[1] {
case "crawl":
crawlFlags.Parse(os.Args[2:])
crawlCmd(start, count, htmlDir, workers)
case "scrape":
scrapeFlags.Parse(os.Args[2:])
scrapeCmd(htmlDir, out)
default:
fmt.Printf("Error: %q is not valid subcommand.\n", os.Args[1])
fmt.Println(usage)
}
}
// crawlCmd() is called by the switch in main()
func crawlCmd(start int, count int, htmlDir string, workers int) {
// make channels
jobs := make(chan suger.Job, workers)
results := make(chan suger.Result, workers)
done := make(chan bool, workers)
j, err := suger.NewJob(start, count)
if err != nil {
log.Fatal(err)
}
parts, err := j.Partition(workers)
log.Println("Parts:", parts)
for i := 0; i < len(parts); i++ {
jobs <- parts[i]
}
remaining := len(parts)
for {
select {
case j := <-jobs:
log.Println("Received Job:", j)
if j.Error != nil {
log.Println(j.Error)
log.Printf("Sleeping for 30 seconds because of error.\n")
time.Sleep(time.Second * 30)
}
if j.IsDone() {
done <- true
} else {
c, _ := suger.NewCrawler()
go c.Crawl(j, results, jobs)
}
case r := <-results:
file := fmt.Sprintf("%v/title-%v-%v.html", htmlDir, r.Page, r.Row)
err = ioutil.WriteFile(file, r.HTML, 0644)
if err != nil {
log.Fatal(err)
}
case <-done:
remaining = remaining - 1
log.Printf("One worker finished; %v workers remaining.", remaining)
if remaining == 0 {
os.Exit(0)
}
}
}
}
func scrapeCmd(htmlDir string, out string) {
var titles []*suger.Title
files, err := ioutil.ReadDir(htmlDir)
for _, fileInfo := range files {
path := fmt.Sprintf("%s/%s", htmlDir, fileInfo.Name())
html, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
title, err := suger.NewTitleFromHTML(html)
if err != nil {
log.Fatal(err)
}
titles = append(titles, title)
}
//
// JSON
//
fileName := fmt.Sprintf("%s/%s", out, "out.json")
f, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer f.Close()
w := bufio.NewWriter(f)
json, err := json.MarshalIndent(titles, "", " ")
_, err = w.Write(json)
if err != nil {
log.Fatal(err)
}
err = w.Flush()
if err != nil {
log.Fatal(err)
}
}