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>
This commit is contained in:
Brian Goff 2023-03-30 00:00:03 +00:00
parent ccae6e9299
commit efd011b793
1 changed files with 36 additions and 32 deletions

View File

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