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