gitlab.com/apertussolutions/u-root@v7.0.0+incompatible/cmds/core/tee/tee.go (about)

     1  // Copyright 2013-2018 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: append the output to the files rather than rewriting them
    13  //     -i, --ignore-interrupts: ignore the SIGINT signal
    14  package main
    15  
    16  import (
    17  	"fmt"
    18  	"io"
    19  	"log"
    20  	"os"
    21  	"os/signal"
    22  
    23  	flag "github.com/spf13/pflag"
    24  )
    25  
    26  const name = "tee"
    27  
    28  var (
    29  	cat    = flag.BoolP("append", "a", false, "append the output to the files rather than rewriting them")
    30  	ignore = flag.BoolP("ignore-interrupts", "i", false, "ignore the SIGINT signal")
    31  )
    32  
    33  // handeFlags parses all the flags and sets variables accordingly
    34  func handleFlags() int {
    35  	flag.Parse()
    36  
    37  	oflags := os.O_WRONLY | os.O_CREATE
    38  
    39  	if *cat {
    40  		oflags |= os.O_APPEND
    41  	}
    42  
    43  	if *ignore {
    44  		signal.Ignore(os.Interrupt)
    45  	}
    46  
    47  	return oflags
    48  }
    49  
    50  func main() {
    51  	oflags := handleFlags()
    52  
    53  	files := make([]*os.File, 0, flag.NArg())
    54  	writers := make([]io.Writer, 0, flag.NArg()+1)
    55  	for _, fname := range flag.Args() {
    56  		f, err := os.OpenFile(fname, oflags, 0666)
    57  		if err != nil {
    58  			log.Fatalf("%s: error opening %s: %v", name, fname, err)
    59  		}
    60  		files = append(files, f)
    61  		writers = append(writers, f)
    62  	}
    63  	writers = append(writers, os.Stdout)
    64  
    65  	mw := io.MultiWriter(writers...)
    66  	if _, err := io.Copy(mw, os.Stdin); err != nil {
    67  		log.Fatalf("%s: error: %v", name, err)
    68  	}
    69  
    70  	for _, f := range files {
    71  		if err := f.Close(); err != nil {
    72  			fmt.Fprintf(os.Stderr, "%s: error closing file %q: %v\n", name, f.Name(), err)
    73  		}
    74  	}
    75  }