-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadwrite.go
66 lines (57 loc) · 1.28 KB
/
readwrite.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
package main
import (
"bufio"
"fmt"
"io"
"regexp"
"strings"
)
func prepareFileInjection(file io.Reader, inject fmt.Stringer) ([]string, error) {
// create a slice to hold the lines
lines := []string{}
// create a scanner to read the file
scanner := bufio.NewScanner(file)
beginRegexp := regexp.MustCompile(`GODOCMD BEGIN`)
endRegexp := regexp.MustCompile(`GODOCMD END`)
// loop through the lines
for scanner.Scan() {
// append the line to the slice
line := scanner.Text()
match := beginRegexp.MatchString(line)
lines = append(lines, line)
if match {
break
}
}
stringReader := strings.NewReader(inject.String())
injectScanner := bufio.NewScanner(stringReader)
for injectScanner.Scan() {
line := injectScanner.Text()
lines = append(lines, line)
}
for scanner.Scan() {
line := scanner.Text()
if !endRegexp.MatchString(line) {
continue
}
lines = append(lines, line)
}
// return the slice of lines
return lines, nil
}
func writeToFile(file io.Writer, lines []string) error {
// create a writer to write the file
writer := bufio.NewWriter(file)
for _, line := range lines {
_, err := writer.WriteString(line + "\n")
if err != nil {
return err
}
}
// flush the writer
err := writer.Flush()
if err != nil {
return err
}
return nil
}