-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (79 loc) · 1.52 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
package main
import (
"errors"
"flag"
"io"
"log"
"os"
"github.com/boutros/marc"
)
func init() {
log.SetFlags(0)
log.SetPrefix("marc2marc: ")
}
func detectFormat(f *os.File) (marc.Format, error) {
sniff := make([]byte, 64)
_, err := f.Read(sniff)
if err != nil {
log.Fatal(err)
}
format := marc.DetectFormat(sniff)
// rewind reader
_, err = f.Seek(0, 0)
if err != nil {
log.Fatal(err)
}
switch format {
case marc.MARC, marc.LineMARC, marc.MARCXML:
return format, nil
default:
return format, errors.New("unknown MARC format")
}
}
func main() {
in := flag.String("i", "", "input file")
f := flag.String("f", "", "output format: (m)arc, (l)ine-marc, marc(x)ml")
flag.Parse()
if *in == "" || *f == "" {
flag.Usage()
os.Exit(1)
}
inF, err := os.Open(*in)
if err != nil {
log.Fatal(err)
}
defer inF.Close()
from, err := detectFormat(inF)
if err != nil {
log.Fatalf("%s: %v", inF.Name(), err)
}
var to marc.Format
switch *f {
case "m", "M":
to = marc.MARC
case "l", "L":
to = marc.LineMARC
case "x", "X":
to = marc.MARCXML
default:
log.Println("illegal option for flag -f")
flag.Usage()
os.Exit(1)
}
if from == to {
log.Println("nothing to do; input format same as output format")
os.Exit(1)
}
dec := marc.NewDecoder(inF, from)
enc := marc.NewEncoder(os.Stdout, to)
for rec, err := dec.Decode(); err != io.EOF; rec, err = dec.Decode() {
if err != nil {
log.Println(err)
continue
}
if err = enc.Encode(rec); err != nil {
log.Println(err)
}
}
enc.Flush()
}