68 lines
1.6 KiB
Go
68 lines
1.6 KiB
Go
package command
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
type ParsedCommand struct {
|
|
Raw string
|
|
Name string
|
|
Args []string
|
|
Module string
|
|
}
|
|
|
|
func Parse(raw string) (*ParsedCommand, error) {
|
|
text := strings.TrimSpace(raw)
|
|
if text == "" || !strings.HasPrefix(text, "/") {
|
|
return nil, fmt.Errorf("not a command")
|
|
}
|
|
parts := strings.Fields(text)
|
|
if len(parts) == 0 {
|
|
return nil, fmt.Errorf("empty command")
|
|
}
|
|
|
|
cmd := &ParsedCommand{Raw: text, Name: parts[0]}
|
|
if len(parts) > 1 {
|
|
cmd.Args = parts[1:]
|
|
}
|
|
mod := strings.TrimPrefix(cmd.Name, "/")
|
|
if i := strings.Index(mod, "@"); i > 0 {
|
|
mod = mod[:i]
|
|
}
|
|
if mod != "" {
|
|
cmd.Module = mod
|
|
}
|
|
return cmd, nil
|
|
}
|
|
|
|
// ParseWithInputs: 支持 /cf dns list <zone_id> 这种输入参数写入 runbook inputs
|
|
func ParseWithInputs(raw string) (*ParsedCommand, map[string]string, error) {
|
|
cmd, err := Parse(raw)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
inputs := map[string]string{}
|
|
if cmd.Module == "cf" {
|
|
// /cf dns list <zone_id>
|
|
if len(cmd.Args) >= 2 && cmd.Args[0] == "dns" && cmd.Args[1] == "list" && len(cmd.Args) >= 3 {
|
|
inputs["zone_id"] = cmd.Args[2]
|
|
}
|
|
// /cf dns update <zone_id> <record_id> <type> <name> <content> [ttl] [proxied]
|
|
if len(cmd.Args) >= 2 && cmd.Args[0] == "dns" && cmd.Args[1] == "update" && len(cmd.Args) >= 7 {
|
|
inputs["zone_id"] = cmd.Args[2]
|
|
inputs["record_id"] = cmd.Args[3]
|
|
inputs["type"] = cmd.Args[4]
|
|
inputs["name"] = cmd.Args[5]
|
|
inputs["content"] = cmd.Args[6]
|
|
if len(cmd.Args) >= 8 {
|
|
inputs["ttl"] = cmd.Args[7]
|
|
}
|
|
if len(cmd.Args) >= 9 {
|
|
inputs["proxied"] = cmd.Args[8]
|
|
}
|
|
}
|
|
}
|
|
return cmd, inputs, nil
|
|
}
|