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)
if n > 0 {
isFirst := *pt.total == 0 isFirst := *pt.total == 0
if n > 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 err != nil && err != io.EOF {
return n, err
}
if !pt.isTerm {
return n, err
}
if isFirst { if isFirst {
fmt.Fprint(pt.writer, aec.Restore) fmt.Fprint(pt.writer, aec.Restore)
fmt.Fprint(pt.writer, aec.EraseLine(aec.EraseModes.All)) 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, aec.EraseLine(aec.EraseModes.Tail))
fmt.Fprint(pt.writer, units.HumanSize(*pt.total)) fmt.Fprint(pt.writer, units.HumanSize(*pt.total))
}
}
return n, err return n, err
} }
@ -229,10 +233,10 @@ func copyFromContainer(ctx context.Context, dockerCli command.Cli, copyConfig cp
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,
} }
} }
@ -361,10 +365,10 @@ func copyToContainer(ctx context.Context, dockerCli command.Cli, copyConfig cpCo
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,
} }
} }
} }