gitlab.com/apertussolutions/u-root@v7.0.0+incompatible/cmds/core/echo/echo.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  // echo writes its arguments separated by blanks and terminated by a newline on
     6  // the standard output.
     7  //
     8  // Synopsis:
     9  //     echo [-e] [-n] [-E] [STRING]...
    10  package main
    11  
    12  import (
    13  	"flag"
    14  	"fmt"
    15  	"io"
    16  	"os"
    17  	"strings"
    18  )
    19  
    20  type flags struct {
    21  	noNewline, interpretEscapes bool
    22  }
    23  
    24  func escapeString(s string) (string, error) {
    25  	if len(s) < 1 {
    26  		return "", nil
    27  	}
    28  
    29  	s = strings.Split(s, "\\c")[0]
    30  	s = strings.Replace(s, "\\0", "\\", -1)
    31  
    32  	// Quote the string and scan it through %q to interpret backslash escapes
    33  	s = fmt.Sprintf("\"%s\"", s)
    34  	_, err := fmt.Sscanf(s, "%q", &s)
    35  	if err != nil {
    36  		return "", err
    37  	}
    38  
    39  	return s, nil
    40  }
    41  
    42  func echo(f flags, w io.Writer, s ...string) error {
    43  	var err error
    44  	line := strings.Join(s, " ")
    45  	if f.interpretEscapes {
    46  		line, err = escapeString(line)
    47  		if err != nil {
    48  			return err
    49  		}
    50  
    51  	}
    52  
    53  	format := "%s"
    54  	if !f.noNewline {
    55  		format += "\n"
    56  	}
    57  	_, err = fmt.Fprintf(w, format, line)
    58  
    59  	return err
    60  }
    61  
    62  func init() {
    63  	defUsage := flag.Usage
    64  	flag.Usage = func() {
    65  		defUsage()
    66  		fmt.Println(`
    67    If -e is in effect, the following sequences are recognized:
    68      \\     backslash
    69      \a     alert (BEL)
    70      \b     backspace
    71      \c     produce no further output
    72      \e     escape
    73      \f     form feed
    74      \n     new line
    75      \r     carriage return
    76      \t     horizontal tab
    77      \v     vertical tab
    78      \0NNN  byte with octal value NNN (1 to 3 digits)
    79      \xHH   byte with hexadecimal value HH (1 to 2 digits)`)
    80  	}
    81  }
    82  
    83  func main() {
    84  	var (
    85  		f flags
    86  		E bool
    87  	)
    88  	flag.BoolVar(&f.noNewline, "n", false, "suppress newline")
    89  	flag.BoolVar(&f.interpretEscapes, "e", true, "enable interpretation of backslash escapes (default)")
    90  	flag.BoolVar(&E, "E", false, "disable interpretation of backslash escapes")
    91  	flag.Parse()
    92  	if E {
    93  		f.interpretEscapes = false
    94  	}
    95  
    96  	err := echo(f, os.Stdout, flag.Args()...)
    97  	if err != nil {
    98  		fmt.Fprintf(os.Stderr, "%s", err)
    99  		os.Exit(1)
   100  	}
   101  }