Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement did you mean v1 #34

Merged
merged 1 commit into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/johtani/smarthome
go 1.20

require (
github.com/hbollon/go-edlib v1.6.0
github.com/nasa9084/go-switchbot/v3 v3.0.1
github.com/slack-go/slack v0.12.3
)
Expand Down
11 changes: 2 additions & 9 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,17 @@ github.com/go-test/deep v1.0.4 h1:u2CU3YKy9I2pmu9pX0eq50wCgjfGIt539SqR7FbHiho=
github.com/go-test/deep v1.0.4/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/nasa9084/go-switchbot/v2 v2.0.1 h1:jSpAhqyTfqr7fXB/DSd6ap8l9pRzE0NLmXjvlAMlIVE=
github.com/nasa9084/go-switchbot/v2 v2.0.1/go.mod h1:/BhZWClJhZFyyK1Uql10HcLM3YdbP6vVjucynAZHGDo=
github.com/nasa9084/go-switchbot/v2 v2.1.0 h1:3gz8sIh7O1GCBjqsY7bL+JIOf56x7aJCYpfb4CdFwLw=
github.com/nasa9084/go-switchbot/v2 v2.1.0/go.mod h1:/BhZWClJhZFyyK1Uql10HcLM3YdbP6vVjucynAZHGDo=
github.com/hbollon/go-edlib v1.6.0 h1:ga7AwwVIvP8mHm9GsPueC0d71cfRU/52hmPJ7Tprv4E=
github.com/hbollon/go-edlib v1.6.0/go.mod h1:wnt6o6EIVEzUfgbUZY7BerzQ2uvzp354qmS2xaLkrhM=
github.com/nasa9084/go-switchbot/v3 v3.0.1 h1:D8COfC+M5Y08qEJEMq0ZDucqORQSS06IlTTkpHQuiRY=
github.com/nasa9084/go-switchbot/v3 v3.0.1/go.mod h1:hrZUTHehZjib+vOCk9Rik5xvKQJ0KZKDOmyiIzonlI4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/slack-go/slack v0.12.2 h1:x3OppyMyGIbbiyFhsBmpf9pwkUzMhthJMRNmNlA4LaQ=
github.com/slack-go/slack v0.12.2/go.mod h1:hlGi5oXA+Gt+yWTPP0plCdRKmjsDxecdHxYQdlMQKOw=
github.com/slack-go/slack v0.12.3 h1:92/dfFU8Q5XP6Wp5rr5/T5JHLM5c5Smtn53fhToAP88=
github.com/slack-go/slack v0.12.3/go.mod h1:hlGi5oXA+Gt+yWTPP0plCdRKmjsDxecdHxYQdlMQKOw=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
Expand Down
28 changes: 20 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/johtani/smarthome/server/slack"
"github.com/johtani/smarthome/subcommand"
"os"
"strings"
)

func printHelp(commandsHelp string) string {
Expand Down Expand Up @@ -41,17 +42,28 @@ func runCmd(config subcommand.Config) error {
return fmt.Errorf(printHelp(config.Commands.Help()))
}
name := os.Args[1]
dymMsg := ""
d, err := config.Commands.Find(name, false)
if err != nil {
fmt.Fprintf(os.Stderr, "command[%v] is not found.\n", name)
printHelp(config.Commands.Help())
} else {
c := d.Init(config)
msg, err := c.Exec()
if err != nil {
return err
candidates, cmds := config.Commands.DidYouMean(name, true)
if len(candidates) == 0 {
fmt.Fprintf(os.Stderr, "command[%v] is not found.\n", name)
printHelp(config.Commands.Help())
return nil
} else {
d = candidates[0]
dymMsg = fmt.Sprintf("Did you mean \"%v\"?", cmds[0])
}
fmt.Fprintln(os.Stdout, msg)
}
c := d.Init(config)
msg, err := c.Exec()
if err != nil {
return err
}
if len(dymMsg) > 0 {
msg = strings.Join([]string{dymMsg, msg}, "\n")
}
fmt.Fprintln(os.Stdout, msg)

return nil
}
23 changes: 15 additions & 8 deletions server/slack/bot-server.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,17 +129,24 @@ func findAndExec(config subcommand.Config, text string) (string, error) {
// TODO message取り出し(もうちょっとスマートにできないか?)
name := strings.TrimSpace(text)
var msg string
dymMsg := ""
d, err := config.Commands.Find(name, true)
if err != nil {
return "", fmt.Errorf("Sorry, I cannot understand what you want from what you said '%v'...\n", name)
} else {
c := d.Init(config)
var err error
msg, err = c.Exec()
if err != nil {
return "", err
candidates, cmds := config.Commands.DidYouMean(name, true)
if len(candidates) == 0 {
return "", fmt.Errorf("Sorry, I cannot understand what you want from what you said '%v'...\n", name)
} else {
d = candidates[0]
dymMsg = fmt.Sprintf("Did you mean \"%v\"?", cmds[0])
}
}
// 何を実行したかを返したほうがいい?
c := d.Init(config)
msg, err = c.Exec()
if err != nil {
return "", err
}
if len(dymMsg) > 0 {
msg = strings.Join([]string{dymMsg, msg}, "\n")
}
return msg, nil
}
40 changes: 40 additions & 0 deletions subcommand/subcommand.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package subcommand
import (
"encoding/json"
"fmt"
"github.com/hbollon/go-edlib"
"github.com/johtani/smarthome/subcommand/action"
"github.com/johtani/smarthome/subcommand/action/owntone"
"github.com/johtani/smarthome/subcommand/action/switchbot"
Expand Down Expand Up @@ -72,6 +73,31 @@ func (e Entry) IsTarget(name string, withoutHyphen bool) bool {
}
}

func (e Entry) Distance(name string, withoutHyphen bool) (int, string) {
distance := edlib.LevenshteinDistance(name, e.Name)
command := e.Name
// TODO shortnameどうする?一番小さいDistanceでいいか?
if len(e.shortnames) > 0 {
for _, tmp := range e.shortnames {
sd := edlib.LevenshteinDistance(name, tmp)
if sd < distance {
distance = sd
command = tmp
}
}
}
if withoutHyphen && len(e.noHyphens) > 0 {
for _, tmp := range e.noHyphens {
sd := edlib.LevenshteinDistance(name, tmp)
if sd < distance {
distance = sd
command = tmp
}
}
}
return distance, command
}

// slices.Contains includes >= Go 1.21
func (e Entry) contains(names []string, target string) bool {
for _, name := range names {
Expand All @@ -95,6 +121,20 @@ func (c Commands) Find(name string, withoutHyphen bool) (Definition, error) {
return Definition{}, fmt.Errorf("not found %s command", name)
}

func (c Commands) DidYouMean(name string, withoutHyphen bool) ([]Definition, []string) {
var candidates []Definition
var cmds []string
for _, entry := range c.entries {
d, cmd := entry.Distance(name, withoutHyphen)
// TODO 3にした場合は、candidatesの距離の小さい順で返したほうが便利な気がする
if d < 3 {
candidates = append(candidates, entry.definition)
cmds = append(cmds, cmd)
}
}
return candidates, cmds
}

func (c Commands) Help() string {
var builder strings.Builder
for _, command := range c.entries {
Expand Down
48 changes: 48 additions & 0 deletions subcommand/subcommand_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,51 @@ func TestSubcommand_Exec(t *testing.T) {
})
}
}

func TestEntry_Distance(t *testing.T) {
type fields struct {
Name string
definition Definition
shortnames []string
}
type args struct {
name string
withoutHyphen bool
}
tests := []struct {
name string
fields fields
args args
distance int
cmd string
}{
{name: "only entity name",
fields: fields{"test", Definition{"tess", "description", NewHelpSubcommand}, []string{}},
args: args{"tess", false}, distance: 1, cmd: "test"},
{name: "hit shortname",
fields: fields{"tesssss", Definition{"tesssss", "description", NewHelpSubcommand}, []string{"hoge", "test"}},
args: args{"tess", false}, distance: 1, cmd: "test"},
{name: "hit entity name without hyphen",
fields: fields{"test-cmd", Definition{"test-cmd", "description", NewHelpSubcommand}, []string{}},
args: args{"tess cmd", true}, distance: 1, cmd: "test cmd"},
{name: "hit shortname without hyphen",
fields: fields{"tesssss-cmd", Definition{"tesssss-cmd", "description", NewHelpSubcommand}, []string{"hoge", "test-cmd"}},
args: args{"tess cmd", true}, distance: 1, cmd: "test cmd"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := newEntry(
tt.fields.Name,
tt.fields.definition,
tt.fields.shortnames,
)
distance, cmd := e.Distance(tt.args.name, tt.args.withoutHyphen)
if distance != tt.distance {
t.Errorf("Distance() distance = %v, want %v", distance, tt.distance)
}
if cmd != tt.cmd {
t.Errorf("Distance() cmd = %v, want %v", cmd, tt.cmd)
}
})
}
}