feat(cli): add internal/{text,compat} packages and acceptance scaffold (PR-6)
text/ gh-style display-width string helpers (Truncate / FuzzyAgo / Pluralize)
compat/ server-CLI version skew probe (kubectl) + 24h TTL cache (gh internal/update)
acceptance/contract/ helpers_test.go for in-process cobra exec + golden assert
(uses iostreams.SetForTest singleton replacement; no t.Parallel)
cmdutil/errors.go: AllCodes() + ClassifyHTTPErrorOutputs() bridge for the
contract test suite (no behavior change in error handling)
go-runewidth promoted from indirect to direct (used by text.Truncate for
display-width-aware CJK truncation).
acceptance/contract/helpers_test.go forward-references cmd.NewRootCmd which
is exported in PR-7 — that file does not compile until then by design.
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
// cli/acceptance/contract/helpers_test.go
|
||||
package contract_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"flag"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/cmd"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// update is the standard Go test golden-update flag.
|
||||
// go test -update ./acceptance/contract/...
|
||||
// Mirrors gh / kubectl / golang-migrate convention.
|
||||
var update = flag.Bool("update", false, "update golden files")
|
||||
|
||||
// newTestFactory builds a Factory whose Client returns mockClient.
|
||||
// Caller must NOT use t.Parallel() — see iostreams.SetForTest contract.
|
||||
//
|
||||
// WEKNORA_BASE_URL is set when mockServer is non-nil. v0.0 buildClient does
|
||||
// not currently honor this env var (it reads from config.Host); commands that
|
||||
// need the mock URL must rely on the mockClient injection above. The env
|
||||
// is set anyway as a forward-affordance for any direct net/http callers
|
||||
// added in PR-7+ (e.g. doctor's PingBaseURL HEAD /health).
|
||||
func newTestFactory(t *testing.T, mockServer *httptest.Server, mockClient *sdk.Client) *cmdutil.Factory {
|
||||
t.Helper()
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
if mockServer != nil {
|
||||
t.Setenv("WEKNORA_BASE_URL", mockServer.URL)
|
||||
}
|
||||
f := cmdutil.New()
|
||||
if mockClient != nil {
|
||||
f.Client = func() (*sdk.Client, error) { return mockClient, nil }
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// runCmd executes the root command in-process and returns captured stdout/stderr.
|
||||
// Replaces iostreams.IO singleton via SetForTest (auto-restored in t.Cleanup).
|
||||
func runCmd(t *testing.T, f *cmdutil.Factory, args ...string) (stdout, stderr string, exitCode int) {
|
||||
t.Helper()
|
||||
out, errBuf := iostreams.SetForTest(t)
|
||||
root := cmd.NewRootCmd(f) // exported in cli/cmd/root.go (Task 16)
|
||||
root.SetArgs(args)
|
||||
root.SetContext(context.Background())
|
||||
err := root.Execute()
|
||||
return out.String(), errBuf.String(), cmdutil.ExitCode(err)
|
||||
}
|
||||
|
||||
// assertGolden compares got against the JSON golden file at path.
|
||||
// With -update, writes got to path. Normalizes _meta.request_id to "<id>"
|
||||
// before compare (only field known unstable in v0.0).
|
||||
func assertGolden(t *testing.T, got []byte, path string) {
|
||||
t.Helper()
|
||||
got = normalizeEnvelope(got)
|
||||
if *update {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
t.Fatalf("mkdir testdata: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, got, 0644); err != nil {
|
||||
t.Fatalf("write golden: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
want, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read golden %s: %v (run with -update to create)", path, err)
|
||||
}
|
||||
if !bytes.Equal(want, got) {
|
||||
t.Errorf("envelope mismatch for %s\nwant:\n%s\ngot:\n%s", path, want, got)
|
||||
}
|
||||
}
|
||||
|
||||
// normalizeEnvelope replaces unstable fields with placeholders for stable diff.
|
||||
// Currently no-op (v0.0 commands don't set _meta.request_id, so output is stable).
|
||||
// Hook for future fields.
|
||||
func normalizeEnvelope(b []byte) []byte {
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// cli/acceptance/doc.go
|
||||
//
|
||||
// Package acceptance is the cli/ subtree top-level home for cross-cutting
|
||||
// contract / integration tests. Lives outside cli/internal/ so a future
|
||||
// reviewer immediately sees "this is the contract surface — change with care".
|
||||
//
|
||||
// Sub-packages:
|
||||
// contract/ — envelope JSON shape golden + error.code registry consistency
|
||||
//
|
||||
// Future v0.2+:
|
||||
// e2e/ — real WeKnora server blackbox tests (testscript-style)
|
||||
//
|
||||
// Mirrors gh's acceptance/ + kubernetes test/e2e/ pattern (spec §4.5).
|
||||
package acceptance
|
||||
+1
-1
@@ -8,6 +8,7 @@ require (
|
||||
github.com/Tencent/WeKnora/client v0.0.0-00010101000000-000000000000
|
||||
github.com/charmbracelet/huh v1.0.0
|
||||
github.com/mattn/go-isatty v0.0.20
|
||||
github.com/mattn/go-runewidth v0.0.16
|
||||
github.com/spf13/cobra v1.8.1
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/zalando/go-keyring v0.2.8
|
||||
@@ -34,7 +35,6 @@ require (
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
|
||||
@@ -184,3 +184,47 @@ func ClassifyHTTPError(err error) ErrorCode {
|
||||
}
|
||||
return CodeServerError
|
||||
}
|
||||
|
||||
// AllCodes returns the registered error code set.
|
||||
// Used by acceptance/contract/errorcodes_test.go to validate that every code
|
||||
// referenced in cli/cmd/ is present here. Update this list whenever a new
|
||||
// ErrorCode constant is added above.
|
||||
func AllCodes() []ErrorCode {
|
||||
return []ErrorCode{
|
||||
// auth
|
||||
CodeAuthUnauthenticated, CodeAuthTokenExpired, CodeAuthBadCredential,
|
||||
CodeAuthForbidden, CodeAuthCrossTenantBlocked, CodeAuthTenantMismatch,
|
||||
// resource
|
||||
CodeResourceNotFound, CodeResourceAlreadyExists, CodeResourceLocked,
|
||||
// input
|
||||
CodeInputInvalidArgument, CodeInputMissingFlag,
|
||||
// server / network
|
||||
CodeServerError, CodeServerTimeout, CodeServerRateLimited,
|
||||
CodeServerIncompatibleVersion, CodeNetworkError,
|
||||
// local
|
||||
CodeLocalConfigCorrupt, CodeLocalKeychainDenied, CodeLocalFileIO,
|
||||
CodeLocalUnimplemented,
|
||||
// mcp
|
||||
CodeMCPReadonlyMode, CodeMCPToolNotAllowed, CodeMCPSchemaUnknown,
|
||||
// v0.1: context use — added in PR-7 (Task 15) when CodeLocalContextNotFound lands
|
||||
}
|
||||
}
|
||||
|
||||
// ClassifyHTTPErrorOutputs returns every code that ClassifyHTTPError can return.
|
||||
// Bridges the AST-friendly literal model with the dynamic switch inside
|
||||
// ClassifyHTTPError. errorcodes_test.go uses this to seed the "referenced codes"
|
||||
// set without trying to AST-introspect a function-call expression.
|
||||
//
|
||||
// IMPORTANT: keep in sync with the switch in ClassifyHTTPError.
|
||||
func ClassifyHTTPErrorOutputs() []ErrorCode {
|
||||
return []ErrorCode{
|
||||
CodeAuthUnauthenticated, // 401
|
||||
CodeAuthForbidden, // 403
|
||||
CodeResourceNotFound, // 404
|
||||
CodeResourceAlreadyExists, // 409
|
||||
CodeServerRateLimited, // 429
|
||||
CodeServerError, // 5xx / parse-failure / default
|
||||
CodeInputInvalidArgument, // 4xx (else)
|
||||
CodeNetworkError, // 非 HTTP error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package cmdutil_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
func TestAllCodes_NonEmpty(t *testing.T) {
|
||||
codes := cmdutil.AllCodes()
|
||||
if len(codes) == 0 {
|
||||
t.Fatal("AllCodes() should return registered codes")
|
||||
}
|
||||
// Sentinel: 至少包含这几个 v0.0 已知 code
|
||||
want := map[cmdutil.ErrorCode]bool{
|
||||
cmdutil.CodeAuthUnauthenticated: false,
|
||||
cmdutil.CodeResourceNotFound: false,
|
||||
cmdutil.CodeNetworkError: false,
|
||||
}
|
||||
for _, c := range codes {
|
||||
if _, ok := want[c]; ok {
|
||||
want[c] = true
|
||||
}
|
||||
}
|
||||
for c, ok := range want {
|
||||
if !ok {
|
||||
t.Errorf("AllCodes() missing %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllCodes_NoDuplicates(t *testing.T) {
|
||||
codes := cmdutil.AllCodes()
|
||||
seen := make(map[cmdutil.ErrorCode]struct{})
|
||||
for _, c := range codes {
|
||||
if _, dup := seen[c]; dup {
|
||||
t.Errorf("AllCodes() duplicate: %q", c)
|
||||
}
|
||||
seen[c] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyHTTPErrorOutputs_Subset(t *testing.T) {
|
||||
outs := cmdutil.ClassifyHTTPErrorOutputs()
|
||||
all := make(map[cmdutil.ErrorCode]struct{})
|
||||
for _, c := range cmdutil.AllCodes() {
|
||||
all[c] = struct{}{}
|
||||
}
|
||||
for _, c := range outs {
|
||||
if _, ok := all[c]; !ok {
|
||||
t.Errorf("ClassifyHTTPErrorOutputs returns %q which is not in AllCodes", c)
|
||||
}
|
||||
}
|
||||
if len(outs) < 5 {
|
||||
t.Errorf("expected at least 5 codes, got %d", len(outs))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package compat
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const ttl = 24 * time.Hour
|
||||
|
||||
// cachePath returns $XDG_CACHE_HOME/weknora/server-info.yaml,fallback ~/.cache/weknora/.
|
||||
func cachePath() (string, error) {
|
||||
if x := os.Getenv("XDG_CACHE_HOME"); x != "" {
|
||||
return filepath.Join(x, "weknora", "server-info.yaml"), nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("locate home dir: %w", err)
|
||||
}
|
||||
return filepath.Join(home, ".cache", "weknora", "server-info.yaml"), nil
|
||||
}
|
||||
|
||||
// LoadCache reads the cached Info. Returns (info, fresh, err).
|
||||
//
|
||||
// info == nil when no cache exists (err == nil)
|
||||
// fresh == false 当 cache 不存在 / TTL 过期
|
||||
func LoadCache() (*Info, bool, error) {
|
||||
p, err := cachePath()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
data, err := os.ReadFile(p)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("read cache: %w", err)
|
||||
}
|
||||
var info Info
|
||||
if err := yaml.Unmarshal(data, &info); err != nil {
|
||||
return nil, false, fmt.Errorf("parse cache: %w", err)
|
||||
}
|
||||
fresh := time.Since(info.ProbedAt) < ttl
|
||||
return &info, fresh, nil
|
||||
}
|
||||
|
||||
// SaveCache atomically writes Info to the cache file (mode 0600).
|
||||
func SaveCache(info *Info) error {
|
||||
p, err := cachePath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
|
||||
return fmt.Errorf("mkdir cache dir: %w", err)
|
||||
}
|
||||
data, err := yaml.Marshal(info)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal cache: %w", err)
|
||||
}
|
||||
tmp := p + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0600); err != nil {
|
||||
return fmt.Errorf("write tmp cache: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmp, p); err != nil {
|
||||
return fmt.Errorf("rename cache: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package compat_test
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/compat"
|
||||
)
|
||||
|
||||
func TestCache_RoundTrip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", dir)
|
||||
|
||||
want := &compat.Info{ServerVersion: "1.2.3", ProbedAt: time.Now().UTC().Truncate(time.Second)}
|
||||
if err := compat.SaveCache(want); err != nil {
|
||||
t.Fatalf("SaveCache: %v", err)
|
||||
}
|
||||
|
||||
got, fresh, err := compat.LoadCache()
|
||||
if err != nil {
|
||||
t.Fatalf("LoadCache: %v", err)
|
||||
}
|
||||
if !fresh {
|
||||
t.Error("just-saved cache should be fresh")
|
||||
}
|
||||
if got == nil || got.ServerVersion != want.ServerVersion {
|
||||
t.Errorf("ServerVersion = %v, want %q", got, want.ServerVersion)
|
||||
}
|
||||
|
||||
// 文件应在 $XDG_CACHE_HOME/weknora/server-info.yaml
|
||||
p := filepath.Join(dir, "weknora", "server-info.yaml")
|
||||
if _, err := filepath.Abs(p); err != nil {
|
||||
t.Errorf("path resolution: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Stale(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", dir)
|
||||
|
||||
old := &compat.Info{ServerVersion: "1.2.3", ProbedAt: time.Now().Add(-25 * time.Hour)}
|
||||
if err := compat.SaveCache(old); err != nil {
|
||||
t.Fatalf("SaveCache: %v", err)
|
||||
}
|
||||
|
||||
_, fresh, err := compat.LoadCache()
|
||||
if err != nil {
|
||||
t.Fatalf("LoadCache: %v", err)
|
||||
}
|
||||
if fresh {
|
||||
t.Error("25h old cache should be stale")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Missing(t *testing.T) {
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
info, fresh, err := compat.LoadCache()
|
||||
if err != nil {
|
||||
t.Fatalf("LoadCache should not error on missing: %v", err)
|
||||
}
|
||||
if fresh {
|
||||
t.Error("missing cache must not be fresh")
|
||||
}
|
||||
if info != nil {
|
||||
t.Errorf("missing cache info should be nil, got %v", info)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package compat
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Level is the client-server version compat level.
|
||||
type Level int
|
||||
|
||||
const (
|
||||
OK Level = iota // 兼容
|
||||
SoftWarn // 服务器旧, 部分新功能不可用
|
||||
HardError // 不兼容, 需升级 CLI 或 server
|
||||
)
|
||||
|
||||
func (l Level) String() string {
|
||||
switch l {
|
||||
case OK:
|
||||
return "ok"
|
||||
case SoftWarn:
|
||||
return "soft_warn"
|
||||
case HardError:
|
||||
return "hard_error"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// Compat compares client/server version. v0.x 阶段允许漂移:
|
||||
//
|
||||
// 同 major, client minor ≤ server minor → OK
|
||||
// 同 major, client minor > server minor → SoftWarn (server 旧, 部分新功能不可用)
|
||||
// 不同 major → HardError
|
||||
// 字符串 unparseable → OK (容错, 不阻塞)
|
||||
// "(unknown)" / "" → OK (dev build / server 字段缺失)
|
||||
func Compat(serverVer, cliVer string) (Level, string) {
|
||||
sMaj, sMin, ok := parseSemver(serverVer)
|
||||
if !ok {
|
||||
return OK, ""
|
||||
}
|
||||
cMaj, cMin, ok := parseSemver(cliVer)
|
||||
if !ok {
|
||||
return OK, ""
|
||||
}
|
||||
if sMaj != cMaj {
|
||||
return HardError, fmt.Sprintf("incompatible: client %s vs server %s — upgrade required", cliVer, serverVer)
|
||||
}
|
||||
if cMin > sMin {
|
||||
return SoftWarn, fmt.Sprintf("server is older (server %s, client %s); some new features may be unavailable", serverVer, cliVer)
|
||||
}
|
||||
return OK, ""
|
||||
}
|
||||
|
||||
// parseSemver extracts (major, minor) from "X.Y.Z" or "X.Y.Z-suffix".
|
||||
// Accepts the leading "v" common in `git describe` output and Tencent/WeKnora
|
||||
// tag conventions ("v0.1.0"), since both server `/system/info.version` and
|
||||
// the CLI's own ldflags-injected build.Version may carry it.
|
||||
// Returns ok=false 当字符串无法识别 (空 / "(unknown)" / 非数字)。
|
||||
func parseSemver(s string) (major, minor int, ok bool) {
|
||||
if s == "" || s == "(unknown)" {
|
||||
return 0, 0, false
|
||||
}
|
||||
// 接受 "v" 前缀 (kubectl / gh 同款宽容):git describe + Tencent tag 都带 v
|
||||
s = strings.TrimPrefix(s, "v")
|
||||
// 去掉 prerelease/build metadata
|
||||
if i := strings.IndexAny(s, "-+"); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
parts := strings.SplitN(s, ".", 3)
|
||||
if len(parts) < 2 {
|
||||
return 0, 0, false
|
||||
}
|
||||
maj, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
min, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
return maj, min, true
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package compat_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/compat"
|
||||
)
|
||||
|
||||
func TestCompat(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serverVer string
|
||||
cliVer string
|
||||
wantLevel compat.Level
|
||||
wantHintHas string
|
||||
}{
|
||||
{"equal", "1.2.3", "1.2.3", compat.OK, ""},
|
||||
{"client minor lower", "1.5.0", "1.2.0", compat.OK, ""},
|
||||
{"client minor higher", "1.2.0", "1.5.0", compat.SoftWarn, "server is older"},
|
||||
{"different major", "1.9.9", "2.0.0", compat.HardError, "incompatible"},
|
||||
{"client unset", "1.2.3", "(unknown)", compat.OK, ""}, // dev build, 不报警
|
||||
{"server unset", "", "1.2.3", compat.OK, ""},
|
||||
{"malformed server", "garbage", "1.2.3", compat.OK, ""}, // 不阻塞
|
||||
|
||||
// "v" prefix tolerance (git describe + Tencent tag convention)
|
||||
{"v-prefix both", "v1.2.0", "v1.5.0", compat.SoftWarn, "server is older"},
|
||||
{"v-prefix server only", "v1.9.9", "2.0.0", compat.HardError, "incompatible"},
|
||||
{"v-prefix cli only", "1.9.9", "v2.0.0", compat.HardError, "incompatible"},
|
||||
|
||||
// Hint must be empty when level == OK (no false positives)
|
||||
{"OK hint empty", "1.2.3", "1.2.3", compat.OK, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
gotLevel, gotHint := compat.Compat(tt.serverVer, tt.cliVer)
|
||||
if gotLevel != tt.wantLevel {
|
||||
t.Errorf("%s: Level = %v, want %v", tt.name, gotLevel, tt.wantLevel)
|
||||
}
|
||||
if tt.wantHintHas != "" && !strings.Contains(gotHint, tt.wantHintHas) {
|
||||
t.Errorf("%s: hint = %q, should contain %q", tt.name, gotHint, tt.wantHintHas)
|
||||
}
|
||||
if tt.wantLevel == compat.OK && gotHint != "" {
|
||||
t.Errorf("%s: OK level should have empty hint, got %q", tt.name, gotHint)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Package compat probes server `/system/info` and decides client-server
|
||||
// version skew level. Used by `weknora doctor` 的 server_version 检查项。
|
||||
//
|
||||
// Mirrors gh internal/update/update.go cache pattern (24h TTL state file)
|
||||
// and kubectl pkg/version/skew_warning.go three-tier compat semantics
|
||||
// (major-mismatch=hard / minor-mismatch=soft / equal=ok).
|
||||
package compat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// Info is the cached server version snapshot.
|
||||
type Info struct {
|
||||
ServerVersion string `yaml:"server_version"`
|
||||
EngineInfo map[string]string `yaml:"engine_info,omitempty"`
|
||||
ProbedAt time.Time `yaml:"probed_at"`
|
||||
}
|
||||
|
||||
// ProbeService is the narrow SDK surface compat depends on (testability via
|
||||
// fake; mirrors v0.0 service interface pattern).
|
||||
type ProbeService interface {
|
||||
GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error)
|
||||
}
|
||||
|
||||
// Probe calls server /system/info and returns a fresh Info snapshot.
|
||||
func Probe(ctx context.Context, c ProbeService) (*Info, error) {
|
||||
resp, err := c.GetSystemInfo(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("probe server: %w", err)
|
||||
}
|
||||
return &Info{
|
||||
ServerVersion: resp.Version,
|
||||
ProbedAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package compat_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/compat"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type fakeProbeClient struct {
|
||||
info *sdk.SystemInfo
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeProbeClient) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, error) {
|
||||
return f.info, f.err
|
||||
}
|
||||
|
||||
func TestProbe_Success(t *testing.T) {
|
||||
c := &fakeProbeClient{info: &sdk.SystemInfo{Version: "1.2.3"}}
|
||||
got, err := compat.Probe(context.Background(), c)
|
||||
if err != nil {
|
||||
t.Fatalf("Probe: %v", err)
|
||||
}
|
||||
if got.ServerVersion != "1.2.3" {
|
||||
t.Errorf("ServerVersion = %q, want %q", got.ServerVersion, "1.2.3")
|
||||
}
|
||||
if got.ProbedAt.IsZero() {
|
||||
t.Error("ProbedAt should be set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbe_Error(t *testing.T) {
|
||||
c := &fakeProbeClient{err: errors.New("HTTP error 500: down")}
|
||||
_, err := compat.Probe(context.Background(), c)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Package text holds gh-style string helpers for human-readable CLI output.
|
||||
// All functions are pure (no I/O, no time.Now), making them trivially testable.
|
||||
package text
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Pluralize returns "<n> <thing>" or "<n> <thing>s". Mirrors gh
|
||||
// internal/text/text.go Pluralize signature — simple suffix "s" only;
|
||||
// irregular forms (person/people) are not supported (add PluralizeIrregular
|
||||
// when needed, per spec §2.1).
|
||||
func Pluralize(n int, thing string) string {
|
||||
if n == 1 {
|
||||
return fmt.Sprintf("%d %s", n, thing)
|
||||
}
|
||||
return fmt.Sprintf("%d %ss", n, thing)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package text_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
)
|
||||
|
||||
func TestPluralize(t *testing.T) {
|
||||
tests := []struct {
|
||||
n int
|
||||
thing string
|
||||
want string
|
||||
}{
|
||||
{0, "doc", "0 docs"},
|
||||
{1, "doc", "1 doc"},
|
||||
{2, "doc", "2 docs"},
|
||||
{5, "chunk", "5 chunks"},
|
||||
{1, "chunk", "1 chunk"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := text.Pluralize(tt.n, tt.thing)
|
||||
if got != tt.want {
|
||||
t.Errorf("Pluralize(%d, %q) = %q, want %q", tt.n, tt.thing, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package text
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FuzzyAgo formats t relative to now in the gh house style.
|
||||
// Mirrors github.com/cli/cli/internal/text/datetime.go FuzzyAgo.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// FuzzyAgo(now, now-5m) → "about 5 minutes ago"
|
||||
// FuzzyAgo(now, now-3h) → "about 3 hours ago"
|
||||
// FuzzyAgo(now, now-2d) → "about 2 days ago"
|
||||
// FuzzyAgo(now, now+5m) → "about 5 minutes from now"
|
||||
func FuzzyAgo(now, t time.Time) string {
|
||||
d := now.Sub(t)
|
||||
suffix := "ago"
|
||||
if d < 0 {
|
||||
d = -d
|
||||
suffix = "from now"
|
||||
}
|
||||
switch {
|
||||
case d < time.Minute:
|
||||
return "less than a minute " + suffix
|
||||
case d < time.Hour:
|
||||
return fmt.Sprintf("about %s %s", Pluralize(int(math.Round(d.Minutes())), "minute"), suffix)
|
||||
case d < 24*time.Hour:
|
||||
return fmt.Sprintf("about %s %s", Pluralize(int(math.Round(d.Hours())), "hour"), suffix)
|
||||
case d < 30*24*time.Hour:
|
||||
return fmt.Sprintf("about %s %s", Pluralize(int(math.Round(d.Hours()/24)), "day"), suffix)
|
||||
case d < 365*24*time.Hour:
|
||||
return fmt.Sprintf("about %s %s", Pluralize(int(math.Round(d.Hours()/(24*30))), "month"), suffix)
|
||||
default:
|
||||
return fmt.Sprintf("about %s %s", Pluralize(int(math.Round(d.Hours()/(24*365))), "year"), suffix)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package text_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
)
|
||||
|
||||
func TestFuzzyAgo(t *testing.T) {
|
||||
now := time.Date(2026, 5, 8, 12, 0, 0, 0, time.UTC)
|
||||
tests := []struct {
|
||||
name string
|
||||
t time.Time
|
||||
want string
|
||||
}{
|
||||
{"5 minutes ago", now.Add(-5 * time.Minute), "about 5 minutes ago"},
|
||||
{"1 hour ago", now.Add(-1 * time.Hour), "about 1 hour ago"},
|
||||
{"3 hours ago", now.Add(-3 * time.Hour), "about 3 hours ago"},
|
||||
{"2 days ago", now.Add(-2 * 24 * time.Hour), "about 2 days ago"},
|
||||
{"30 days ago", now.Add(-30 * 24 * time.Hour), "about 1 month ago"},
|
||||
{"5 minutes from now", now.Add(5 * time.Minute), "about 5 minutes from now"},
|
||||
{"less than 1m ago", now.Add(-30 * time.Second), "less than a minute ago"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := text.FuzzyAgo(now, tt.t)
|
||||
if got != tt.want {
|
||||
t.Errorf("FuzzyAgo(%s) = %q, want %q", tt.name, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package text
|
||||
|
||||
import "github.com/mattn/go-runewidth"
|
||||
|
||||
const ellipsis = "…"
|
||||
|
||||
// Truncate cuts s to at most maxWidth display columns (CJK / emoji 占 2 列;
|
||||
// ASCII 占 1 列), appending "…" if truncated. Mirrors gh
|
||||
// internal/text/text.go Truncate semantics — display width, not rune count.
|
||||
//
|
||||
// Edge cases:
|
||||
//
|
||||
// maxWidth ≤ 0 → ""
|
||||
// s 已 ≤ maxWidth → s 原样返回
|
||||
// ellipsis 占 1 列, 所以 truncate 时 budget = maxWidth - 1
|
||||
func Truncate(maxWidth int, s string) string {
|
||||
if maxWidth <= 0 {
|
||||
return ""
|
||||
}
|
||||
if runewidth.StringWidth(s) <= maxWidth {
|
||||
return s
|
||||
}
|
||||
if maxWidth == 1 {
|
||||
return ellipsis
|
||||
}
|
||||
budget := maxWidth - 1 // reserve for ellipsis
|
||||
w := 0
|
||||
for i, r := range s {
|
||||
rw := runewidth.RuneWidth(r)
|
||||
if w+rw > budget {
|
||||
return s[:i] + ellipsis
|
||||
}
|
||||
w += rw
|
||||
}
|
||||
return s + ellipsis
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package text_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/text"
|
||||
)
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
maxWidth int
|
||||
s string
|
||||
want string
|
||||
}{
|
||||
{"no truncate ASCII", 20, "hello", "hello"},
|
||||
{"truncate ASCII", 5, "hello world", "hell…"},
|
||||
{"no truncate CJK", 8, "中文测试", "中文测试"},
|
||||
{"truncate CJK", 5, "中文测试", "中文…"},
|
||||
{"empty", 5, "", ""},
|
||||
{"single char fits", 1, "a", "a"},
|
||||
{"truncate to width 1", 1, "abc", "…"},
|
||||
{"maxWidth zero", 0, "x", ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := text.Truncate(tt.maxWidth, tt.s)
|
||||
if got != tt.want {
|
||||
t.Errorf("Truncate(%d, %q) = %q, want %q", tt.maxWidth, tt.s, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user