-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.go
84 lines (76 loc) · 2.21 KB
/
io.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
package main
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"os"
)
// file represents *os.File and is used wherever *os.File is used.
type file interface {
Read(b []byte) (int, error)
Write(b []byte) (int, error)
Seek(offset int64, whence int) (int64, error)
Truncate(size int64) error
Close() error
}
// osOpenFile is a type of os.OpenFile.
type osOpenFile func(name string, flag int, perm os.FileMode) (file, error)
// openFile is a wrapper around os.OpenFile.
var openFile osOpenFile = func(
name string, flag int, perm os.FileMode,
) (file, error) {
return os.OpenFile(name, flag, perm)
}
// config represents parsed CLI arguments.
type config struct {
version bool
write bool
paths []string
}
const usageText = "usage: gouse [-v] [-w] [file paths...]"
// parseArgs accepts args, parses them and returns config, parsing message and
// err. flag.ErrHelp is a special error which is returned on -h, -help, --help
// and when misused.
func parseArgs(args []string) (*config, string, error) {
c := new(config)
flags := flag.NewFlagSet("", flag.ContinueOnError)
var out bytes.Buffer
flags.SetOutput(&out)
flags.BoolVar(&c.version, "v", false, "show version")
flags.BoolVar(&c.write, "w", false, "write results to files")
flags.Usage = func() { out.Write([]byte(usageText)) }
if err := flags.Parse(args); err != nil {
return nil, out.String(), err
}
// flags.Args must be called after flags.Parse.
c.paths = flags.Args()
return c, out.String(), nil
}
// toggleFile takes code from in, toggles it, deletes contents of out if it’s
// in, and writes the toggled version to out.
func toggleFile(ctx context.Context, in, out file) error {
code, err := io.ReadAll(in)
if err != nil {
return fmt.Errorf("toggleFile: in io.ReadAll: %v", err)
}
toggled, err := toggle(ctx, code)
if err != nil {
return fmt.Errorf("toggleFile: %v", err)
}
if out == in {
if _, err := out.Seek(0, io.SeekStart); err != nil {
return fmt.Errorf("toggleFile: in *File.Seek: %v", err)
}
if err := out.Truncate(0); err != nil {
return fmt.Errorf(
"toggleFile: in *File.Truncate: %v", err,
)
}
}
if _, err := out.Write(toggled); err != nil {
return fmt.Errorf("toggleFile: in *File.Write: %v", err)
}
return nil
}