/
root.go
98 lines (88 loc) · 2.03 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package cmd
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"github.com/b4b4r07/crowi/cli"
"github.com/spf13/cobra"
)
const Version = "0.1.1"
var showVersion bool
var RootCmd = &cobra.Command{
Use: "crowi",
Short: "crowi command-line interface",
Long: "crowi - A simple Crowi editor for CLI",
SilenceUsage: true,
SilenceErrors: true,
Args: noArgs,
Run: func(cmd *cobra.Command, args []string) {
if showVersion {
fmt.Printf("version %s/%s\n", Version, runtime.Version())
return
}
if len(args) == 0 {
cmd.Usage()
}
},
}
func Execute() {
err := RootCmd.Execute()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func init() {
initConf()
RootCmd.Flags().BoolVarP(&showVersion, "version", "v", false, "Show the version and exit")
}
func initConf() {
dir, _ := cli.GetDefaultDir()
toml := filepath.Join(dir, "config.toml")
err := cli.Conf.LoadFile(toml)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func noArgs(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
suggestionsString := ""
if !cmd.DisableSuggestions {
if cmd.SuggestionsMinimumDistance <= 0 {
cmd.SuggestionsMinimumDistance = 2
}
suggestions := cmd.SuggestionsFor(args[0])
switch len(suggestions) {
case 0:
// Ignore because crowi-XXX may be present
break
// case 1:
// TODO: call function dynamically by name
// fmt.Println(suggestions[0])
default:
suggestionsString += "\n\nDid you mean this?\n"
for _, s := range suggestions {
suggestionsString += fmt.Sprintf("\t%v\n", s)
}
return fmt.Errorf("unknown command %q for crowi%s", args[0], suggestionsString)
}
}
crowiCmd := cmd.CommandPath() + "-" + args[0]
if _, err := exec.LookPath(crowiCmd); err != nil {
return fmt.Errorf(
"crowi: '%s' is not a crowi command.\nSee 'crowi --help'", args[0])
}
out, err := exec.Command(crowiCmd).Output()
if err != nil {
return err
}
if len(out) > 0 {
fmt.Printf(string(out))
}
return nil
}