Skip to content

Commit 3aa260d

Browse files
author
andrey
committed
Add comments, add tests
1 parent e1c4df2 commit 3aa260d

File tree

12 files changed

+216
-18
lines changed

12 files changed

+216
-18
lines changed

generators/testdata/consts.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const (
1313
PackageDB = "db"
1414
PackageVT = "vt"
1515
PackageVTTemplate = "vt-template"
16+
PackageVTUpdated = "vt-updated"
1617

1718
PrefixAll = "all"
1819
PrefixEntity = "entities"
@@ -21,14 +22,13 @@ const (
2122
var (
2223
PathActual = filepath.Join(DirParent, DirTestdata, "actual")
2324
PathExpected = filepath.Join(DirParent, DirTestdata, "expected")
24-
PathUpdated = filepath.Join(DirParent, DirTestdata, "updated")
2525

2626
PathActualMFD = filepath.Join(PathActual, FilenameMFD)
2727
PathExpectedMFD = filepath.Join(PathExpected, FilenameMFD)
2828
PathActualDB = filepath.Join(PathActual, PackageDB)
2929
PathExpectedDB = filepath.Join(PathExpected, PackageDB)
3030
PathActualVT = filepath.Join(PathActual, PackageVT)
31-
PathUpdatedVT = filepath.Join(PathUpdated, PackageVT)
31+
PathUpdatedVT = filepath.Join(PathActual, PackageVTUpdated)
3232
PathExpectedVT = filepath.Join(PathExpected, PackageVT)
3333
PathActualVTTemplateAll = filepath.Join(PathActual, PackageVTTemplate, PrefixAll)
3434
PathExpectedVTTemplateAll = filepath.Join(PathExpected, PackageVTTemplate, PrefixAll)

generators/testdata/updated/vt/portal.go renamed to generators/testdata/expected/vt-updated/portal_actual.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,8 @@ func (s NewsService) dbSort(ops *ViewOps) db.OpFunc {
211211
v = db.WithSort(db.NewSortField(ops.SortColumn, ops.SortDesc))
212212
}
213213

214+
//data
215+
214216
return v
215217
}
216218

generators/testdata/updated/vt/portal_converter.go renamed to generators/testdata/expected/vt-updated/portal_converter.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ func NewNewsSummary(in *db.News) *NewsSummary {
5252
Category: NewCategorySummary(in.Category),
5353
Status: NewStatus(in.StatusID),
5454
}
55+
//data
5556
}
5657

5758
func NewNews(in *db.News) *News {
@@ -74,6 +75,7 @@ func NewNews(in *db.News) *News {
7475
Status: NewStatus(in.StatusID),
7576
}
7677

78+
//data
7779
return news
7880
}
7981

generators/testdata/updated/vt/portal_model.go renamed to generators/testdata/expected/vt-updated/portal_model.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ func (n *News) ToDB() *db.News {
3333
StatusID: n.StatusID,
3434
}
3535

36+
//data
3637
return news
3738
}
3839

@@ -94,6 +95,7 @@ type News struct {
9495

9596
Category *CategorySummary `json:"category"`
9697
Status *Status `json:"status"`
98+
//data
9799
}
98100

99101
func (ns *NewsSearch) ToDB() *db.NewsSearch {
@@ -112,6 +114,7 @@ func (ns *NewsSearch) ToDB() *db.NewsSearch {
112114
StatusID: ns.StatusID,
113115
IDs: ns.IDs,
114116
}
117+
//data
115118
}
116119

117120
type NewsSearch struct {

generators/vt/generator.go

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,27 @@ func PrintServer(namespaces []*mfd.VTNamespace, tmpl string, options Options) er
243243
return nil
244244
}
245245

246+
// PartialUpdate updates parts of the project by generating model, converter, and service files based on specified templates.
247+
//
248+
// Parameters:
249+
// - project: a pointer to the mfd.Project to be updated.
250+
// - modelTemplate: the path to the model template file.
251+
// - converterTemplate: the path to the converter template file.
252+
// - serviceTemplate: the path to the service template file.
253+
//
254+
// Returns:
255+
// - error: an error if there was an issue updating the files or at other stages.
256+
//
257+
// Example usage:
258+
//
259+
// project := ... // initialize the project
260+
// modelTemplate := "path/to/model_template.tmpl"
261+
// converterTemplate := "path/to/converter_template.tmpl"
262+
// serviceTemplate := "path/to/service_template.tmpl"
263+
// err := g.PartialUpdate(project, modelTemplate, converterTemplate, serviceTemplate)
264+
// if err != nil {
265+
// log.Fatal(err)
266+
// }
246267
func (g *Generator) PartialUpdate(project *mfd.Project, modelTemplate, converterTemplate, serviceTemplate string) error {
247268
for _, namespace := range g.options.Namespaces {
248269
ns := project.VTNamespace(namespace)
@@ -297,7 +318,14 @@ func (g *Generator) PartialUpdate(project *mfd.Project, modelTemplate, converter
297318
return nil
298319
}
299320

300-
// TargetServiceEntityData validate contains entities in ns
321+
// TargetServiceEntityData filters and returns the model entity data that are located in the specified namespace.
322+
//
323+
// Parameters:
324+
// - s: a ServiceNamespaceData object containing information about the namespace and its entities.
325+
//
326+
// Returns:
327+
// - [ ] ServiceEntityData: an array of entity data that are located in the specified namespace.
328+
// - error: an error if no entities were found or if some entities were not found in the specified namespace.
301329
func (g *Generator) TargetServiceEntityData(s ServiceNamespaceData) ([]ServiceEntityData, error) {
302330
var ee []ServiceEntityData
303331
le := len(g.options.Entities)
@@ -316,7 +344,14 @@ func (g *Generator) TargetServiceEntityData(s ServiceNamespaceData) ([]ServiceEn
316344
return ee, nil
317345
}
318346

319-
// TargetModelEntityData validate contains entities in modelData
347+
// TargetModelEntityData filters and returns the model entity data that are located in the specified namespace.
348+
//
349+
// Parameters:
350+
// - s: a NamespaceData object containing information about the namespace and its entities.
351+
//
352+
// Returns:
353+
// - [ ] EntityData: an array of entity data that are located in the specified namespace.
354+
// - error: an error if no entities were found or if some entities were not found in the specified namespace.
320355
func (g *Generator) TargetModelEntityData(s NamespaceData) ([]EntityData, error) {
321356
var ee []EntityData
322357
le := len(g.options.Entities)

generators/vt/generator_test.go

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,18 @@ func getDataCommentCount(path string) int {
3232

3333
// returnTestData function prepare test data
3434
func returnTestData() (err error) {
35+
folderPath := testdata.PathActual + "/vt-updated/"
36+
if _, err := os.Stat(folderPath); os.IsNotExist(err) {
37+
err := os.Mkdir(folderPath, 0755)
38+
if err != nil {
39+
return err
40+
}
41+
}
42+
3543
ff := make(map[string]string)
36-
ff[testdata.PathUpdated+"/vt/portal_actual.txt"] = testdata.PathUpdated + "/vt/portal.go"
37-
ff[testdata.PathUpdated+"/vt/portal_model_actual.txt"] = testdata.PathUpdated + "/vt/portal_model.go"
38-
ff[testdata.PathUpdated+"/vt/portal_converter_actual.txt"] = testdata.PathUpdated + "/vt/portal_converter.go"
44+
ff[testdata.PathExpected+"/vt-updated/portal_actual.txt"] = testdata.PathExpected + "/vt-updated/portal.go"
45+
ff[testdata.PathExpected+"/vt-updated/portal_model_actual.txt"] = testdata.PathExpected + "/vt-updated/portal_model.go"
46+
ff[testdata.PathExpected+"/vt-updated/portal_converter_actual.txt"] = testdata.PathExpected + "/vt-updated/portal_converter.go"
3947

4048
for srcPath, destPath := range ff {
4149
srcFile, err := os.Open(srcPath)
@@ -76,16 +84,17 @@ func TestGenerator_Generate(t *testing.T) {
7684
_ = returnTestData()
7785

7886
// get count comment before used generator
79-
startCountServiceComment := getDataCommentCount(testdata.PathUpdated + "/vt/portal.go")
80-
startCountModelComment := getDataCommentCount(testdata.PathUpdated + "/vt/portal_model.go")
81-
startCountConvertComment := getDataCommentCount(testdata.PathUpdated + "/vt/portal_converter.go")
87+
startCountServiceComment := getDataCommentCount(testdata.PathExpected + "/vt-updated/portal.go")
88+
startCountModelComment := getDataCommentCount(testdata.PathExpected + "/vt-updated/portal_model.go")
89+
startCountConvertComment := getDataCommentCount(testdata.PathExpected + "/vt-updated/portal_converter.go")
8290

91+
// generate
8392
generator := New()
8493

8594
generator.options.Def()
8695
generator.options.Output = testdata.PathUpdatedVT
8796
generator.options.MFDPath = testdata.PathExpectedMFD
88-
generator.options.Package = testdata.PackageVT
97+
generator.options.Package = testdata.PackageVTUpdated
8998
generator.options.Namespaces = []string{"portal"}
9099

91100
// added entity what need updated
@@ -98,9 +107,9 @@ func TestGenerator_Generate(t *testing.T) {
98107
So(err, ShouldBeNil)
99108

100109
// get count comment after used generator
101-
endCountServiceComment := getDataCommentCount(testdata.PathUpdated + "/vt/portal.go")
102-
endCountModelComment := getDataCommentCount(testdata.PathUpdated + "/vt/portal_model.go")
103-
endCountConvertComment := getDataCommentCount(testdata.PathUpdated + "/vt/portal_converter.go")
110+
endCountServiceComment := getDataCommentCount(testdata.PathUpdatedVT + "/portal.go")
111+
endCountModelComment := getDataCommentCount(testdata.PathUpdatedVT + "/portal_model.go")
112+
endCountConvertComment := getDataCommentCount(testdata.PathUpdatedVT + "/portal_converter.go")
104113

105114
// checked that after generate struct or function rewrite but not all
106115
So(startCountServiceComment, ShouldNotEqual, endCountServiceComment)

generators/vt/template.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -380,5 +380,4 @@ const serverDefaultTemplate = `
380380
`
381381

382382
const StructPattern = `type (\w+) struct {`
383-
384-
const FuncPattern = `func (\w+)`
383+
const FuncPattern = `^func (\w+)`

mfd/files.go

Lines changed: 101 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,25 @@ func FormatAndSave(data interface{}, output, tmpl string, format bool) (bool, er
195195
return Save(buffer.Bytes(), output)
196196
}
197197

198+
// renderTemplate generates data based on a template and returns it in a buffer.
199+
//
200+
// Parameters:
201+
// - data: the data used to populate the template.
202+
// - tmpl: the string containing the template for data generation.
203+
//
204+
// Returns:
205+
// - bytes.Buffer: a buffer containing the generated data.
206+
// - error: an error if there was an issue parsing or executing the template.
207+
//
208+
// Example usage:
209+
//
210+
// data := ... // data for the template
211+
// tmpl := "Template string with {{.}}"
212+
// buffer, err := renderTemplate(data, tmpl)
213+
// if err != nil {
214+
// log.Fatal(err)
215+
// }
216+
// fmt.Println("Rendered template:", buffer.String())
198217
func renderTemplate(data interface{}, tmpl string) (bytes.Buffer, error) {
199218
var buffer bytes.Buffer
200219
parsed, err := template.New("base").Funcs(TemplateFunctions).Parse(tmpl)
@@ -208,6 +227,32 @@ func renderTemplate(data interface{}, tmpl string) (bytes.Buffer, error) {
208227
return buffer, nil
209228
}
210229

230+
// replaceFragmentInFile replaces fragments of text in a file with new data if they match a given regular expression.
231+
//
232+
// Parameters:
233+
// - output: the path to the file where the replacement will take place.
234+
// - findData: the string to search for within the fragment to be replaced.
235+
// - newData: the string to replace the found fragment with.
236+
// - pattern: a pointer to a compiled regular expression used to find the fragments.
237+
//
238+
// Returns:
239+
//
240+
// - bool: true if the replacement was successful, and false otherwise.
241+
//
242+
// - error: an error if there was an issue reading the file or replacing the fragments.
243+
//
244+
// Example usage:
245+
//
246+
// output := "path/to/file.txt"
247+
// findData := "old text"
248+
// newData := "new text"
249+
// pattern := regexp.MustCompile(`pattern`)
250+
// success, err := replaceFragmentInFile(output, findData, newData, pattern)
251+
// if err != nil {
252+
// log.Fatal(err)
253+
// }
254+
//
255+
// fmt.Println("Replacement successful:", success)
211256
func replaceFragmentInFile(output, findData, newData string, pattern *regexp.Regexp) (bool, error) {
212257
content, err := os.ReadFile(output)
213258
if err != nil {
@@ -245,7 +290,31 @@ func replaceFragmentInFile(output, findData, newData string, pattern *regexp.Reg
245290
return util.FmtAndSave([]byte(newContent), output)
246291
}
247292

248-
// extractFragments returned array with coordinates start and end text
293+
// extractFragments searches for fragments of text in the provided lines that match the given regular expression.
294+
// It returns an array of tuples, each containing the start and end coordinates of the text fragments found.
295+
//
296+
// Parameters:
297+
//
298+
// - re: a pointer to a compiled regular expression used to find matches in the lines.
299+
//
300+
// - lines: an array of strings to search for matching text fragments.
301+
//
302+
// Returns:
303+
//
304+
// - [][2]int: an array of tuples, each containing the start and end indices of the found text fragments.
305+
//
306+
// - error: an error if no matching fragments are found.
307+
//
308+
// Example usage:
309+
//
310+
// re := regexp.MustCompile(`pattern`)
311+
// lines := []string{"text1", "text2", "pattern", "text3", "}"}
312+
// fragments, err := extractFragments(re, lines)
313+
// if err != nil {
314+
// log.Fatal(err)
315+
// }
316+
//
317+
// fmt.Println(fragments) // [[2, 5]]
249318
func extractFragments(re *regexp.Regexp, lines []string) ([][2]int, error) {
250319
var (
251320
reFragments [][2]int
@@ -255,12 +324,16 @@ func extractFragments(re *regexp.Regexp, lines []string) ([][2]int, error) {
255324
for i, line := range lines {
256325
if re.MatchString(line) {
257326
if start != -1 {
327+
// added fragment in slice
258328
reFragments = append(reFragments, [2]int{start, i})
259329
}
330+
// first coordinate in fragment
260331
start = i
261332
}
262333
}
263334

335+
// if the last fragment is not closed in the loop
336+
// think that this fragment is to the end of the lines
264337
if start != -1 {
265338
reFragments = append(reFragments, [2]int{start, len(lines)})
266339
}
@@ -287,14 +360,40 @@ func extractFragments(re *regexp.Regexp, lines []string) ([][2]int, error) {
287360
return ff, nil
288361
}
289362

363+
// UpdateFile updates a file by replacing specific fragments with new data generated from a template.
364+
//
365+
// Parameters:
366+
// - data: the data used to populate the template.
367+
// - output: the path to the file where the replacement will take place.
368+
// - tmpl: the path to the template file.
369+
// - pattern: a pointer to a compiled regular expression used to find the fragments.
370+
//
371+
// Returns:
372+
// - bool: true if the update was successful, and false otherwise.
373+
// - error: an error if there was an issue generating the data, replacing the fragments, or at other stages.
374+
//
375+
// Example usage:
376+
//
377+
// data := ... // data for the template
378+
// output := "path/to/file.txt"
379+
// tmpl := "path/to/template.tmpl"
380+
// pattern := regexp.MustCompile(`pattern`)
381+
// success, err := UpdateFile(data, output, tmpl, pattern)
382+
// if err != nil {
383+
// log.Fatal(err)
384+
// }
385+
//
386+
// fmt.Println("Update successful:", success)
290387
func UpdateFile(data interface{}, output, tmpl string, pattern *regexp.Regexp) (bool, error) {
291388
buffer, err := renderTemplate(data, tmpl)
292389
if err != nil {
293390
return false, fmt.Errorf("generating data error: %w", err)
294391
}
295392

393+
// get []string from generate template
296394
lines := strings.Split(buffer.String(), "\n")
297395

396+
// search fragment from our template
298397
fragments, err := extractFragments(pattern, lines)
299398

300399
for _, fragment := range fragments {
@@ -318,7 +417,7 @@ func UpdateFile(data interface{}, output, tmpl string, pattern *regexp.Regexp) (
318417

319418
// isStartedRow find row where start function or structure
320419
func isStartedRow(row string) bool {
321-
if strings.Contains(row, "func") || strings.Contains(row, "struct") {
420+
if (strings.Contains(row, "func") || strings.Contains(row, "struct")) && !strings.Contains(row, "//") {
322421
return true
323422
}
324423
return false

0 commit comments

Comments
 (0)