spec_change.go 13.6 KB
Newer Older
Mustafa Gezen's avatar
Mustafa Gezen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Copyright (c) 2021 The Srpmproc Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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"
)

39
40
41
42
const (
	sectionChangelog = "%changelog"
)

Mustafa Gezen's avatar
Mustafa Gezen committed
43
44
45
46
var (
	sections = []string{"%description", "%prep", "%build", "%install", "%files", "%changelog"}
)

47
48
49
50
51
52
type sourcePatchOperationInLoopRequest struct {
	cfg           *srpmprocpb.Cfg
	field         string
	value         *string
	longestField  int
	lastNum       *int
Mustafa Gezen's avatar
Mustafa Gezen committed
53
	in            *string
54
	expectedField string
Mustafa Gezen's avatar
Mustafa Gezen committed
55
	operation     srpmprocpb.SpecChange_FileOperation_Type
56
57
58
59
60
61
62
63
}

type sourcePatchOperationAfterLoopRequest struct {
	cfg           *srpmprocpb.Cfg
	inLoopNum     int
	lastNum       *int
	longestField  int
	newLines      *[]string
Mustafa Gezen's avatar
Mustafa Gezen committed
64
	in            *string
65
66
67
68
69
70
71
	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
72
			if file.Type != req.operation {
73
74
75
76
77
78
79
80
81
82
83
				continue
			}

			switch file.Mode.(type) {
			case *srpmprocpb.SpecChange_FileOperation_Delete:
				if file.Name == *req.value {
					*req.value = ""
				}
				break
			}
		}
84
85
86
87
88
89
		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
90
91
92
93
94
95
96
		}
	}

	return nil
}

func sourcePatchOperationAfterLoop(req *sourcePatchOperationAfterLoopRequest) (bool, error) {
Mustafa Gezen's avatar
Mustafa Gezen committed
97
	if req.inLoopNum == *req.lastNum && *req.in == req.expectedField {
98
99
100
101
102
103
104
		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
105
106
				fieldNum := *req.lastNum + 1
				field := fmt.Sprintf("%s%d", req.expectedField, fieldNum)
107
108
				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
109
110
111
112
113
114
115
116
117
118
119
120
121

				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,
					})
				}

122
123
124
125
				*req.lastNum++
				break
			}
		}
Mustafa Gezen's avatar
Mustafa Gezen committed
126
		*req.in = ""
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

		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:
145
			if strings.HasPrefix(strings.TrimSpace(line), searchAndReplace.Find) {
146
147
148
149
				line = strings.Replace(line, searchAndReplace.Find, searchAndReplace.Replace, int(searchAndReplace.N))
			}
			break
		case *srpmprocpb.SpecChange_SearchAndReplaceOperation_EndsWith:
150
			if strings.HasSuffix(strings.TrimSpace(line), searchAndReplace.Find) {
151
152
153
154
155
156
157
158
159
				line = strings.Replace(line, searchAndReplace.Find, searchAndReplace.Replace, int(searchAndReplace.N))
			}
			break
		}
	}

	return line
}

Mustafa Gezen's avatar
Mustafa Gezen committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
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
179
180
181
182
183
184
185
186
187
188
func strSliceContains(slice []string, str string) bool {
	for _, x := range slice {
		if str == x {
			return true
		}
	}

	return false
}

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
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
225
226
	futureAdditions := map[int][]string{}
	newFieldMemory := map[string]map[string]int{}
227
228
	lastSourceNum := 0
	lastPatchNum := 0
229
	inSection := ""
Mustafa Gezen's avatar
Mustafa Gezen committed
230
	inField := ""
231
232
	lastSource := ""
	lastPatch := ""
Mustafa Gezen's avatar
Mustafa Gezen committed
233
	hasPatch := false
234
235

	version := ""
236
237
	importName := strings.Replace(pd.Importer.ImportName(pd, md), md.RpmFile.Name(), "1", 1)
	importNameSplit := strings.SplitN(importName, "-", 2)
238
239
240
241
	if len(importNameSplit) == 2 {
		versionSplit := strings.SplitN(importNameSplit[1], ".el", 2)
		if len(versionSplit) == 2 {
			version = versionSplit[0]
242
243
244
245
246
		} else {
			versionSplit := strings.SplitN(importNameSplit[1], ".module", 2)
			if len(versionSplit) == 2 {
				version = versionSplit[0]
			}
247
248
249
250
251
252
		}
	}

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

	longestField := 0
Mustafa Gezen's avatar
Mustafa Gezen committed
253
	for lineNum, line := range lines {
254
255
256
257
258
259
260
		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
261
262
			} else if strings.HasPrefix(field, "Patch") {
				lastPatch = field
Mustafa Gezen's avatar
Mustafa Gezen committed
263
				hasPatch = true
Mustafa Gezen's avatar
Mustafa Gezen committed
264
265
266
267
268
269
270
271
272
			} 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
					}
				}
273
			}
Mustafa Gezen's avatar
Mustafa Gezen committed
274
275
276
277
278
279
280
281
		}
	}
	for _, nf := range cfg.SpecChange.NewField {
		if newFieldMemory[nf.Key] == nil {
			newFieldMemory[nf.Key] = map[string]int{}
			newFieldMemory[nf.Key][nf.Value] = 0
		}
	}
282

Mustafa Gezen's avatar
Mustafa Gezen committed
283
284
285
286
287
	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)
288
289
290
291
			}
		}
	}

292
	for lineNum, line := range lines {
293
294
295
296
		inLoopSourceNum := lastSourceNum
		inLoopPatchNum := lastPatchNum
		prefixLine := strings.TrimSpace(line)

Mustafa Gezen's avatar
Mustafa Gezen committed
297
		for i, additions := range futureAdditions {
298
			if lineNum == i {
Mustafa Gezen's avatar
Mustafa Gezen committed
299
300
301
				for _, addition := range additions {
					newLines = append(newLines, addition)
				}
302
303
304
			}
		}

305
306
307
308
309
310
311
		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
312
				inField = "Source"
313
			} else if field == lastPatch {
Mustafa Gezen's avatar
Mustafa Gezen committed
314
				inField = "Patch"
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
			}

			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
331
332
333
			for _, appendOp := range cfg.SpecChange.Append {
				if field == appendOp.Field {
					value = value + appendOp.Value
334
335
336
337

					if field == "Release" {
						version = version + appendOp.Value
					}
Mustafa Gezen's avatar
Mustafa Gezen committed
338
339
340
				}
			}

341
342
343
344
345
346
347
348
			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
349
				in:            &inField,
Mustafa Gezen's avatar
Mustafa Gezen committed
350
351
				expectedField: "Source",
				operation:     srpmprocpb.SpecChange_FileOperation_Source,
352
353
354
355
356
357
358
359
360
361
362
			})
			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
363
				in:            &inField,
364
				expectedField: "Patch",
Mustafa Gezen's avatar
Mustafa Gezen committed
365
				operation:     srpmprocpb.SpecChange_FileOperation_Patch,
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
			})
			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
382
				in:            &inField,
383
384
385
386
387
388
				operation:     srpmprocpb.SpecChange_FileOperation_Source,
			})
			if err != nil {
				return err
			}

Mustafa Gezen's avatar
Mustafa Gezen committed
389
			if executed && !hasPatch {
390
				newLines = append(newLines, "")
Mustafa Gezen's avatar
Mustafa Gezen committed
391
				inField = "Patch"
392
393
394
395
396
397
398
399
400
			}

			executed, err = sourcePatchOperationAfterLoop(&sourcePatchOperationAfterLoopRequest{
				cfg:           cfg,
				inLoopNum:     inLoopPatchNum,
				lastNum:       &lastPatchNum,
				longestField:  longestField,
				newLines:      &newLines,
				expectedField: "Patch",
Mustafa Gezen's avatar
Mustafa Gezen committed
401
				in:            &inField,
402
403
404
405
406
407
				operation:     srpmprocpb.SpecChange_FileOperation_Patch,
			})
			if err != nil {
				return err
			}

Mustafa Gezen's avatar
Mustafa Gezen committed
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
			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)
					}
				}
			}

428
429
430
			if executed && !strings.Contains(specStr, "%changelog") {
				newLines = append(newLines, "")
				newLines = append(newLines, "%changelog")
431
				inSection = sectionChangelog
432
433
			}

434
			if inSection == sectionChangelog {
435
436
437
438
439
440
441
442
				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, "")
				}
443
				inSection = ""
444
445
446
447
			} else {
				line = searchAndReplaceLine(line, cfg.SpecChange.SearchAndReplace)
			}

448
449
450
451
452
453
454
			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
455
456
							if strSliceContains(sections, strings.TrimSpace(x)) {
								insertedLine = lineNum + i
Mustafa Gezen's avatar
Mustafa Gezen committed
457
								setFASlice(futureAdditions, insertedLine, appendOp.Value)
458
459
460
461
462
463
464
								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
465
									setFASlice(futureAdditions, insertedLine, appendOp.Value)
466
467
468
469
470
471
									break
								}
							}
						}
					}
				}
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
			}

			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
}