Files
Enterprise-Knowledge-Base/cli/cmd/context/add.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

151 lines
5.3 KiB
Go

package contextcmd
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// AddOptions captures `weknora context add` flag state.
type AddOptions struct {
Host string
User string
JSONOut bool
}
// addResult is the typed payload emitted under data on success.
type addResult struct {
Name string `json:"name"`
Host string `json:"host"`
User string `json:"user,omitempty"`
Current bool `json:"current"`
}
// NewCmdAdd builds `weknora context add`. Registers a *credentialless*
// connection target — host + optional user only. Credentials for the new
// context are attached separately with `weknora auth login --name <n>`,
// reflecting gh's separation of "where" the CLI talks to (the host) and
// "how" it authenticates (the credential). kubectl's `config set-context`
// covers the same operation under a different surface convention. If you
// want one command for both, run `weknora auth login --name <n> --host
// <h>` instead.
func NewCmdAdd(f *cmdutil.Factory) *cobra.Command {
opts := &AddOptions{}
cmd := &cobra.Command{
Use: "add <name>",
Short: "Register a new context (host without credentials)",
Long: `Add a new context entry to config.yaml. Stores host (and optionally
user) but does NOT prompt for credentials. Use ` + "`weknora auth login --name <n>`" + ` to
attach credentials in a single step instead, or run ` + "`weknora auth login --name <n>`" + ` after
` + "`weknora context add`" + ` to fill them in.
The first context added is auto-selected as the current context. Subsequent
adds leave the current context untouched.`,
Example: ` weknora context add staging --host https://staging.example.com
weknora context add prod --host https://prod.example.com --user alice@example.com`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
return runAdd(opts, args[0])
},
}
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in `context list` (optional, cosmetic only)")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
_ = cmd.MarkFlagRequired("host")
agent.SetAgentHelp(cmd, "Adds a context. First context added auto-becomes current. Errors with resource.already_exists if name collides; input.invalid_argument if --host is not an absolute http(s) URL.")
return cmd
}
func runAdd(opts *AddOptions, name string) error {
if err := validateName(name); err != nil {
return err
}
host, err := cmdutil.NormalizeHost(opts.Host)
if err != nil {
return err
}
cfg, err := config.Load()
if err != nil {
return err
}
if _, exists := cfg.Contexts[name]; exists {
return &cmdutil.Error{
Code: cmdutil.CodeResourceAlreadyExists,
Message: fmt.Sprintf("context %q already exists", name),
Hint: fmt.Sprintf("use a different name, or run `weknora context remove %s` first", name),
}
}
if cfg.Contexts == nil {
cfg.Contexts = map[string]config.Context{}
}
cfg.Contexts[name] = config.Context{Host: host, User: opts.User}
wasFirst := cfg.CurrentContext == ""
if wasFirst {
cfg.CurrentContext = name
}
if err := config.Save(cfg); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
}
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("add context %s", name)}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(
addResult{Name: name, Host: host, User: opts.User, Current: wasFirst},
&format.Meta{Context: cfg.CurrentContext},
risk,
))
}
if wasFirst {
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
} else {
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name)
}
return nil
}
// validateName enforces the allowlist advertised in the --help hint: letters,
// digits, dash, underscore, dot. The `.` exception lets emails / DNS-like
// names through; the path-traversal `..` is structurally rejected by a
// separate guard because it would let a hand-edited config.yaml claim a
// context whose name walks out of the keyring namespace.
func validateName(name string) error {
if name == "" {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "context name must not be empty",
}
}
if name == "." || name == ".." || strings.Contains(name, "/") || strings.Contains(name, "\\") {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("context name %q is reserved or path-like", name),
Hint: "use letters, digits, dashes, underscores, or dots",
}
}
for _, r := range name {
switch {
case r >= 'a' && r <= 'z',
r >= 'A' && r <= 'Z',
r >= '0' && r <= '9',
r == '-' || r == '_' || r == '.':
continue
default:
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("context name %q contains invalid character %q", name, r),
Hint: "use letters, digits, dashes, underscores, or dots",
}
}
}
return nil
}