gopkg.in/dedis/onet.v2@v2.0.0-20181115163211-c8f3724038a7/app/io.go (about)

     1  package app
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"os/user"
     9  	"path"
    10  	"strings"
    11  
    12  	"gopkg.in/dedis/onet.v2/log"
    13  )
    14  
    15  var in *bufio.Reader
    16  var out io.Writer
    17  
    18  func init() {
    19  	in = bufio.NewReader(os.Stdin)
    20  	out = os.Stdout
    21  }
    22  
    23  // TildeToHome takes a path and replaces an eventual "~" with the home-directory.
    24  // If the user-directory is not defined it will return a path relative to the
    25  // root-directory "/".
    26  func TildeToHome(path string) string {
    27  	if strings.HasPrefix(path, "~/") {
    28  		usr, err := user.Current()
    29  		log.ErrFatal(err, "Got error while fetching home-directory")
    30  		return usr.HomeDir + path[1:]
    31  	}
    32  	return path
    33  }
    34  
    35  // Input prints the arguments given with an 'input'-format and
    36  // proposes the 'def' string as default. If the user presses
    37  // 'enter', the 'dev' will be returned.
    38  // In the case of an error it will Fatal.
    39  func Input(def string, args ...interface{}) string {
    40  	fmt.Fprintln(out)
    41  	fmt.Fprint(out, args...)
    42  	fmt.Fprintf(out, " [%s]: ", def)
    43  	str, err := in.ReadString('\n')
    44  	if err != nil {
    45  		log.Fatal("Could not read input.")
    46  	}
    47  	str = strings.TrimSpace(str)
    48  	if str == "" {
    49  		return def
    50  	}
    51  	return str
    52  }
    53  
    54  // Inputf takes a format string and arguments and calls
    55  // Input.
    56  func Inputf(def string, f string, args ...interface{}) string {
    57  	return Input(def, fmt.Sprintf(f, args...))
    58  }
    59  
    60  // InputYN asks a Yes/No question. Anything else than upper/lower-case
    61  // 'y' will be interpreted as no.
    62  func InputYN(def bool, args ...interface{}) bool {
    63  	defStr := "Yn"
    64  	if !def {
    65  		defStr = "Ny"
    66  	}
    67  	return strings.ToLower(string(Input(defStr, args...)[0])) == "y"
    68  }
    69  
    70  // Copy makes a copy of a local file with the same file-mode-bits set.
    71  func Copy(dst, src string) error {
    72  	info, err := os.Stat(dst)
    73  	if err == nil && info.IsDir() {
    74  		return Copy(path.Join(dst, path.Base(src)), src)
    75  	}
    76  	fSrc, err := os.Open(src)
    77  	if err != nil {
    78  		return err
    79  	}
    80  	defer fSrc.Close()
    81  	stat, err := fSrc.Stat()
    82  	if err != nil {
    83  		return err
    84  	}
    85  	fDst, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR, stat.Mode())
    86  	if err != nil {
    87  		return err
    88  	}
    89  	defer fDst.Close()
    90  	_, err = io.Copy(fDst, fSrc)
    91  	return err
    92  }