Skip to content

Commit

Permalink
Enable build chaching for s2i local build
Browse files Browse the repository at this point in the history
Signed-off-by: Matej Vašek <[email protected]>
  • Loading branch information
matejvasek committed Nov 19, 2024
1 parent 2fd4982 commit f5d96a7
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions pkg/builders/s2i/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package s2i
import (
"archive/tar"
"context"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -256,6 +258,12 @@ func (b *Builder) Build(ctx context.Context, f fn.Function, platforms []fn.Platf
// s2i apparently is not excluding the files in --as-dockerfile mode
exclude := regexp.MustCompile(cfg.ExcludeRegExp)

// patch dockerfile to using cache mount
err = patchDockerfile(cfg.AsDockerfile, f)
if err != nil {
return err
}

const up = ".." + string(os.PathSeparator)
go func() {
tw := tar.NewWriter(pw)
Expand Down Expand Up @@ -356,6 +364,20 @@ func (b *Builder) Build(ctx context.Context, f fn.Function, platforms []fn.Platf
return jsonmessage.DisplayJSONMessagesStream(resp.Body, out, fd, isTerminal, nil)
}

func patchDockerfile(path string, f fn.Function) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
re := regexp.MustCompile(`RUN (.*assemble)`)
s := sha1.Sum([]byte(f.Root))
mountCmd := "--mount=type=cache,target=/tmp/artifacts/,uid=1001,id=" + hex.EncodeToString(s[:8])
replacement := fmt.Sprintf("RUN %s \\\n $1", mountCmd)
newDockerFileStr := re.ReplaceAllString(string(data), replacement)

return os.WriteFile(path, []byte(newDockerFileStr), 0644)
}

func s2iScriptURL(ctx context.Context, cli DockerClient, image string) (string, error) {
img, _, err := cli.ImageInspectWithRaw(ctx, image)
if err != nil {
Expand Down

0 comments on commit f5d96a7

Please sign in to comment.