diff --git a/main.go b/main.go index 718b985..b4b8e92 100644 --- a/main.go +++ b/main.go @@ -1,15 +1,15 @@ package main import ( - "fmt" - "io/ioutil" - "os" - "betaqr.com/go_fir_cli/api" "betaqr.com/go_fir_cli/constants" "betaqr.com/go_fir_cli/notifiers" + "betaqr.com/go_fir_cli/utils" + "fmt" "github.com/skip2/go-qrcode" "gopkg.in/urfave/cli.v1" + "io/ioutil" + "os" ) func main() { @@ -66,12 +66,12 @@ func initLogin() cli.Command { }, }, Action: func(c *cli.Context) error { - api_token := c.String("token") fir_api := &api.FirApi{} - fir_api.Login(api_token) + if err := fir_api.Login(api_token); err != nil { + return utils.SaveToLocal(fir_api.Email, api_token) + } fmt.Println(fir_api.Email) - return nil }, } @@ -93,6 +93,10 @@ func testWebhook() cli.Command { token := c.String("token") secret := c.String("secret") + if token == "" { + token = utils.LoadLocalToken() + } + notifier := ¬ifiers.DingTalkNotifier{ Key: token, SecretToken: secret, @@ -171,6 +175,10 @@ func uploadFile() cli.Command { file := c.String("file") token := c.GlobalString("token") + if token == "" { + token = utils.LoadLocalToken() + } + if token == "" { fmt.Println("请先设置 token") return nil diff --git a/utils/token.go b/utils/token.go new file mode 100644 index 0000000..f6b8e15 --- /dev/null +++ b/utils/token.go @@ -0,0 +1,50 @@ +package utils + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +func LoadLocalToken() string { + config, err := LoadLocalConfig() + if err != nil { + return "" + } + return config["token"] +} + +func LoadLocalConfig() (map[string]string, error) { + home, err := os.UserHomeDir() + if err != nil { + return nil, err + } + tokenPath := filepath.Join(home, ".fir-cli") + raw, err := os.ReadFile(tokenPath) + if err != nil { + return nil, err + } + if strings.HasPrefix(string(raw), "---\n") { + raw = raw[4:] + } + data := make(map[string]string) + for _, item := range strings.Split(string(raw), "\n") { + cmp := strings.SplitN(item, ": ", 2) + if len(cmp) == 2 && strings.HasPrefix(cmp[0], ":") { + cmp[0] = cmp[0][1:len(cmp[0])] + data[cmp[0]] = cmp[1] + } + } + return data, nil +} + +func SaveToLocal(email string, token string) error { + raw := fmt.Sprintf("---\n:email: %s\n:token: %s\n", email, token) + home, err := os.UserHomeDir() + if err != nil { + return err + } + tokenPath := filepath.Join(home, ".fir-cli") + return os.WriteFile(tokenPath, []byte(raw), 0644) +} diff --git a/utils/token_test.go b/utils/token_test.go new file mode 100644 index 0000000..3e21443 --- /dev/null +++ b/utils/token_test.go @@ -0,0 +1,20 @@ +package utils + +import ( + "fmt" + "testing" +) + +func TestLoadLocalToken(t *testing.T) { + for i := 0; i < 2; i++ { + data, err := LoadLocalConfig() + if err != nil { + t.Error(err) + } + fmt.Println(data) + err = SaveToLocal(data["email"], data["token"]) + if err != nil { + t.Error(err) + } + } +}