-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
root.go
78 lines (64 loc) · 2 KB
/
root.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
package cmd
import (
"fmt"
"os"
"runtime"
"github.com/spf13/cobra"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "hostctl",
Short: "Manage your hosts file like a pro",
Long: `
__ __ __ __
/ /_ ____ _____ / /_ _____ / /_ / /
/ __ \ / __ \ / ___/ / __/ / ___/ / __/ / /
/ / / // /_/ / (__ ) / /_ / /__ / /_ / /
/_/ /_/ \____/ /____/ \__/ \___/ \__/ /_/
hostctl is a CLI tool to manage your hosts file with ease.
You can have multiple profiles, enable/disable exactly what
you need each time with a simple interface.
`,
SilenceUsage: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
host, _ := cmd.Flags().GetString("host-file")
quiet, _ := cmd.Flags().GetBool("quiet")
defaultHostsFile := getDefaultHostFile()
if (host != defaultHostsFile || os.Getenv("HOSTCTL_FILE") != "") && !quiet {
fmt.Printf("Using hosts file: %s\n", host)
}
return nil
},
}
// Execute is the main entrypoint for CLI usage
func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func getDefaultHostFile() string {
envHostFile := os.Getenv("HOSTCTL_FILE")
if envHostFile != "" {
return envHostFile
}
if runtime.GOOS == "windows" {
return `C:/Windows/System32/Drivers/etc/hosts`
}
return "/etc/hosts"
}
func init() {
rootCmd.PersistentFlags().StringP("profile", "p", "", "Choose a profile")
rootCmd.PersistentFlags().String("host-file", getDefaultHostFile(), "Hosts file path")
rootCmd.PersistentFlags().BoolP("quiet", "q", false, "Run command without output")
rootCmd.PersistentFlags().StringSliceP("column", "c", nil, "Columns to show on lists")
rootCmd.PersistentFlags().Bool("raw", false, "Output without table borders")
}
// isPiped detect if there is any input through STDIN
func isPiped() bool {
info, err := os.Stdin.Stat()
if err != nil {
panic(err)
}
notPipe := info.Mode()&os.ModeNamedPipe == 0
return !notPipe || info.Size() > 0
}