replace.go 1.73 KB
Newer Older
Mustafa Gezen's avatar
Mustafa Gezen committed
1
2
3
package directives

import (
4
5
	"errors"
	"fmt"
6
	"git.rockylinux.org/release-engineering/public/srpmproc/internal/data"
7
	srpmprocpb "git.rockylinux.org/release-engineering/public/srpmproc/pb"
Mustafa Gezen's avatar
Mustafa Gezen committed
8
9
10
11
12
	"github.com/go-git/go-git/v5"
	"io/ioutil"
	"os"
)

13
func replace(cfg *srpmprocpb.Cfg, _ *data.ProcessData, _ *data.ModeData, patchTree *git.Worktree, pushTree *git.Worktree) error {
Mustafa Gezen's avatar
Mustafa Gezen committed
14
15
16
17
	for _, replace := range cfg.Replace {
		filePath := checkAddPrefix(replace.File)
		stat, err := pushTree.Filesystem.Stat(filePath)
		if replace.File == "" || err != nil {
18
			return errors.New(fmt.Sprintf("INVALID_FILE:%s", filePath))
Mustafa Gezen's avatar
Mustafa Gezen committed
19
20
21
22
		}

		err = pushTree.Filesystem.Remove(filePath)
		if err != nil {
23
			return errors.New(fmt.Sprintf("COULD_NOT_REMOVE_OLD_FILE:%s", filePath))
Mustafa Gezen's avatar
Mustafa Gezen committed
24
25
26
27
		}

		f, err := pushTree.Filesystem.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, stat.Mode())
		if err != nil {
28
			return errors.New(fmt.Sprintf("COULD_NOT_OPEN_REPLACEMENT:%s", filePath))
Mustafa Gezen's avatar
Mustafa Gezen committed
29
30
31
32
33
34
		}

		switch replacing := replace.Replacing.(type) {
		case *srpmprocpb.Replace_WithFile:
			fPatch, err := patchTree.Filesystem.OpenFile(replacing.WithFile, os.O_RDONLY, 0644)
			if err != nil {
35
				return errors.New(fmt.Sprintf("COULD_NOT_OPEN_REPLACING:%s", replacing.WithFile))
Mustafa Gezen's avatar
Mustafa Gezen committed
36
37
38
39
			}

			replacingBytes, err := ioutil.ReadAll(fPatch)
			if err != nil {
40
				return errors.New(fmt.Sprintf("COULD_NOT_READ_REPLACING:%s", replacing.WithFile))
Mustafa Gezen's avatar
Mustafa Gezen committed
41
42
43
44
			}

			_, err = f.Write(replacingBytes)
			if err != nil {
45
				return errors.New(fmt.Sprintf("COULD_NOT_WRITE_REPLACING:%s", replacing.WithFile))
Mustafa Gezen's avatar
Mustafa Gezen committed
46
47
48
49
50
			}
			break
		case *srpmprocpb.Replace_WithInline:
			_, err := f.Write([]byte(replacing.WithInline))
			if err != nil {
51
				return errors.New(fmt.Sprintf("COULD_NOT_WRITE_INLINE:%s", filePath))
Mustafa Gezen's avatar
Mustafa Gezen committed
52
53
54
55
			}
			break
		}
	}
56
57

	return nil
Mustafa Gezen's avatar
Mustafa Gezen committed
58
}