forked from xeals/signal-back
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
109 lines (92 loc) · 2.27 KB
/
util.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package cmd
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/pkg/errors"
"github.com/urfave/cli"
"github.com/xeals/signal-back/types"
)
// AppHelp is the help template.
const AppHelp = `Usage: {{.HelpName}} COMMAND [OPTION...] BACKUPFILE
{{range .Flags}}{{.}}
{{end}}{{if .Commands}}
Commands:
{{range .Commands}} {{index .Names 0}}{{ "\t"}}{{.Usage}}
{{end}}{{end}}
`
// TODO: Work out how to display global flags here
// SubcommandHelp is the subcommand help template.
const SubcommandHelp = `Usage: {{.HelpName}} [OPTION...] BACKUPFILE
{{if .UsageText}}{{.UsageText}}
{{else}}{{.Usage}}
{{end}}{{if .Flags}}
{{range .Flags}}{{.}}
{{end}}{{end}}
`
var coreFlags = []cli.Flag{
cli.StringFlag{
Name: "password, p",
Usage: "use `PASS` as password for backup file",
},
cli.StringFlag{
Name: "pwdfile, P",
Usage: "read password from `FILE`",
},
cli.BoolFlag{
Name: "verbose, v",
Usage: "enable verbose logging output",
},
}
func setup(c *cli.Context) (*types.BackupFile, error) {
// -- Enable logging
if c.Bool("verbose") {
log.SetOutput(os.Stderr)
} else {
log.SetOutput(ioutil.Discard)
}
// -- Verify
if c.Args().Get(0) == "" {
return nil, errors.New("must specify a Signal backup file")
}
// -- Initialise
pass, err := readPassword(c)
if err != nil {
return nil, errors.Wrap(err, "unable to read password")
}
bf, err := types.NewBackupFile(c.Args().Get(0), pass)
if err != nil {
return nil, errors.Wrap(err, "failed to open backup file")
}
return bf, nil
}
func readPassword(c *cli.Context) (string, error) {
var pass string
if c.String("password") != "" {
pass = c.String("password")
} else if c.String("pwdfile") != "" {
bs, err := ioutil.ReadFile(c.String("pwdfile"))
if err != nil {
return "", errors.Wrap(err, "unable to read file")
}
pass = string(bs)
} else {
r := bufio.NewReader(os.Stdin)
fmt.Fprint(os.Stderr, "Password: ")
t, err := r.ReadString('\n')
if err != nil {
return "", errors.Wrap(err, "unable to read from stdin")
}
pass = t
}
return pass, nil
}
// E is a wrapper to simply create a cli.ExitError.
func E(err error, msg string, code int) *cli.ExitError {
if err == nil {
return cli.NewExitError(errors.New(msg), code)
}
return cli.NewExitError(errors.Wrap(err, msg), code)
}