github.com/craftyguy/u-root@v1.0.0/cmds/tee/tee.go (about)

     1  // Copyright 2013-2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Tee transcribes the standard input to the standard output and makes copies
     6  // in the files.
     7  //
     8  // Synopsis:
     9  //     tee [-ai] FILES...
    10  //
    11  // Options:
    12  //     -a: append the output to the files rather than rewriting them
    13  //     -i: ignore the SIGINT signal
    14  package main
    15  
    16  import (
    17  	"bufio"
    18  	"flag"
    19  	"io"
    20  	"log"
    21  	"os"
    22  	"os/signal"
    23  )
    24  
    25  var (
    26  	cat    = flag.Bool("a", false, "append the output to the files rather than rewriting them")
    27  	ignore = flag.Bool("i", false, "ignore the SIGINT signal")
    28  )
    29  
    30  // Copy any input from buffer to Stdout and files
    31  func copyinput(files []io.Writer, buf []byte) error {
    32  	for _, v := range files {
    33  		if _, err := v.Write(buf); err != nil {
    34  			return err
    35  		}
    36  	}
    37  	return nil
    38  }
    39  
    40  // Parses all the flags and sets variables accordingly
    41  func handleflags() int {
    42  	flag.Parse()
    43  
    44  	oflags := os.O_WRONLY | os.O_CREATE
    45  
    46  	if *cat {
    47  		oflags |= os.O_APPEND
    48  	}
    49  
    50  	if *ignore {
    51  		signal.Ignore(os.Interrupt)
    52  	}
    53  
    54  	return oflags
    55  }
    56  
    57  func main() {
    58  	oflags := handleflags()
    59  
    60  	files := make([]io.Writer, flag.NArg())
    61  
    62  	for i, v := range flag.Args() {
    63  		f, err := os.OpenFile(v, oflags, 0666)
    64  		if err != nil {
    65  			log.Fatalf("error opening %s: %v", v, err)
    66  		}
    67  		files[i] = f
    68  	}
    69  
    70  	b := make([]byte, 1048576)
    71  	files = append(files, os.Stdout)
    72  	buf := bufio.NewReader(os.Stdin)
    73  
    74  	for {
    75  		if n, err := buf.Read(b[:]); err != nil {
    76  			log.Fatalf("%v", err)
    77  		} else {
    78  			copyinput(files, b[:n])
    79  		}
    80  	}
    81  }