-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
117 lines (96 loc) · 2.21 KB
/
app.go
File metadata and controls
117 lines (96 loc) · 2.21 KB
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
110
111
112
113
114
115
116
117
package main
import (
"errors"
"flag"
"fmt"
"io"
"os"
"runtime"
"strings"
)
type App struct {
out io.Writer
err io.Writer
}
type cliOptions struct {
showHelp bool
doExport bool
importPath string
}
func NewApp(out, err io.Writer) *App {
return &App{
out: out,
err: err,
}
}
func (a *App) Run(args []string) int {
opts, err := parseCLIArgs(args)
if err != nil {
a.printError(err)
return 1
}
if opts.showHelp {
renderHelp(a.out)
return 0
}
if runtime.GOOS != "darwin" {
a.printError(errors.New("zensync currently supports macOS only"))
return 1
}
if os.Geteuid() == 0 {
a.printError(errors.New("do not run zensync with sudo/root; run it as your normal macOS user"))
return 1
}
renderLogo(a.out)
if opts.doExport {
if err := exportZen(a.out); err != nil {
a.printError(err)
return 1
}
return 0
}
if err := importZen(a.out, opts.importPath); err != nil {
a.printError(err)
return 1
}
return 0
}
func (a *App) printError(err error) {
fmt.Fprintf(a.err, "Error: %s\n", err)
fmt.Fprintln(a.err, "Run `zensync --help` to see commands.")
}
func parseCLIArgs(args []string) (cliOptions, error) {
if len(args) == 0 {
return cliOptions{showHelp: true}, nil
}
if len(args) == 1 {
switch args[0] {
case "help", "commands":
return cliOptions{showHelp: true}, nil
}
}
fs := flag.NewFlagSet("zensync", flag.ContinueOnError)
fs.SetOutput(io.Discard)
showHelp := fs.Bool("help", false, "Show help")
showHelpShort := fs.Bool("h", false, "Show help")
doExport := fs.Bool("export", false, "Export Zen Browser data to a zip in ~/Downloads")
importPath := fs.String("import", "", "Import a Zen backup zip")
if err := fs.Parse(args); err != nil {
return cliOptions{}, err
}
if *showHelp || *showHelpShort {
return cliOptions{showHelp: true}, nil
}
if fs.NArg() > 0 {
return cliOptions{}, fmt.Errorf("unexpected arguments: %s", strings.Join(fs.Args(), " "))
}
trimmedImportPath := strings.TrimSpace(*importPath)
hasImport := trimmedImportPath != ""
if *doExport == hasImport {
return cliOptions{}, errors.New("choose exactly one command: --export or --import <zip-path>")
}
return cliOptions{
doExport: *doExport,
importPath: trimmedImportPath,
}, nil
}