-
Notifications
You must be signed in to change notification settings - Fork 8
/
bash.go
137 lines (110 loc) · 2.37 KB
/
bash.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package main
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
)
type bashApplier struct {
}
func (g *bashApplier) CheckHeader(target *os.File, t *TagContext) (bool, error) {
// Check compiler flags.
sbFlag, sbBuf, err := g.checkSheBang(target)
if err != nil {
return false, err
}
target.Seek(0, 0)
tbuf, err := os.ReadFile(filepath.Join(t.templatePath, "bash.txt"))
if err != nil {
return false, err
}
var templateBuf string
if sbFlag {
templateBuf = fmt.Sprintf("%s%s%s", sbBuf, "\n\n", tbuf)
} else {
templateBuf = string(tbuf)
}
targetBuf := make([]byte, len(templateBuf))
n, err := target.Read(targetBuf)
if err != nil {
return false, err
}
if n == len(templateBuf) {
if strings.Compare(templateBuf, string(targetBuf)) == 0 {
return true, nil
}
}
return false, nil
}
func (g *bashApplier) ApplyHeader(path string, t *TagContext) error {
file, err := os.OpenFile(path, os.O_RDONLY, 0666)
if err != nil {
return err
}
defer file.Close()
t.templateFiles.goTemplateFile.Seek(0, 0)
headerExist, err := g.CheckHeader(file, t)
if err != nil {
return err
}
if headerExist {
return nil
}
// Reset the read pointers to begining of file.
t.templateFiles.goTemplateFile.Seek(0, 0)
file.Seek(0, 0)
sbFlag, sbBuf, err := g.checkSheBang(file)
if err != nil {
return err
}
file.Seek(0, 0)
tempFile := path + ".tmp"
tFile, err := os.OpenFile(tempFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return err
}
defer tFile.Close()
reader := bufio.NewReader(file)
if sbFlag {
tFile.Write(sbBuf)
tFile.Write([]byte("\n\n"))
_, err = reader.Discard(len(sbBuf))
}
t.templateFiles.shTemplateFile.Seek(0, 0)
_, err = io.Copy(tFile, t.templateFiles.shTemplateFile)
if err != nil {
return err
}
_, err = io.Copy(tFile, reader)
if err != nil {
return err
}
info, err := os.Stat(path)
if err != nil {
return err
}
err = os.Rename(tempFile, path)
if err != nil {
return err
}
err = os.Chmod(path, info.Mode().Perm())
if err != nil {
return err
}
return nil
}
var parserSheBang = regexp.MustCompile(`^#!(.*)`)
func (g *bashApplier) checkSheBang(target *os.File) (bool, []byte, error) {
reader := bufio.NewReader(target)
buf, _, err := reader.ReadLine()
if err != nil {
return false, nil, err
}
if parserSheBang.Match(buf) {
return true, buf, nil
}
return false, nil, nil
}