cp: reduce branching in progress printer

This just makes it easier to reason about what is happening.

Signed-off-by: Brian Goff <cpuguy83@gmail.com>
(cherry picked from commit efd011b793)
Signed-off-by: Brian Goff <cpuguy83@gmail.com>
This commit is contained in:
Brian Goff 2023-03-30 00:00:03 +00:00
parent f813c9639f
commit 948dfa91c9
1 changed files with 36 additions and 32 deletions

View File

@ -49,35 +49,39 @@ type cpConfig struct {
// copying files to/from a container.
type copyProgressPrinter struct {
io.ReadCloser
toContainer bool
total *float64
writer io.Writer
isTerm bool
header string
}
const (
copyToContainerHeader = "Copying to container - "
copyFromContainerHeader = "Copying from container - "
)
func (pt *copyProgressPrinter) Read(p []byte) (int, error) {
n, err := pt.ReadCloser.Read(p)
if n > 0 {
isFirst := *pt.total == 0
if n > 0 {
*pt.total += float64(n)
if pt.isTerm {
var header string
if pt.toContainer {
header = "Copying to container - "
} else {
header = "Copying from container - "
}
if err != nil && err != io.EOF {
return n, err
}
if !pt.isTerm {
return n, err
}
if isFirst {
fmt.Fprint(pt.writer, aec.Restore)
fmt.Fprint(pt.writer, aec.EraseLine(aec.EraseModes.All))
fmt.Fprint(pt.writer, header)
fmt.Fprint(pt.writer, pt.header)
}
fmt.Fprint(pt.writer, aec.Column(uint(len(header)+1)))
fmt.Fprint(pt.writer, aec.Column(uint(len(pt.header)+1)))
fmt.Fprint(pt.writer, aec.EraseLine(aec.EraseModes.Tail))
fmt.Fprint(pt.writer, units.HumanSize(*pt.total))
}
}
return n, err
}
@ -229,10 +233,10 @@ func copyFromContainer(ctx context.Context, dockerCli command.Cli, copyConfig cp
if !copyConfig.quiet {
content = &copyProgressPrinter{
ReadCloser: content,
toContainer: false,
writer: dockerCli.Err(),
total: &copiedSize,
isTerm: stderrIsTerm,
header: copyFromContainerHeader,
}
}
@ -361,10 +365,10 @@ func copyToContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpCo
if !copyConfig.quiet {
content = &copyProgressPrinter{
ReadCloser: content,
toContainer: true,
writer: dockerCli.Err(),
total: &copiedSize,
isTerm: stderrIsTerm,
header: copyToContainerHeader,
}
}
}