spec_change.go 12.5 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"
)

Mustafa Gezen's avatar
Mustafa Gezen committed
23
24
25
26
var (
	sections = []string{"%description", "%prep", "%build", "%install", "%files", "%changelog"}
)

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

type sourcePatchOperationAfterLoopRequest struct {
	cfg           *srpmprocpb.Cfg
	inLoopNum     int
	lastNum       *int
	longestField  int
	newLines      *[]string
Mustafa Gezen's avatar
Mustafa Gezen committed
44
	in            *string
45
46
47
48
49
50
51
	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
52
			if file.Type != req.operation {
53
54
55
56
57
58
59
60
61
62
63
				continue
			}

			switch file.Mode.(type) {
			case *srpmprocpb.SpecChange_FileOperation_Delete:
				if file.Name == *req.value {
					*req.value = ""
				}
				break
			}
		}
64
65
66
67
68
69
		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
70
71
72
73
74
75
76
		}
	}

	return nil
}

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

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

				if req.expectedField == "Patch" && file.AddToPrep {
					val := fmt.Sprintf("%%patch%d", fieldNum)
					if file.NPath > 0 {
						val = fmt.Sprintf("%s -p%d", val, file.NPath)
					}

					req.cfg.SpecChange.Append = append(req.cfg.SpecChange.Append, &srpmprocpb.SpecChange_AppendOperation{
						Field: "%prep",
						Value: val,
					})
				}

102
103
104
105
				*req.lastNum++
				break
			}
		}
Mustafa Gezen's avatar
Mustafa Gezen committed
106
		*req.in = ""
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124

		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:
125
			if strings.HasPrefix(strings.TrimSpace(line), searchAndReplace.Find) {
126
127
128
129
				line = strings.Replace(line, searchAndReplace.Find, searchAndReplace.Replace, int(searchAndReplace.N))
			}
			break
		case *srpmprocpb.SpecChange_SearchAndReplaceOperation_EndsWith:
130
			if strings.HasSuffix(strings.TrimSpace(line), searchAndReplace.Find) {
131
132
133
134
135
136
137
138
139
				line = strings.Replace(line, searchAndReplace.Find, searchAndReplace.Replace, int(searchAndReplace.N))
			}
			break
		}
	}

	return line
}

Mustafa Gezen's avatar
Mustafa Gezen committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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)
}

Mustafa Gezen's avatar
Mustafa Gezen committed
159
160
161
162
163
164
165
166
167
168
func strSliceContains(slice []string, str string) bool {
	for _, x := range slice {
		if str == x {
			return true
		}
	}

	return false
}

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
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
205
206
	futureAdditions := map[int][]string{}
	newFieldMemory := map[string]map[string]int{}
207
208
	lastSourceNum := 0
	lastPatchNum := 0
209
	inSection := ""
Mustafa Gezen's avatar
Mustafa Gezen committed
210
	inField := ""
211
212
	lastSource := ""
	lastPatch := ""
Mustafa Gezen's avatar
Mustafa Gezen committed
213
	hasPatch := false
214
215

	version := ""
216
217
	importName := strings.Replace(pd.Importer.ImportName(pd, md), md.RpmFile.Name(), "1", 1)
	importNameSplit := strings.SplitN(importName, "-", 2)
218
219
220
221
	if len(importNameSplit) == 2 {
		versionSplit := strings.SplitN(importNameSplit[1], ".el", 2)
		if len(versionSplit) == 2 {
			version = versionSplit[0]
222
223
224
225
226
		} else {
			versionSplit := strings.SplitN(importNameSplit[1], ".module", 2)
			if len(versionSplit) == 2 {
				version = versionSplit[0]
			}
227
228
229
230
231
232
		}
	}

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

	longestField := 0
Mustafa Gezen's avatar
Mustafa Gezen committed
233
	for lineNum, line := range lines {
234
235
236
237
238
239
240
		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
241
242
			} else if strings.HasPrefix(field, "Patch") {
				lastPatch = field
Mustafa Gezen's avatar
Mustafa Gezen committed
243
				hasPatch = true
Mustafa Gezen's avatar
Mustafa Gezen committed
244
245
246
247
248
249
250
251
252
			} 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
					}
				}
253
			}
Mustafa Gezen's avatar
Mustafa Gezen committed
254
255
256
257
258
259
260
261
		}
	}
	for _, nf := range cfg.SpecChange.NewField {
		if newFieldMemory[nf.Key] == nil {
			newFieldMemory[nf.Key] = map[string]int{}
			newFieldMemory[nf.Key][nf.Value] = 0
		}
	}
262

Mustafa Gezen's avatar
Mustafa Gezen committed
263
264
265
266
267
	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)
268
269
270
271
			}
		}
	}

272
	for lineNum, line := range lines {
273
274
275
276
		inLoopSourceNum := lastSourceNum
		inLoopPatchNum := lastPatchNum
		prefixLine := strings.TrimSpace(line)

Mustafa Gezen's avatar
Mustafa Gezen committed
277
		for i, additions := range futureAdditions {
278
			if lineNum == i {
Mustafa Gezen's avatar
Mustafa Gezen committed
279
280
281
				for _, addition := range additions {
					newLines = append(newLines, addition)
				}
282
283
284
			}
		}

285
286
287
288
289
290
291
		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
292
				inField = "Source"
293
			} else if field == lastPatch {
Mustafa Gezen's avatar
Mustafa Gezen committed
294
				inField = "Patch"
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
			}

			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
311
312
313
			for _, appendOp := range cfg.SpecChange.Append {
				if field == appendOp.Field {
					value = value + appendOp.Value
314
315
316
317

					if field == "Release" {
						version = version + appendOp.Value
					}
Mustafa Gezen's avatar
Mustafa Gezen committed
318
319
320
				}
			}

321
322
323
324
325
326
327
328
			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
329
				in:            &inField,
Mustafa Gezen's avatar
Mustafa Gezen committed
330
331
				expectedField: "Source",
				operation:     srpmprocpb.SpecChange_FileOperation_Source,
332
333
334
335
336
337
338
339
340
341
342
			})
			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
343
				in:            &inField,
344
				expectedField: "Patch",
Mustafa Gezen's avatar
Mustafa Gezen committed
345
				operation:     srpmprocpb.SpecChange_FileOperation_Patch,
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
			})
			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
362
				in:            &inField,
363
364
365
366
367
368
				operation:     srpmprocpb.SpecChange_FileOperation_Source,
			})
			if err != nil {
				return err
			}

Mustafa Gezen's avatar
Mustafa Gezen committed
369
			if executed && !hasPatch {
370
				newLines = append(newLines, "")
Mustafa Gezen's avatar
Mustafa Gezen committed
371
				inField = "Patch"
372
373
374
375
376
377
378
379
380
			}

			executed, err = sourcePatchOperationAfterLoop(&sourcePatchOperationAfterLoopRequest{
				cfg:           cfg,
				inLoopNum:     inLoopPatchNum,
				lastNum:       &lastPatchNum,
				longestField:  longestField,
				newLines:      &newLines,
				expectedField: "Patch",
Mustafa Gezen's avatar
Mustafa Gezen committed
381
				in:            &inField,
382
383
384
385
386
387
				operation:     srpmprocpb.SpecChange_FileOperation_Patch,
			})
			if err != nil {
				return err
			}

Mustafa Gezen's avatar
Mustafa Gezen committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
			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)
					}
				}
			}

408
409
410
			if executed && !strings.Contains(specStr, "%changelog") {
				newLines = append(newLines, "")
				newLines = append(newLines, "%changelog")
411
				inSection = sectionChangelog
412
413
			}

414
			if inSection == sectionChangelog {
415
416
417
418
419
420
421
422
				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, "")
				}
423
				inSection = ""
424
425
426
427
			} else {
				line = searchAndReplaceLine(line, cfg.SpecChange.SearchAndReplace)
			}

428
429
430
431
432
433
434
			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:] {
Mustafa Gezen's avatar
Mustafa Gezen committed
435
436
							if strSliceContains(sections, strings.TrimSpace(x)) {
								insertedLine = lineNum + i
Mustafa Gezen's avatar
Mustafa Gezen committed
437
								setFASlice(futureAdditions, insertedLine, appendOp.Value)
438
439
440
441
442
443
444
								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
445
									setFASlice(futureAdditions, insertedLine, appendOp.Value)
446
447
448
449
450
451
									break
								}
							}
						}
					}
				}
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
			}

			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
}