github.com/coreos/mantle@v0.13.0/util/logio.go (about)

     1  // Copyright 2015 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"bufio"
    19  	"fmt"
    20  	"io"
    21  	"os"
    22  
    23  	"github.com/coreos/ioprogress"
    24  	"github.com/coreos/pkg/capnslog"
    25  )
    26  
    27  var plog = capnslog.NewPackageLogger("github.com/coreos/mantle", "util")
    28  
    29  // LogFrom reads lines from reader r and sends them to logger l.
    30  func LogFrom(l capnslog.LogLevel, r io.Reader) {
    31  	scanner := bufio.NewScanner(r)
    32  	for scanner.Scan() {
    33  		plog.Log(l, scanner.Text())
    34  	}
    35  	if err := scanner.Err(); err != nil {
    36  		plog.Errorf("Reading %s failed: %v", r, err)
    37  	}
    38  }
    39  
    40  // CopyProgress copies data from reader into writter, logging progress through level.
    41  func CopyProgress(level capnslog.LogLevel, prefix string, writer io.Writer, reader io.Reader, total int64) (int64, error) {
    42  	// TODO(marineam): would be nice to support this natively in
    43  	// capnslog so the right output stream and formatter are used.
    44  	if plog.LevelAt(level) {
    45  		// ripped off from rkt, so another reason to add to capnslog
    46  		fmtBytesSize := 18
    47  		barSize := int64(80 - len(prefix) - fmtBytesSize)
    48  		bar := ioprogress.DrawTextFormatBarForW(barSize, os.Stderr)
    49  		fmtfunc := func(progress, total int64) string {
    50  			if total < 0 {
    51  				return fmt.Sprintf(
    52  					"%s: %v of an unknown total size",
    53  					prefix,
    54  					ioprogress.ByteUnitStr(progress),
    55  				)
    56  			}
    57  			return fmt.Sprintf(
    58  				"%s: %s %s",
    59  				prefix,
    60  				bar(progress, total),
    61  				ioprogress.DrawTextFormatBytes(progress, total),
    62  			)
    63  		}
    64  
    65  		reader = &ioprogress.Reader{
    66  			Reader:   reader,
    67  			Size:     total,
    68  			DrawFunc: ioprogress.DrawTerminalf(os.Stderr, fmtfunc),
    69  		}
    70  	}
    71  
    72  	return io.Copy(writer, reader)
    73  }