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

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

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

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

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

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

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

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

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