mirror of
https://github.com/larksuite/cli.git
synced 2026-09-14 18:42:53 +08:00
70 lines
1.8 KiB
Go
70 lines
1.8 KiB
Go
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package event
|
|
|
|
import (
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/larksuite/cli/errs"
|
|
"github.com/larksuite/cli/internal/event/catalog"
|
|
"github.com/larksuite/cli/internal/suggest"
|
|
)
|
|
|
|
const maxSuggestions = 3
|
|
|
|
// suggestEventKeys returns up to maxSuggestions keys resembling input (substring match beats edit distance).
|
|
func suggestEventKeys(snap *catalog.Snapshot, input string) []string {
|
|
type match struct {
|
|
key string
|
|
dist int
|
|
}
|
|
var hits []match
|
|
threshold := max(2, len(input)/5)
|
|
|
|
for _, key := range snap.Keys() {
|
|
if strings.Contains(key, input) {
|
|
hits = append(hits, match{key, 0})
|
|
continue
|
|
}
|
|
if d := suggest.Levenshtein(input, key); d <= threshold {
|
|
hits = append(hits, match{key, d})
|
|
}
|
|
}
|
|
sort.Slice(hits, func(i, j int) bool { return hits[i].dist < hits[j].dist })
|
|
|
|
n := min(maxSuggestions, len(hits))
|
|
out := make([]string, n)
|
|
for i := range out {
|
|
out[i] = hits[i].key
|
|
}
|
|
return out
|
|
}
|
|
|
|
// formatSuggestions renders keys as a human-readable quoted tail.
|
|
func formatSuggestions(keys []string) string {
|
|
if len(keys) == 0 {
|
|
return ""
|
|
}
|
|
quoted := make([]string, len(keys))
|
|
for i, k := range keys {
|
|
quoted[i] = fmt.Sprintf("%q", k)
|
|
}
|
|
if len(quoted) == 1 {
|
|
return quoted[0]
|
|
}
|
|
return "one of: " + strings.Join(quoted, ", ")
|
|
}
|
|
|
|
// unknownEventKeyErr builds the shared "unknown EventKey" error with a suggestion tail when available.
|
|
func unknownEventKeyErr(snap *catalog.Snapshot, key string) error {
|
|
msg := fmt.Sprintf("unknown EventKey: %s", key)
|
|
if guesses := suggestEventKeys(snap, key); len(guesses) > 0 {
|
|
msg += " — did you mean " + formatSuggestions(guesses) + "?"
|
|
}
|
|
return errs.NewValidationError(errs.SubtypeInvalidArgument, "%s", msg).
|
|
WithHint("Run 'lark-cli event list' to see available keys.")
|
|
}
|