/
ioutils.go
95 lines (82 loc) · 2.37 KB
/
ioutils.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
93
94
95
package ioutils
import (
"bufio"
"fmt"
"io"
"os"
"strings"
"syscall"
"github.com/jfrog/jfrog-cli-core/utils/coreutils"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"golang.org/x/crypto/ssh/terminal"
)
// disallowUsingSavedPassword - Prevent changing username or url without changing the password.
// False iff the user changed the username or the url.
func ReadCredentialsFromConsole(details, savedDetails coreutils.Credentials, disallowUsingSavedPassword bool) error {
if details.GetUser() == "" {
tempUser := ""
ScanFromConsole("JFrog username", &tempUser, savedDetails.GetUser())
details.SetUser(tempUser)
disallowUsingSavedPassword = true
}
if details.GetPassword() == "" {
password, err := ScanPasswordFromConsole("JFrog password or API key: ")
if err != nil {
return err
}
details.SetPassword(password)
if details.GetPassword() == "" && !disallowUsingSavedPassword {
details.SetPassword(savedDetails.GetPassword())
}
}
return nil
}
func ScanPasswordFromConsole(message string) (string, error) {
print(message)
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", errorutils.CheckError(err)
}
// New-line required after the password input:
fmt.Println()
return string(bytePassword), nil
}
func ScanFromConsole(caption string, scanInto *string, defaultValue string) {
if defaultValue != "" {
print(caption + " [" + defaultValue + "]: ")
} else {
print(caption + ": ")
}
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
*scanInto = scanner.Text()
if *scanInto == "" {
*scanInto = defaultValue
}
*scanInto = strings.TrimSpace(*scanInto)
}
func CopyFile(src, dst string, fileMode os.FileMode) error {
from, err := os.Open(src)
if err != nil {
return errorutils.CheckError(err)
}
defer from.Close()
to, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE, fileMode)
if err != nil {
return errorutils.CheckError(err)
}
defer to.Close()
if _, err = io.Copy(to, from); err != nil {
return errorutils.CheckError(err)
}
return errorutils.CheckError(os.Chmod(dst, fileMode))
}
func DoubleWinPathSeparator(filePath string) string {
return strings.Replace(filePath, "\\", "\\\\", -1)
}
func UnixToWinPathSeparator(filePath string) string {
return strings.Replace(filePath, "/", "\\\\", -1)
}
func WinToUnixPathSeparator(filePath string) string {
return strings.Replace(filePath, "\\", "/", -1)
}