forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
271 lines (252 loc) · 5.31 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
// ex4.12 gets, indexes, and searches xkcd comic metadata.
package main
import (
"bufio"
"encoding/gob"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
type WordIndex map[string]map[int]bool
type NumIndex map[int]Comic
type Comic struct {
Num int
Year, Month, Day string
Title string
Transcript string
Alt string
Img string // url
}
func getComic(n int) (Comic, error) {
var comic Comic
url := fmt.Sprintf("https://xkcd.com/%d/info.0.json", n)
fmt.Println(url)
resp, err := http.Get(url)
if err != nil {
return comic, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return comic, fmt.Errorf("can't get comic %d: %s", n, resp.Status)
}
if err = json.NewDecoder(resp.Body).Decode(&comic); err != nil {
return comic, err
}
return comic, nil
}
func getComics() (chan Comic, error) {
max, err := getComicCount()
if err != nil {
return nil, err
}
fmt.Println("max", max)
max = 20
nworkers := 5
comics := make(chan Comic, 5*nworkers)
comicNums := make(chan int, 1*nworkers)
done := make(chan int, 0)
for i := 0; i < nworkers; i++ {
go fetcher(comicNums, comics, done)
}
for i := 1; i <= max; i++ {
comicNums <- i
}
close(comicNums)
for i := 0; i < nworkers; i++ {
<-done
}
close(done)
close(comics)
return comics, nil
}
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
i := 0
start := 0
stop := 0
for i < len(data) {
r, size := utf8.DecodeRune(data[i:])
i += size
if unicode.IsLetter(r) {
start = i - size
break
}
}
for i < len(data) {
r, size := utf8.DecodeRune(data[i:])
i += size
if !unicode.IsLetter(r) {
stop = i - size
break
}
}
if stop > start {
token = data[start:stop]
}
return i, token, nil
}
func indexComics(comics chan Comic) (WordIndex, NumIndex) {
wordIndex := make(WordIndex)
numIndex := make(NumIndex)
for comic := range comics {
numIndex[comic.Num] = comic
scanner := bufio.NewScanner(strings.NewReader(comic.Transcript))
scanner.Split(ScanWords)
for scanner.Scan() {
token := strings.ToLower(scanner.Text())
if _, ok := wordIndex[token]; !ok {
wordIndex[token] = make(map[int]bool, 1)
}
wordIndex[token][comic.Num] = true
}
}
return wordIndex, numIndex
}
func index(filename string) error {
comicChan, err := getComics()
if err != nil {
return err
}
wordIndex, numIndex := indexComics(comicChan)
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
enc := gob.NewEncoder(file)
fmt.Println(wordIndex)
err = enc.Encode(wordIndex)
if err != nil {
return err
}
err = enc.Encode(numIndex)
if err != nil {
return err
}
return nil
}
func readIndex(filename string) (WordIndex, NumIndex, error) {
file, err := os.Open(filename)
if err != nil {
return nil, nil, err
}
dec := gob.NewDecoder(file)
var wordIndex WordIndex
var numIndex NumIndex
err = dec.Decode(&wordIndex)
if err != nil {
return nil, nil, err
}
dec.Decode(&numIndex)
if err != nil {
return nil, nil, err
}
return wordIndex, numIndex, nil
}
func comicsContainingWords(words []string, wordIndex WordIndex, numIndex NumIndex) []Comic {
found := make(map[int]int) // comic Num -> count words found
comics := make([]Comic, 0)
for _, word := range words {
for num := range wordIndex[word] {
found[num]++
}
}
for num, nfound := range found {
if nfound == len(words) {
comics = append(comics, numIndex[num])
}
}
return comics
}
func search(query string, filename string) error {
wordIndex, numIndex, err := readIndex(filename)
if err != nil {
return err
}
comics := comicsContainingWords(strings.Fields(query), wordIndex, numIndex)
for _, comic := range comics {
fmt.Printf("%+v\n\n", comic)
}
return nil
}
func fetcher(comicNums chan int, comics chan Comic, done chan int) {
for n := range comicNums {
comic, err := getComic(n)
if err != nil {
log.Printf("Can't get comic %d: %s", n, err)
continue
}
comics <- comic
}
done <- 1
}
func getComicCount() (int, error) {
resp, err := http.Get("https://xkcd.com/info.0.json")
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("can't get main page: %s", resp.Status)
}
var comic Comic
if err = json.NewDecoder(resp.Body).Decode(&comic); err != nil {
return 0, err
}
return comic.Num, nil
}
const usage = `xkcd get N
xkcd index OUTPUT_FILE
xkcd search INDEX_FILE QUERY`
func usageDie() {
fmt.Println(usage)
os.Exit(1)
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, usage)
os.Exit(1)
}
cmd := os.Args[1]
switch cmd {
case "get":
if len(os.Args) != 3 {
usageDie()
}
n, err := strconv.Atoi(os.Args[2])
if err != nil {
fmt.Fprintf(os.Stderr, "N (%s) must be an int", os.Args[1])
usageDie()
}
comic, err := getComic(n)
if err != nil {
log.Fatal("Error getting comic", err)
}
fmt.Println(comic)
case "index":
if len(os.Args) != 3 {
usageDie()
}
err := index(os.Args[2])
if err != nil {
log.Fatal("Error serializing indexes", err)
}
case "search":
if len(os.Args) != 4 {
usageDie()
}
filename := os.Args[2]
query := os.Args[3]
err := search(query, filename)
if err != nil {
log.Fatal("Error searching index", err)
}
default:
usageDie()
}
}