/
pipe.go
104 lines (84 loc) · 2.05 KB
/
pipe.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
95
96
97
98
99
100
101
102
103
104
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package regenerate regenerates some generated code.
package regenerate
import (
"bytes"
"fmt"
"io"
"regexp"
"golang.org/x/tools/imports"
)
func Pipe(in io.Reader, out file, opts ...Option) error {
var cfg Configuration
for _, opt := range opts {
opt(&cfg)
}
b, err := io.ReadAll(in)
if err != nil {
return fmt.Errorf("io util read all: %w", err)
}
for _, replace := range cfg.strings {
b = bytes.ReplaceAll(b, []byte(replace.Match), []byte(replace.Replacement))
}
for _, replace := range cfg.regexps {
b = replace.Match.ReplaceAll(b, []byte(replace.Replacement))
}
err = out.Truncate(0)
if err != nil {
return fmt.Errorf("io file truncate: %w", err)
}
if cfg.gofmt != nil {
b, err = imports.Process("", b, cfg.gofmt)
if err != nil {
return fmt.Errorf("imports process: %w", err)
}
}
_, err = out.WriteAt(b, 0)
if err != nil {
return fmt.Errorf("os file write at 0: %w", err)
}
return nil
}
type file interface {
io.WriterAt
Truncate(size int64) error
}
type String struct {
Match string
Replacement string
}
type Regexp struct {
Match *regexp.Regexp
Replacement string
}
// Option changes configuration.
type Option func(*Configuration)
// Configuration holds values changeable by options.
type Configuration struct {
strings []String
regexps []Regexp
gofmt *imports.Options
}
// ReplaceString add replacement.
func ReplaceString(match string, replacement string) Option {
return func(c *Configuration) {
c.strings = append(c.strings, String{
Match: match,
Replacement: replacement,
})
}
}
// ReplaceRegexp add replacement.
func ReplaceRegexp(match *regexp.Regexp, replacement string) Option {
return func(c *Configuration) {
c.regexps = append(c.regexps, Regexp{
Match: match,
Replacement: replacement,
})
}
}
func WithGofmt(opts *imports.Options) Option {
return func(c *Configuration) { c.gofmt = opts }
}