spec_change.go 11.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package directives

import (
	"errors"
	"fmt"
	"git.rockylinux.org/release-engineering/public/srpmproc/internal/data"
	srpmprocpb "git.rockylinux.org/release-engineering/public/srpmproc/pb"
	"github.com/go-git/go-git/v5"
	"io/ioutil"
	"math"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"
)

19
20
21
22
const (
	sectionChangelog = "%changelog"
)

23
24
25
26
27
28
type sourcePatchOperationInLoopRequest struct {
	cfg           *srpmprocpb.Cfg
	field         string
	value         *string
	longestField  int
	lastNum       *int
Mustafa Gezen's avatar
Mustafa Gezen committed
29
	in            *string
30
	expectedField string
Mustafa Gezen's avatar
Mustafa Gezen committed
31
	operation     srpmprocpb.SpecChange_FileOperation_Type
32
33
34
35
36
37
38
39
}

type sourcePatchOperationAfterLoopRequest struct {
	cfg           *srpmprocpb.Cfg
	inLoopNum     int
	lastNum       *int
	longestField  int
	newLines      *[]string
Mustafa Gezen's avatar
Mustafa Gezen committed
40
	in            *string
41
42
43
44
45
46
47
	expectedField string
	operation     srpmprocpb.SpecChange_FileOperation_Type
}

func sourcePatchOperationInLoop(req *sourcePatchOperationInLoopRequest) error {
	if strings.HasPrefix(req.field, req.expectedField) {
		for _, file := range req.cfg.SpecChange.File {
Mustafa Gezen's avatar
Mustafa Gezen committed
48
			if file.Type != req.operation {
49
50
51
52
53
54
55
56
57
58
59
				continue
			}

			switch file.Mode.(type) {
			case *srpmprocpb.SpecChange_FileOperation_Delete:
				if file.Name == *req.value {
					*req.value = ""
				}
				break
			}
		}
60
61
62
63
64
65
		if req.field != req.expectedField {
			sourceNum, err := strconv.Atoi(strings.Split(req.field, req.expectedField)[1])
			if err != nil {
				return errors.New(fmt.Sprintf("INVALID_%s_NUM:%s", strings.ToUpper(req.expectedField), req.field))
			}
			*req.lastNum = sourceNum
66
67
68
69
70
71
72
		}
	}

	return nil
}

func sourcePatchOperationAfterLoop(req *sourcePatchOperationAfterLoopRequest) (bool, error) {
Mustafa Gezen's avatar
Mustafa Gezen committed
73
	if req.inLoopNum == *req.lastNum && *req.in == req.expectedField {
74
75
76
77
78
79
80
81
82
83
84
85
86
87
		for _, file := range req.cfg.SpecChange.File {
			if file.Type != req.operation {
				continue
			}

			switch file.Mode.(type) {
			case *srpmprocpb.SpecChange_FileOperation_Add:
				field := fmt.Sprintf("%s%d", req.expectedField, *req.lastNum+1)
				spaces := calculateSpaces(req.longestField, len(field))
				*req.newLines = append(*req.newLines, fmt.Sprintf("%s:%s%s", field, spaces, file.Name))
				*req.lastNum++
				break
			}
		}
Mustafa Gezen's avatar
Mustafa Gezen committed
88
		*req.in = ""
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

		return true, nil
	}

	return false, nil
}

func calculateSpaces(longestField int, fieldLength int) string {
	return strings.Repeat(" ", longestField+8-fieldLength)
}

func searchAndReplaceLine(line string, sar []*srpmprocpb.SpecChange_SearchAndReplaceOperation) string {
	for _, searchAndReplace := range sar {
		switch searchAndReplace.Identifier.(type) {
		case *srpmprocpb.SpecChange_SearchAndReplaceOperation_Any:
			line = strings.Replace(line, searchAndReplace.Find, searchAndReplace.Replace, int(searchAndReplace.N))
			break
		case *srpmprocpb.SpecChange_SearchAndReplaceOperation_StartsWith:
107
			if strings.HasPrefix(strings.TrimSpace(line), searchAndReplace.Find) {
108
109
110
111
				line = strings.Replace(line, searchAndReplace.Find, searchAndReplace.Replace, int(searchAndReplace.N))
			}
			break
		case *srpmprocpb.SpecChange_SearchAndReplaceOperation_EndsWith:
112
			if strings.HasSuffix(strings.TrimSpace(line), searchAndReplace.Find) {
113
114
115
116
117
118
119
120
121
				line = strings.Replace(line, searchAndReplace.Find, searchAndReplace.Replace, int(searchAndReplace.N))
			}
			break
		}
	}

	return line
}

Mustafa Gezen's avatar
Mustafa Gezen committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
func isNextLineSection(lineNum int, lines []string) bool {
	if len(lines)-1 > lineNum {
		if strings.HasPrefix(strings.TrimSpace(lines[lineNum+1]), "%") {
			return true
		}

		return false
	}

	return true
}

func setFASlice(futureAdditions map[int][]string, key int, addition string) {
	if futureAdditions[key] == nil {
		futureAdditions[key] = []string{}
	}
	futureAdditions[key] = append(futureAdditions[key], addition)
}

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
func specChange(cfg *srpmprocpb.Cfg, pd *data.ProcessData, md *data.ModeData, _ *git.Worktree, pushTree *git.Worktree) error {
	// no spec change operations present
	// skip parsing spec
	if cfg.SpecChange == nil {
		return nil
	}

	specFiles, err := pushTree.Filesystem.ReadDir("SPECS")
	if err != nil {
		return errors.New("COULD_NOT_READ_SPECS_DIR")
	}

	if len(specFiles) != 1 {
		return errors.New("ONLY_ONE_SPEC_FILE_IS_SUPPORTED")
	}

	filePath := filepath.Join("SPECS", specFiles[0].Name())
	stat, err := pushTree.Filesystem.Stat(filePath)
	if err != nil {
		return errors.New("COULD_NOT_STAT_SPEC_FILE")
	}

	specFile, err := pushTree.Filesystem.OpenFile(filePath, os.O_RDONLY, 0644)
	if err != nil {
		return errors.New("COULD_NOT_READ_SPEC_FILE")
	}

	specBts, err := ioutil.ReadAll(specFile)
	if err != nil {
		return errors.New("COULD_NOT_READ_ALL_BYTES")
	}

	specStr := string(specBts)
	lines := strings.Split(specStr, "\n")

	var newLines []string
Mustafa Gezen's avatar
Mustafa Gezen committed
177
178
	futureAdditions := map[int][]string{}
	newFieldMemory := map[string]map[string]int{}
179
180
	lastSourceNum := 0
	lastPatchNum := 0
181
	inSection := ""
Mustafa Gezen's avatar
Mustafa Gezen committed
182
	inField := ""
183
184
185
186
	lastSource := ""
	lastPatch := ""

	version := ""
187
188
	importName := strings.Replace(pd.Importer.ImportName(pd, md), md.RpmFile.Name(), "1", 1)
	importNameSplit := strings.SplitN(importName, "-", 2)
189
190
191
192
	if len(importNameSplit) == 2 {
		versionSplit := strings.SplitN(importNameSplit[1], ".el", 2)
		if len(versionSplit) == 2 {
			version = versionSplit[0]
193
194
195
196
197
		} else {
			versionSplit := strings.SplitN(importNameSplit[1], ".module", 2)
			if len(versionSplit) == 2 {
				version = versionSplit[0]
			}
198
199
200
201
202
203
		}
	}

	fieldValueRegex := regexp.MustCompile("^[A-Z].+:")

	longestField := 0
Mustafa Gezen's avatar
Mustafa Gezen committed
204
	for lineNum, line := range lines {
205
206
207
208
209
210
211
		if fieldValueRegex.MatchString(line) {
			fieldValue := strings.SplitN(line, ":", 2)
			field := strings.TrimSpace(fieldValue[0])
			longestField = int(math.Max(float64(len(field)), float64(longestField)))

			if strings.HasPrefix(field, "Source") {
				lastSource = field
Mustafa Gezen's avatar
Mustafa Gezen committed
212
213
214
215
216
217
218
219
220
221
222
			} else if strings.HasPrefix(field, "Patch") {
				lastPatch = field
			} else {
				for _, nf := range cfg.SpecChange.NewField {
					if field == nf.Key {
						if newFieldMemory[field] == nil {
							newFieldMemory[field] = map[string]int{}
						}
						newFieldMemory[field][nf.Value] = lineNum
					}
				}
223
			}
Mustafa Gezen's avatar
Mustafa Gezen committed
224
225
226
227
228
229
230
231
		}
	}
	for _, nf := range cfg.SpecChange.NewField {
		if newFieldMemory[nf.Key] == nil {
			newFieldMemory[nf.Key] = map[string]int{}
			newFieldMemory[nf.Key][nf.Value] = 0
		}
	}
232

Mustafa Gezen's avatar
Mustafa Gezen committed
233
234
235
236
237
	for field, nfm := range newFieldMemory {
		for value, lineNum := range nfm {
			if lineNum != 0 {
				newLine := fmt.Sprintf("%s:%s%s", field, calculateSpaces(longestField, len(field)), value)
				setFASlice(futureAdditions, lineNum+1, newLine)
238
239
240
241
			}
		}
	}

242
	for lineNum, line := range lines {
243
244
245
246
		inLoopSourceNum := lastSourceNum
		inLoopPatchNum := lastPatchNum
		prefixLine := strings.TrimSpace(line)

Mustafa Gezen's avatar
Mustafa Gezen committed
247
		for i, additions := range futureAdditions {
248
			if lineNum == i {
Mustafa Gezen's avatar
Mustafa Gezen committed
249
250
251
				for _, addition := range additions {
					newLines = append(newLines, addition)
				}
252
253
254
			}
		}

255
256
257
258
259
260
261
		if fieldValueRegex.MatchString(line) {
			line = searchAndReplaceLine(line, cfg.SpecChange.SearchAndReplace)
			fieldValue := strings.SplitN(line, ":", 2)
			field := strings.TrimSpace(fieldValue[0])
			value := strings.TrimSpace(fieldValue[1])

			if field == lastSource {
Mustafa Gezen's avatar
Mustafa Gezen committed
262
				inField = "Source"
263
			} else if field == lastPatch {
Mustafa Gezen's avatar
Mustafa Gezen committed
264
				inField = "Patch"
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
			}

			if field == "Version" && version == "" {
				version = value
			}

			for _, searchAndReplace := range cfg.SpecChange.SearchAndReplace {
				switch identifier := searchAndReplace.Identifier.(type) {
				case *srpmprocpb.SpecChange_SearchAndReplaceOperation_Field:
					if field == identifier.Field {
						value = strings.Replace(value, searchAndReplace.Find, searchAndReplace.Replace, int(searchAndReplace.N))
					}
					break
				}
			}

Mustafa Gezen's avatar
Mustafa Gezen committed
281
282
283
			for _, appendOp := range cfg.SpecChange.Append {
				if field == appendOp.Field {
					value = value + appendOp.Value
284
285
286
287

					if field == "Release" {
						version = version + appendOp.Value
					}
Mustafa Gezen's avatar
Mustafa Gezen committed
288
289
290
				}
			}

291
292
293
294
295
296
297
298
			spaces := calculateSpaces(longestField, len(field))

			err := sourcePatchOperationInLoop(&sourcePatchOperationInLoopRequest{
				cfg:           cfg,
				field:         field,
				value:         &value,
				lastNum:       &lastSourceNum,
				longestField:  longestField,
Mustafa Gezen's avatar
Mustafa Gezen committed
299
				in:            &inField,
Mustafa Gezen's avatar
Mustafa Gezen committed
300
301
				expectedField: "Source",
				operation:     srpmprocpb.SpecChange_FileOperation_Source,
302
303
304
305
306
307
308
309
310
311
312
			})
			if err != nil {
				return err
			}

			err = sourcePatchOperationInLoop(&sourcePatchOperationInLoopRequest{
				cfg:           cfg,
				field:         field,
				value:         &value,
				longestField:  longestField,
				lastNum:       &lastPatchNum,
Mustafa Gezen's avatar
Mustafa Gezen committed
313
				in:            &inField,
314
				expectedField: "Patch",
Mustafa Gezen's avatar
Mustafa Gezen committed
315
				operation:     srpmprocpb.SpecChange_FileOperation_Patch,
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
			})
			if err != nil {
				return err
			}

			if value != "" {
				newLines = append(newLines, fmt.Sprintf("%s:%s%s", field, spaces, value))
			}
		} else {
			executed, err := sourcePatchOperationAfterLoop(&sourcePatchOperationAfterLoopRequest{
				cfg:           cfg,
				inLoopNum:     inLoopSourceNum,
				lastNum:       &lastSourceNum,
				longestField:  longestField,
				newLines:      &newLines,
				expectedField: "Source",
Mustafa Gezen's avatar
Mustafa Gezen committed
332
				in:            &inField,
333
334
335
336
337
338
339
340
				operation:     srpmprocpb.SpecChange_FileOperation_Source,
			})
			if err != nil {
				return err
			}

			if executed && !strings.Contains(specStr, "Patch") {
				newLines = append(newLines, "")
Mustafa Gezen's avatar
Mustafa Gezen committed
341
				inField = "Patch"
342
343
344
345
346
347
348
349
350
			}

			executed, err = sourcePatchOperationAfterLoop(&sourcePatchOperationAfterLoopRequest{
				cfg:           cfg,
				inLoopNum:     inLoopPatchNum,
				lastNum:       &lastPatchNum,
				longestField:  longestField,
				newLines:      &newLines,
				expectedField: "Patch",
Mustafa Gezen's avatar
Mustafa Gezen committed
351
				in:            &inField,
352
353
354
355
356
357
				operation:     srpmprocpb.SpecChange_FileOperation_Patch,
			})
			if err != nil {
				return err
			}

Mustafa Gezen's avatar
Mustafa Gezen committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
			if executed {
				var innerNewLines []string
				for field, nfm := range newFieldMemory {
					for value, ln := range nfm {
						newLine := fmt.Sprintf("%s:%s%s", field, calculateSpaces(longestField, len(field)), value)
						if ln == 0 {
							if isNextLineSection(lineNum, lines) {
								innerNewLines = append(innerNewLines, newLine)
							}
						}
					}
				}
				if len(innerNewLines) > 0 {
					newLines = append(newLines, "")
					for _, il := range innerNewLines {
						newLines = append(newLines, il)
					}
				}
			}

378
379
380
			if executed && !strings.Contains(specStr, "%changelog") {
				newLines = append(newLines, "")
				newLines = append(newLines, "%changelog")
381
				inSection = sectionChangelog
382
383
			}

384
			if inSection == sectionChangelog {
385
386
387
388
389
390
391
392
				now := time.Now().Format("Mon Jan 02 2006")
				for _, changelog := range cfg.SpecChange.Changelog {
					newLines = append(newLines, fmt.Sprintf("* %s %s <%s> - %s", now, changelog.AuthorName, changelog.AuthorEmail, version))
					for _, msg := range changelog.Message {
						newLines = append(newLines, fmt.Sprintf("- %s", msg))
					}
					newLines = append(newLines, "")
				}
393
				inSection = ""
394
395
396
397
			} else {
				line = searchAndReplaceLine(line, cfg.SpecChange.SearchAndReplace)
			}

398
399
400
401
402
403
404
405
406
			if strings.HasPrefix(prefixLine, "%") {
				inSection = prefixLine

				for _, appendOp := range cfg.SpecChange.Append {
					if inSection == appendOp.Field {
						insertedLine := 0
						for i, x := range lines[lineNum+1:] {
							if strings.HasPrefix(strings.TrimSpace(x), "%") {
								insertedLine = lineNum + i + 2
Mustafa Gezen's avatar
Mustafa Gezen committed
407
								setFASlice(futureAdditions, insertedLine, appendOp.Value)
408
409
410
411
412
413
414
								break
							}
						}
						if insertedLine == 0 {
							for i, x := range lines[lineNum+1:] {
								if strings.TrimSpace(x) == "" {
									insertedLine = lineNum + i + 2
Mustafa Gezen's avatar
Mustafa Gezen committed
415
									setFASlice(futureAdditions, insertedLine, appendOp.Value)
416
417
418
419
420
421
									break
								}
							}
						}
					}
				}
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
			}

			newLines = append(newLines, line)
		}
	}

	err = pushTree.Filesystem.Remove(filePath)
	if err != nil {
		return errors.New(fmt.Sprintf("COULD_NOT_REMOVE_OLD_SPEC_FILE:%s", filePath))
	}

	f, err := pushTree.Filesystem.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, stat.Mode())
	if err != nil {
		return errors.New(fmt.Sprintf("COULD_NOT_OPEN_REPLACEMENT_SPEC_FILE:%s", filePath))
	}

	_, err = f.Write([]byte(strings.Join(newLines, "\n")))
	if err != nil {
		return errors.New("COULD_NOT_WRITE_NEW_SPEC_FILE")
	}

	return nil
}