aboutsummaryrefslogtreecommitdiffstats
path: root/skate/cmd/skate-conv/main.go
blob: 647472ef30ae2b3dd167fc3d13b0e4ae279427c6 (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
// skate-conv converts various schemas into releases. This should replace the
// very specific skate-ref-to-release and the like.
//
// $ skate-conv -f ref < FILE > FILE
//
// Currently source schemas: "ref", "ol", "rg"
package main

import (
	"flag"
	"log"
	"os"
	"runtime"
	"strings"

	"git.archive.org/martin/cgraph/skate"
	"git.archive.org/martin/cgraph/skate/parallel"
	json "github.com/segmentio/encoding/json"
)

var (
	numWorkers = flag.Int("w", runtime.NumCPU(), "number of workers")
	batchSize  = flag.Int("b", 100000, "batch size")
	fromFormat = flag.String("f", "ref", "import schema")

	bytesNewline = []byte("\n")
	f            func([]byte) ([]byte, error)
)

func main() {
	flag.Parse()
	switch *fromFormat {
	case "ref":
		f = refToRelease
	case "rg":
		f = rgSitemapToRelease
	case "ol":
		f = openLibraryToRelease
	}
	pp := parallel.NewProcessor(os.Stdin, os.Stdout, f)
	pp.NumWorkers = *numWorkers
	pp.BatchSize = *batchSize
	if err := pp.Run(); err != nil {
		log.Fatal(err)
	}
}

// refToRelease converts a ref document to a release.
func refToRelease(p []byte) ([]byte, error) {
	var ref skate.Ref
	if err := json.Unmarshal(p, &ref); err != nil {
		return nil, err
	}
	release, err := skate.RefToRelease(&ref)
	if err != nil {
		return nil, err
	}
	release.Extra.Skate.Status = "ref" // means: converted from ref
	release.Extra.Skate.Ref.Index = ref.Index
	release.Extra.Skate.Ref.Key = ref.Key
	b, err := json.Marshal(release)
	b = append(b, bytesNewline...)
	return b, err
}

func rgSitemapToRelease(p []byte) ([]byte, error) {
	var (
		s       skate.Sitemap
		release skate.Release
	)
	if err := json.Unmarshal(p, &s); err != nil {
		return nil, err
	}
	release.Title = s.Title
	if len(s.URL) > 41 {
		// XXX: A pseudo ident, maybe irritating.
		release.Ident = strings.Split(s.URL[41:], "_")[0]
	}
	release.Extra.Skate.Status = "rg"
	release.Extra.Skate.ResearchGate.URL = s.URL
	b, err := json.Marshal(release)
	b = append(b, bytesNewline...)
	return b, err
}

func openLibraryToRelease(p []byte) ([]byte, error) {
	var w skate.OpenLibraryWork
	if err := json.Unmarshal(p, &w); err != nil {
		return nil, err
	}
	release, err := skate.OpenLibraryToRelease(&w)
	if err != nil {
		return nil, err
	}
	release.Extra.Skate.Status = "ol"
	b, err := json.Marshal(release)
	b = append(b, bytesNewline...)
	return b, err
}