Files
Enterprise-Knowledge-Base/cli/internal/cmdutil/host.go
T
nullkey 41a98b5743 feat(cli): context CRUD
New v0.3 P0 entry 3-4: kubectl-style context-management subtree using
gh's `<noun> <verb>` surface convention consistent with the rest of
this CLI.

- context list: tabwriter rendering + --json envelope; reads config.yaml
  only.
- context add <name> --host <url> [--user]: validates http(s) URL, first
  context auto-becomes current, rejects duplicates with did-you-mean.
- context remove <name>: best-effort keyring cleanup like `auth logout`.
  Removing the current context triggers exit-10 confirmation (lark-cli
  skill protocol) — subsequent commands would lose their default
  --context.

(`context use` predates v0.3; the subtree was previously use-only.)

Bugs caught and fixed inline by the post-commit reviewer round:
- auth login was accepting `http://` (empty host portion) because the
  old validateHost only checked the scheme. New cmdutil.NormalizeHost
  (shared by both login and context add) requires u.Host != "".
- context add's validateName claimed `..` was rejected but only denied
  / \\ space. Switched to positive allowlist [A-Za-z0-9._-] plus
  explicit ./../path-separator rejection.

Helper consolidation:
- cli/internal/cmdutil/host.go: NormalizeHost (trim, scheme, host
  non-empty) — both auth login and context add share it.
- cli/internal/format/dash.go: DashIfEmpty — promoted from copies in
  cmd/auth/list.go and cmd/context/list.go.
- recordingStore test stub dropped in favor of secrets.NewMemStore;
  contextKeyList test helper replaced by the existing contextKeys.

14 unit tests; 13 e2e branches verified.

Roadmap: 3-4.
2026-05-14 10:57:17 +08:00

40 lines
1.3 KiB
Go

package cmdutil
import (
"fmt"
"net/url"
"strings"
)
// NormalizeHost validates and canonicalizes a `--host` / `--hostname` value.
// The returned string is trimmed of trailing slashes. Returns a typed
// CLI error (CodeInputMissingFlag for empty, CodeInputInvalidArgument for
// malformed) so callers can `return cmdutil.NormalizeHost(...)` directly.
//
// Rules (matches gh CLI's URL handling):
// - non-empty
// - scheme is http or https
// - URL parses
// - u.Host is non-empty (rejects "http://" which url.Parse accepts)
func NormalizeHost(host string) (string, error) {
host = strings.TrimRight(strings.TrimSpace(host), "/")
if host == "" {
return "", NewError(CodeInputInvalidArgument, "--host must not be empty")
}
u, err := url.Parse(host)
if err != nil {
return "", NewError(CodeInputInvalidArgument, fmt.Sprintf("--host %q is not a valid URL: %v", host, err))
}
if u.Scheme != "http" && u.Scheme != "https" {
return "", &Error{
Code: CodeInputInvalidArgument,
Message: fmt.Sprintf("--host scheme must be http or https, got %q", u.Scheme),
Hint: "example: https://kb.example.com",
}
}
if u.Host == "" {
return "", NewError(CodeInputInvalidArgument, fmt.Sprintf("--host %q is missing the host portion", host))
}
return host, nil
}