Skip to content

Commit 6ec27e1

Browse files
authored
Merge pull request #821 from devlights/add-utf8bom-example
2 parents 0d401d3 + 942dfd1 commit 6ec27e1

File tree

2 files changed

+125
-0
lines changed

2 files changed

+125
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# https://taskfile.dev
2+
3+
version: '3'
4+
5+
vars:
6+
TEST_FILE: test.txt
7+
8+
tasks:
9+
default:
10+
cmds:
11+
- task: run
12+
run:
13+
cmds:
14+
- echo helloworld > {{.TEST_FILE}}
15+
- defer: rm -f {{.TEST_FILE}}
16+
- nkf -g {{.TEST_FILE}}; hexdump {{.TEST_FILE}}
17+
- go run main.go {{.TEST_FILE}}
18+
- nkf -g {{.TEST_FILE}}; hexdump {{.TEST_FILE}}
19+
- go run main.go -d {{.TEST_FILE}}
20+
- nkf -g {{.TEST_FILE}}; hexdump {{.TEST_FILE}}
21+
clean:
22+
cmds:
23+
- rm -rf bin

examples/singleapp/utf8bom/main.go

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"flag"
6+
"log"
7+
"os"
8+
)
9+
10+
var (
11+
BOM = []byte{0xEF, 0xBB, 0xBF}
12+
)
13+
14+
var (
15+
files []string
16+
rmBOM bool
17+
)
18+
19+
func init() {
20+
log.SetFlags(0)
21+
22+
flag.BoolVar(&rmBOM, "d", false, "BOM removal mode")
23+
flag.Usage = func() {
24+
log.Println("Usage: bom (-d) file-path...")
25+
flag.PrintDefaults()
26+
}
27+
}
28+
29+
func main() {
30+
flag.Parse()
31+
32+
if flag.NArg() == 0 {
33+
flag.Usage()
34+
os.Exit(-1)
35+
}
36+
37+
files = make([]string, len(flag.Args()))
38+
copy(files, flag.Args())
39+
40+
if err := run(); err != nil {
41+
log.Fatal(err)
42+
}
43+
}
44+
45+
func run() error {
46+
for _, fpath := range files {
47+
if err := process(fpath); err != nil {
48+
return err
49+
}
50+
}
51+
52+
return nil
53+
}
54+
55+
func process(fpath string) error {
56+
fi, err := os.Stat(fpath)
57+
if err != nil {
58+
return err
59+
}
60+
61+
data, err := os.ReadFile(fpath)
62+
if err != nil {
63+
return err
64+
}
65+
66+
if bytes.HasPrefix(data, BOM) {
67+
if rmBOM {
68+
if err := os.WriteFile(fpath, data[len(BOM):], fi.Mode()); err != nil {
69+
return err
70+
}
71+
}
72+
73+
return nil
74+
}
75+
76+
if err := os.WriteFile(fpath, append(BOM, data...), fi.Mode()); err != nil {
77+
return err
78+
}
79+
80+
return nil
81+
82+
/*
83+
$ task
84+
task: [run] echo helloworld > test.txt
85+
task: [run] nkf -g test.txt; hexdump test.txt
86+
ASCII
87+
0000000 6568 6c6c 776f 726f 646c 000a
88+
000000b
89+
task: [run] go run main.go test.txt
90+
task: [run] nkf -g test.txt; hexdump test.txt
91+
UTF-8
92+
0000000 bbef 68bf 6c65 6f6c 6f77 6c72 0a64
93+
000000e
94+
task: [run] go run main.go -d test.txt
95+
task: [run] nkf -g test.txt; hexdump test.txt
96+
ASCII
97+
0000000 6568 6c6c 776f 726f 646c 000a
98+
000000b
99+
task: [run] rm -f test.txt
100+
*/
101+
102+
}

0 commit comments

Comments
 (0)