-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (57 loc) · 1.36 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
package main
import (
"bufio"
"fmt"
"github.com/saintfish/chardet"
"golang.org/x/text/encoding/ianaindex"
"io"
"io/ioutil"
"os"
"strings"
)
func checknil(err error) {
if err != nil {
panic(err)
}
}
func main() {
var filename string
var encoding string
detector := chardet.NewTextDetector()
fmt.Println("Mojibake v0.1 - UTF-8 file encoding converter")
fmt.Printf("Input file : ")
reader := bufio.NewReader(os.Stdin)
filename, _ = reader.ReadString('\n')
filename = strings.TrimSpace(filename)
dat, err := ioutil.ReadFile(filename)
checknil(err)
result, err := detector.DetectBest(dat)
checknil(err)
fmt.Printf("Input encoding (%s) : ", result.Charset)
encoding, _ = reader.ReadString('\n')
encoding = strings.TrimSpace(encoding)
if len(encoding) == 0 {
encoding = result.Charset
}
enc, err := ianaindex.IANA.Encoding(encoding)
checknil(err)
name, err := ianaindex.IANA.Name(enc)
checknil(err)
fmt.Printf("Selected encoding : %s\n", name)
f, err := os.Open(filename)
checknil(err)
outputname := "utf8." + filename
defer func() {
if r := recover(); r != nil {
fmt.Printf("Failure to convert file %s\n", filename)
os.Remove(outputname)
}
}()
r := enc.NewDecoder().Reader(f)
out, err := os.Create(outputname)
checknil(err)
io.Copy(out, r)
out.Close()
f.Close()
fmt.Printf("File successfully written to : %s\n", outputname)
}