From 043738668b0b0cd6d93dec122fb730326d49b432 Mon Sep 17 00:00:00 2001 From: Ryan Cavicchioni Date: Mon, 5 Sep 2022 13:03:02 -0500 Subject: [PATCH] Add new implementation of HasCommand --- lib/common.go | 27 +++++++++++++++++++++++++++ lib/common_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/lib/common.go b/lib/common.go index bf9b562..79ca850 100644 --- a/lib/common.go +++ b/lib/common.go @@ -50,6 +50,33 @@ func BuildURI(rawuri, rawpath string) string { return u.String() } +func HasCommand(s, prefix string) bool { + s = strings.TrimSpace(s) + + if len(s) == 0 || len(prefix) == 0 { + return false + } + + if !strings.HasPrefix(s, prefix) { + return false + } + + // remove the command prefix + s = s[len(prefix):] + + // multiple assignment trick + cmd, _ := func() (string, string) { + x := strings.SplitN(s, " ", 2) + if len(x) > 1 { + return x[0], x[1] + } + + return x[0], "" + }() + + return len(cmd) > 0 +} + func ContainsCommand(s, prefix, cmd string) bool { s = strings.TrimSpace(s) diff --git a/lib/common_test.go b/lib/common_test.go index 023e195..9ebede4 100644 --- a/lib/common_test.go +++ b/lib/common_test.go @@ -26,3 +26,30 @@ func TestContainsCommand(t *testing.T) { } } } + +func TestHasCommandCommand(t *testing.T) { + tables := []struct { + s string + prefix string + want bool + }{ + {"!command", "!", true}, + {"!command x y", "!", true}, + {"!c x y", "!", true}, + {"! x y", "!", false}, + {"hey guy", "!", false}, + {"hey", "!", false}, + {"hey", "", false}, + {"", "!", false}, + {"", "", false}, + } + + for _, table := range tables { + if got, want := HasCommand(table.s, table.prefix), table.want; got != want { + t.Errorf( + "s: %s, prefix: %s, got: %t, want: %t", + table.s, table.prefix, got, want, + ) + } + } +}