-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerator.go
235 lines (192 loc) · 6.08 KB
/
generator.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package liquo
import (
"bytes"
"context"
_ "embed"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"text/template"
"time"
"github.com/go-xmlfmt/xmlfmt"
"github.com/gobuffalo/flect"
"github.com/spf13/pflag"
"github.com/wawandco/liquo/internal/log"
"github.com/wawandco/ox/plugins/core"
)
var (
ErrNameArgMissing = errors.New("name arg missing")
ErrInvalidName = errors.New("invalid migration name")
ErrInvalidPath = errors.New("invalid path")
ErrInvalidChangelogFormat = errors.New("changelog.xml file has bad format or is empty")
// MigrationTemplate for the migration generator.
//go:embed templates/migration.xml.tmpl
migrationTemplate string
//go:embed templates/changelog.xml.tmpl
changelogTemplate string
)
var (
// Ensuring we're building a plugin
_ core.Plugin = (*Generator)(nil)
// Ensuring the plugin is a flagparser
_ core.FlagParser = (*Generator)(nil)
)
// Generator for liquibase SQL migrations, it generates xml liquibase
// for SQL in the root + basedir folder. It uses the argument passed
// to determine both the name of the migration and the destination.
// Some examples are:
// - "ox generate migration name" generates [timestamp]-name.xml
// - "ox generate migration folder/name" generates folder/[timestamp]-name.xml
// - "ox generate migration name --base migrations" generates migrations/[timestamp]-name.xml
type Generator struct {
// mockTimestamp is used for testing purposes, it would replace the
// timestamp at the beggining of the migration name.
mockTimestamp string
// Basefolder for the migrations, if a path is passed, then we will append that
// path to the baseFolder when generating the migration.
baseFolder string
flags *pflag.FlagSet
}
// Name is the name used to identify the generator and also
// the plugin
func (g Generator) Name() string {
return "liquo/generate-migration"
}
// Name is the name used to identify the generator and also
// the plugin
func (g Generator) InvocationName() string {
return "migration"
}
// Generate a new migration based on the passed args. This needs at least 3
// args since the 3rd arg will be used by the generator to build the name of
// the migration.
func (g Generator) Generate(ctx context.Context, root string, args []string) error {
if len(args) < 3 {
return ErrNameArgMissing
}
path, err := g.generateFile(args)
if err != nil {
return err
}
log.Infof("migration generated in %v", path)
err = g.addToChangelog(root, path)
if err == ErrInvalidChangelogFormat {
log.Infof("auto-add to changelog file failed: %v", err.Error())
return nil
}
if err != nil {
return err
}
log.Infof("migration added to the changelog.xml file")
return nil
}
func (g Generator) addToChangelog(root, path string) error {
changelog := filepath.Join(root, "migrations", "changelog.xml")
original, err := ioutil.ReadFile(changelog)
if os.IsNotExist(err) {
err = g.generateChangelogFile()
if err != nil {
log.Infof("failed generating changelog.xml file: %v", err.Error())
}
log.Infof("changelog.xml was not found, file was generated automatically")
original, err = ioutil.ReadFile(changelog)
}
if err != nil {
return err
}
fileContent := string(original)
fileContent = strings.TrimSpace(fileContent)
if len(original) == 0 {
return ErrInvalidChangelogFormat
}
mainTagRegexPattern := `<\?xml\s+.+\?>`
matchesMainTag, err := regexp.MatchString(mainTagRegexPattern, fileContent)
if err != nil {
return err
}
if !matchesMainTag {
return ErrInvalidChangelogFormat
}
dbChangelogTags := `<databaseChangeLog\s+.*>(.|\n)*</databaseChangeLog>`
matchesTags, err := regexp.MatchString(dbChangelogTags, fileContent)
if err != nil {
return err
}
if !matchesTags {
return ErrInvalidChangelogFormat
}
statement := fmt.Sprintf(`<include file="%s" />`, path)
result := strings.Replace(fileContent, `</databaseChangeLog>`, statement+"</databaseChangeLog>", 1)
result = xmlfmt.FormatXML(result, "", "\t")
parts := strings.Split(result, "\n")
result = strings.Join(parts[1:], "\n")
err = ioutil.WriteFile(changelog, []byte(result), 0777)
if err != nil {
return err
}
return nil
}
func (g Generator) generateFile(args []string) (string, error) {
timestamp := time.Now().UTC().Format("20060102150405")
if g.mockTimestamp != "" {
timestamp = g.mockTimestamp
}
filename, err := g.composeFilename(args[2], timestamp)
if err != nil {
return "", err
}
path := g.baseFolder
if dir := filepath.Dir(args[2]); dir != "." {
path = filepath.Join(g.baseFolder, dir)
}
path = filepath.Join(path, filename)
err = os.MkdirAll(filepath.Dir(path), 0755)
if err != nil {
return path, err
}
tmpl, err := template.New("migration-template").Parse(migrationTemplate)
if err != nil {
return path, err
}
var tpl bytes.Buffer
err = tmpl.Execute(&tpl, strings.ReplaceAll(filename, ".xml", ""))
if err != nil {
return path, err
}
return path, ioutil.WriteFile(path, tpl.Bytes(), 0655)
}
func (g Generator) generateChangelogFile() error {
filename := "changelog.xml"
path := filepath.Join("migrations", filename)
err := os.MkdirAll(filepath.Dir(path), 0755)
if err != nil {
return err
}
return ioutil.WriteFile(path, []byte(changelogTemplate), 0655)
}
// composeFilename from the passed arg and timestamp, if the passed path is
// a dot (.) or a folder "/" then it will return ErrInvalidName.
func (g Generator) composeFilename(passed, timestamp string) (string, error) {
name := filepath.Base(passed)
//Should we check the name here ?
if name == "." || name == "/" {
return "", ErrInvalidName
}
underscoreName := flect.Underscore(name)
result := timestamp + "-" + underscoreName + ".xml"
return result, nil
}
// Parseflags will parse the baseFolder from the --base or -b flag
func (g *Generator) ParseFlags(args []string) {
g.flags = pflag.NewFlagSet(g.Name(), pflag.ContinueOnError)
g.flags.StringVarP(&g.baseFolder, "base", "b", "migrations", "destination folder of the generated migration")
g.flags.Parse(args) //nolint:errcheck,we don't care hence the flag
}
// Flags parsed by the plugin
func (g *Generator) Flags() *pflag.FlagSet {
return g.flags
}