Skip to content

Commit 56746fe

Browse files
authored
fix(tar): data race fix (#9309)
* fix(tar): data race fix * linters tar.go
1 parent a2f4043 commit 56746fe

File tree

1 file changed

+23
-13
lines changed

1 file changed

+23
-13
lines changed

pkg/skaffold/util/tar.go

+23-13
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,20 @@ import (
3333

3434
type headerModifier func(*tar.Header)
3535

36+
type cancelableWriter struct {
37+
w io.Writer
38+
ctx context.Context
39+
}
40+
41+
func (cw *cancelableWriter) Write(p []byte) (n int, err error) {
42+
select {
43+
case <-cw.ctx.Done():
44+
return 0, cw.ctx.Err()
45+
default:
46+
return cw.w.Write(p)
47+
}
48+
}
49+
3650
func CreateMappedTar(ctx context.Context, w io.Writer, root string, pathMap map[string][]string) error {
3751
tw := tar.NewWriter(w)
3852
defer tw.Close()
@@ -173,21 +187,17 @@ func addFileToTar(ctx context.Context, root string, src string, dst string, tw *
173187
return err
174188
}
175189
defer f.Close()
176-
errChan := make(chan error, 1)
177190

178-
go func() {
179-
_, err := io.Copy(tw, f)
180-
if err != nil {
181-
errChan <- fmt.Errorf("writing real file %q: %w", src, err)
182-
}
183-
errChan <- nil
184-
}()
191+
if ctx.Err() != nil {
192+
return ctx.Err()
193+
}
185194

186-
select {
187-
case <-ctx.Done():
188-
return fmt.Errorf("writing real file %q: %w", src, ctx.Err())
189-
case err := <-errChan:
190-
return err
195+
// Wrap the tar.Writer in a cancelableWriter that checks the context
196+
cw := &cancelableWriter{w: tw, ctx: ctx}
197+
198+
// Proceed with copying the file content using the cancelable writer
199+
if _, err := io.Copy(cw, f); err != nil {
200+
return fmt.Errorf("writing real file %q: %w", src, err)
191201
}
192202
}
193203

0 commit comments

Comments
 (0)