-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
109 lines (94 loc) · 2.62 KB
/
main.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 main
import (
"fmt"
"os"
"path/filepath"
Cmd "github.com/soulteary/ssh-config/cmd"
Fn "github.com/soulteary/ssh-config/internal/fn"
Parser "github.com/soulteary/ssh-config/internal/parser"
)
type Dependencies struct {
StdinStat func() (os.FileInfo, error)
Exit func(int)
Println func(...interface{}) (n int, err error)
GetContent func(string) ([]byte, error)
SaveFile func(string, []byte) error
GetUserInputFromStdin func() string
Process func(string, string, Cmd.Args) []byte
CheckUseStdin func() bool
UserHomeDir func() (string, error)
}
func Run(args Cmd.Args, deps Dependencies) error {
isValid, notValidReason := Cmd.CheckConvertArgvValid(args)
if !isValid {
deps.Println(notValidReason)
return fmt.Errorf(notValidReason)
}
pipeMode := deps.CheckUseStdin()
var userInput string
if pipeMode {
userInput = deps.GetUserInputFromStdin()
} else {
isValid, notValidReason := Cmd.CheckIOArgvValid(args)
if !isValid {
deps.Println(notValidReason)
return fmt.Errorf(notValidReason)
}
content, err := deps.GetContent(args.Src)
if err != nil {
deps.Println("Error reading file:", err)
return err
}
userInput = string(content)
}
fileType := Fn.DetectStringType(userInput)
result := deps.Process(fileType, userInput, args)
if pipeMode {
deps.Println(string(result))
} else {
if args.Dest == "" {
deps.Println(string(result))
return nil
}
err := deps.SaveFile(args.Dest, result)
if err != nil {
deps.Println("Error saving file:", err)
return err
}
deps.Println("File has been saved successfully")
deps.Println("File path:", args.Dest)
}
return nil
}
func MainWithDependencies(exit func(int), userHomeDir func() (string, error)) {
deps := Dependencies{
StdinStat: os.Stdin.Stat,
Exit: os.Exit,
Println: fmt.Println,
GetContent: Fn.GetPathContent,
SaveFile: Fn.Save,
GetUserInputFromStdin: Fn.GetUserInputFromStdin,
Process: Parser.Process,
CheckUseStdin: func() bool { return Cmd.CheckUseStdin(os.Stdin.Stat) },
}
args := Cmd.ParseArgs()
// default src to ~/.ssh
if args.Src == "" {
homeDir, err := userHomeDir()
if err != nil {
fmt.Println("Error: getting user home directory:", err)
exit(1)
}
args.Src = filepath.Join(homeDir, ".ssh")
}
// default to YAML
if !(args.ToYAML && args.ToJSON && args.ToSSH) {
args.ToYAML = true
}
if err := Run(args, deps); err != nil {
exit(1)
}
}
func main() {
MainWithDependencies(os.Exit, os.UserHomeDir)
}