chore: refactor duplication

This commit is contained in:
Pasha Sviderski
2025-09-30 15:42:01 +10:00
parent 6b758c810e
commit ae458d260f
+13 -39
View File
@@ -36,37 +36,8 @@ func (cli *Client) PullImage(
return nil, err return nil, err
} }
decoder := json.NewDecoder(respBody)
ch := make(chan PullPushImageMessage) ch := make(chan PullPushImageMessage)
go processPullPushImageResp(ctx, respBody, ch)
go func() {
defer respBody.Close()
defer close(ch)
for {
var jm jsonmessage.JSONMessage
if err = decoder.Decode(&jm); err != nil {
if errors.Is(err, io.EOF) {
break
}
ch <- PullPushImageMessage{Err: fmt.Errorf("decode image pull message: %w", err)}
break
}
msg := PullPushImageMessage{Message: jm}
if jm.Error != nil {
msg.Err = errors.New(jm.Error.Message)
}
select {
case <-ctx.Done():
ch <- PullPushImageMessage{Err: ctx.Err()}
return
default:
ch <- msg
}
}
}()
return ch, nil return ch, nil
} }
@@ -87,21 +58,27 @@ func (cli *Client) PushImage(
return nil, err return nil, err
} }
decoder := json.NewDecoder(respBody)
ch := make(chan PullPushImageMessage) ch := make(chan PullPushImageMessage)
go processPullPushImageResp(ctx, respBody, ch)
go func() { return ch, nil
}
// processPullPushImageResp decodes JSON messages from the image pull/push response body and
// sends them to the provided channel.
func processPullPushImageResp(ctx context.Context, respBody io.ReadCloser, ch chan<- PullPushImageMessage) {
defer respBody.Close() defer respBody.Close()
defer close(ch) defer close(ch)
decoder := json.NewDecoder(respBody)
for { for {
var jm jsonmessage.JSONMessage var jm jsonmessage.JSONMessage
if err = decoder.Decode(&jm); err != nil { if err := decoder.Decode(&jm); err != nil {
if errors.Is(err, io.EOF) { if errors.Is(err, io.EOF) {
break return
} }
ch <- PullPushImageMessage{Err: fmt.Errorf("decode image push message: %w", err)} ch <- PullPushImageMessage{Err: fmt.Errorf("decode image pull/push message: %w", err)}
break return
} }
msg := PullPushImageMessage{Message: jm} msg := PullPushImageMessage{Message: jm}
@@ -117,9 +94,6 @@ func (cli *Client) PushImage(
ch <- msg ch <- msg
} }
} }
}()
return ch, nil
} }
// RetrieveLocalDockerRegistryAuth retrieves the authentication token for the specified image from the local Docker // RetrieveLocalDockerRegistryAuth retrieves the authentication token for the specified image from the local Docker