-
Notifications
You must be signed in to change notification settings - Fork 8
/
makefile.go
83 lines (67 loc) · 1.49 KB
/
makefile.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
package main
import (
"bufio"
"io"
"os"
"path/filepath"
"strings"
)
type makefileApplier struct {
}
func (g *makefileApplier) CheckHeader(target *os.File, t *TagContext) (bool, error) {
tbuf, err := os.ReadFile(filepath.Join(t.templatePath, "makefile.txt"))
if err != nil {
return false, err
}
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(string(templateBuf), string(targetBuf)) == 0 {
return true, nil
}
}
return false, nil
}
func (g *makefileApplier) 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.mTemplateFile.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.mTemplateFile.Seek(0, 0)
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)
t.templateFiles.mTemplateFile.Seek(0, 0)
_, err = io.Copy(tFile, t.templateFiles.mTemplateFile)
if err != nil {
return err
}
_, err = io.Copy(tFile, reader)
if err != nil {
return err
}
err = os.Rename(tempFile, path)
if err != nil {
return err
}
return nil
}