aboutsummaryrefslogtreecommitdiffstats
path: root/skate/cmd/skate-cdx-lookup/main.go
blob: 1bfbdb8e31cd5601c09db3b72ad61c2783872646 (plain)
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
package main

import (
	"bufio"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path"
	"strings"
	"time"

	"git.archive.org/martin/cgraph/skate"
	"github.com/adrg/xdg"
)

var (
	sleep      = flag.Duration("s", 200*time.Millisecond, "sleep between requests")
	cacheDir   = flag.String("c", path.Join(xdg.CacheHome, "skate-cdx"), "cache dir")
	bestEffort = flag.Bool("B", false, "best effort")
	writeJson  = flag.Bool("j", false, "json output")
	quiet      = flag.Bool("q", false, "no logging")
)

func main() {
	flag.Parse()
	var r io.Reader = os.Stdin
	if flag.NArg() > 0 {
		f, err := os.Open(flag.Arg(0))
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		r = f
	}
	if *quiet {
		log.SetOutput(ioutil.Discard)
	}
	var (
		cache = skate.Cache{Dir: *cacheDir}
		br    = bufio.NewReader(r)
		i     int
	)
	for {
		line, err := br.ReadString('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		line = strings.TrimSpace(line)
		if !cache.Has(line) {
			_, b, err := skate.LookupCDX(line)
			if err != nil {
				if *bestEffort {
					log.Println(err)
					continue
				} else {
					log.Fatal(err)
				}
			}
			if err := cache.Set(line, b); err != nil {
				log.Fatal(err)
			}
			time.Sleep(*sleep)
		}
		b, err := cache.Get(line)
		if err != nil {
			log.Fatal(err)
		}
		rows, err := skate.ParseCDX(b)
		if err != nil {
			if *bestEffort {
				log.Println(err)
				continue
			} else {
				log.Fatal(err)
			}
		}
		if *writeJson {
			cdxSummary := rows.Summary()
			var dummy = struct {
				Summary *skate.CDXSummary `json:"summary"`
				NumRows int               `json:"numRows"`
				Line    string            `json:"line"`
			}{
				Summary: cdxSummary,
				NumRows: len(rows),
				Line:    line,
			}
			b, err := json.Marshal(dummy)
			if err != nil {
				log.Fatal(err)
			}
			fmt.Println(string(b))
		} else {
			fmt.Printf("[%05d] % 10d %s %s\n", i, len(rows), rows.Summary(), line)
		}
		i++
	}
}