github.com/BIG5Concepts/forego@v0.16.1/outlet.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"github.com/ddollar/forego/Godeps/_workspace/src/github.com/daviddengcn/go-colortext"
     8  	"io"
     9  	"os"
    10  	"sync"
    11  )
    12  
    13  type OutletFactory struct {
    14  	Padding int
    15  
    16  	sync.Mutex
    17  }
    18  
    19  var colors = []ct.Color{
    20  	ct.Cyan,
    21  	ct.Yellow,
    22  	ct.Green,
    23  	ct.Magenta,
    24  	ct.Red,
    25  	ct.Blue,
    26  }
    27  
    28  func NewOutletFactory() (of *OutletFactory) {
    29  	return new(OutletFactory)
    30  }
    31  
    32  func (of *OutletFactory) LineReader(wg *sync.WaitGroup, name string, index int, r io.Reader, isError bool) {
    33  	defer wg.Done()
    34  
    35  	color := colors[index%len(colors)]
    36  
    37  	reader := bufio.NewReader(r)
    38  
    39  	var buffer bytes.Buffer
    40  
    41  	for {
    42  		buf := make([]byte, 1024)
    43  		v, _ := reader.Read(buf)
    44  
    45  		if v == 0 {
    46  			return
    47  		}
    48  
    49  		idx := bytes.IndexByte(buf, '\n')
    50  		if idx >= 0 {
    51  			buffer.Write(buf[0:idx])
    52  			of.WriteLine(name, buffer.String(), color, ct.None, isError)
    53  			buffer.Reset()
    54  		} else {
    55  			buffer.Write(buf)
    56  		}
    57  	}
    58  }
    59  
    60  func (of *OutletFactory) SystemOutput(str string) {
    61  	of.WriteLine("forego", str, ct.White, ct.None, false)
    62  }
    63  
    64  func (of *OutletFactory) ErrorOutput(str string) {
    65  	fmt.Printf("ERROR: %s\n", str)
    66  	os.Exit(1)
    67  }
    68  
    69  // Write out a single coloured line
    70  func (of *OutletFactory) WriteLine(left, right string, leftC, rightC ct.Color, isError bool) {
    71  	of.Lock()
    72  	defer of.Unlock()
    73  
    74  	ct.ChangeColor(leftC, true, ct.None, false)
    75  	formatter := fmt.Sprintf("%%-%ds | ", of.Padding)
    76  	fmt.Printf(formatter, left)
    77  
    78  	if isError {
    79  		ct.ChangeColor(ct.Red, true, ct.None, true)
    80  	} else {
    81  		ct.ResetColor()
    82  	}
    83  	fmt.Println(right)
    84  	if isError {
    85  		ct.ResetColor()
    86  	}
    87  }