refactor(cli,auth): consolidate auth/profile model (BREAKING)
Auth now acts on the active profile instead of per-command --host/--name:
register a target with `profile add <name> --host <url> --use`, then
`auth login`. `auth login --with-token` reads an API key from stdin
(non-interactive, agent default); password login is interactive-only.
`auth token` prints the raw credential by default (clean $(...) capture);
--format json emits the {token,mode,profile} envelope, --jq implies json.
Login mode label corrected (api-key vs bearer). profile use and the auth/
profile read commands gain --dry-run / agent-help where they were missing.
This commit is contained in:
+25
-14
@@ -13,6 +13,7 @@ import (
|
||||
type AddOptions struct {
|
||||
Host string
|
||||
User string
|
||||
Use bool // --use: switch to this profile after adding
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
@@ -32,24 +33,25 @@ type addResult struct {
|
||||
|
||||
// NewCmdAdd builds `weknora profile add`. Registers a *credentialless*
|
||||
// connection target - host + optional user only. Credentials for the new
|
||||
// profile are attached separately with `weknora auth login --name <n>`,
|
||||
// separating "where" the CLI talks to (the host) and "how" it authenticates
|
||||
// (the credential). If you want one command for both, run
|
||||
// `weknora auth login --name <n> --host <h>` instead.
|
||||
// profile are attached separately by making it active and running
|
||||
// `weknora auth login`, separating "where" the CLI talks to (the host) and
|
||||
// "how" it authenticates (the credential). Pass --use to switch to the new
|
||||
// profile immediately, then run `weknora auth login`.
|
||||
func NewCmdAdd(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &AddOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "add <name>",
|
||||
Short: "Register a new profile (host without credentials)",
|
||||
Long: `Add a new profile 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 profile add`" + ` to fill them in.
|
||||
user) but does NOT prompt for credentials. To attach credentials, make the
|
||||
profile active (` + "`weknora profile use <n>`" + `, or ` + "`profile add <n> --use`" + `) and run
|
||||
` + "`weknora auth login`" + `.
|
||||
|
||||
The first profile added is auto-selected as the current profile. Subsequent
|
||||
adds leave the current profile untouched.`,
|
||||
adds leave the current profile untouched unless --use is passed.`,
|
||||
Example: ` weknora profile add staging --host https://staging.example.com
|
||||
weknora profile add prod --host https://prod.example.com --user alice@example.com`,
|
||||
weknora profile add prod --host https://prod.example.com --user alice@example.com
|
||||
weknora profile add prod --host https://prod.example.com --use # switch to it now`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
@@ -93,9 +95,15 @@ adds leave the current profile untouched.`,
|
||||
}
|
||||
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 'profile list' (optional, cosmetic only)")
|
||||
cmd.Flags().BoolVar(&opts.Use, "use", false, "Switch to this profile after adding it")
|
||||
cmdutil.AddFormatFlag(cmd, profileAddFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Register a new profile (connection target) with a name and host URL. Does not store credentials; make it active (--use, or `profile use <n>`) and run `auth login` afterwards to authenticate.",
|
||||
RequiredFlags: []string{"<name> (positional)", "--host"},
|
||||
Output: "envelope.data has name, host, user, current",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -133,7 +141,10 @@ func runAddWithConfig(opts *AddOptions, fopts *cmdutil.FormatOptions, name, host
|
||||
}
|
||||
cfg.Profiles[name] = config.Profile{Host: host, User: opts.User}
|
||||
wasFirst := cfg.CurrentProfile == ""
|
||||
if wasFirst {
|
||||
// The first profile is auto-selected; --use forces selection even when
|
||||
// another profile is already current.
|
||||
current := wasFirst || opts.Use
|
||||
if current {
|
||||
cfg.CurrentProfile = name
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
@@ -141,12 +152,12 @@ func runAddWithConfig(opts *AddOptions, fopts *cmdutil.FormatOptions, name, host
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst}, nil)
|
||||
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: current}, nil)
|
||||
}
|
||||
if wasFirst {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
if current {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s (now current). Run `weknora auth login` to attach credentials.\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s. Run `weknora profile use %s` then `weknora auth login` to attach credentials.\n", name, name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -119,6 +119,44 @@ func TestAdd_SecondProfileDoesNotChangeCurrent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdd_UseSwitchesCurrent asserts --use switches the current profile to the
|
||||
// newly-added one even when another profile is already current.
|
||||
func TestAdd_UseSwitchesCurrent(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "production",
|
||||
Profiles: map[string]config.Profile{"production": {Host: "https://prod.example.com"}},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
host, err := cmdutil.NormalizeHost("https://h")
|
||||
if err != nil {
|
||||
t.Fatalf("NormalizeHost: %v", err)
|
||||
}
|
||||
loaded, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if err := runAddWithConfig(&AddOptions{Host: host, Use: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "new", host, loaded); err != nil {
|
||||
t.Fatalf("runAddWithConfig: %v", err)
|
||||
}
|
||||
|
||||
got, _ := config.Load()
|
||||
if got.CurrentProfile != "new" {
|
||||
t.Errorf("--use must switch current to the new profile; got %q", got.CurrentProfile)
|
||||
}
|
||||
if _, ok := got.Profiles["new"]; !ok {
|
||||
t.Errorf("new profile not registered; keys=%v", profileKeys(got.Profiles))
|
||||
}
|
||||
if !strings.Contains(out.String(), "now current") {
|
||||
t.Errorf("output should note the profile is now current, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd_JSON(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
@@ -53,6 +53,11 @@ the CLI can talk to; "auth list" is the catalog of *how*.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, profileListFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "list configured connection profiles (name, host, which is active)",
|
||||
Examples: []string{"weknora profile list", "weknora profile list --jq '.data[].name'"},
|
||||
Output: "envelope.data is an array of {name, host, user, current}",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ func runRemove(opts *RemoveOptions, fopts *cmdutil.FormatOptions, name string, s
|
||||
// Confirmation only fires for removing the current profile - non-current
|
||||
// remove uses the same low-friction policy as `auth logout`.
|
||||
if wasCurrent {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current profile", name, "profile.remove", fmt.Sprintf("weknora profile remove %s -y", name)); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "remove", "current profile", name, "profile.remove", fmt.Sprintf("weknora profile remove %s -y", name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ var profileUseFields = []string{"current_profile", "previous_profile"}
|
||||
|
||||
// NewCmdUse builds the `weknora profile use <name>` command.
|
||||
func NewCmdUse(f *cmdutil.Factory) *cobra.Command {
|
||||
var dryRun bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "use <name>",
|
||||
Short: "Switch the default profile for subsequent commands",
|
||||
@@ -39,10 +40,23 @@ the global --profile flag instead, which writes nothing to disk.`,
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
if handled, err := cmdutil.HandleDryRun(c, dryRun, cmdutil.DryRunPlan{
|
||||
Action: "profile.use",
|
||||
Args: map[string]any{"name": args[0]},
|
||||
}); handled {
|
||||
return err
|
||||
}
|
||||
return runUse(args[0], fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, profileUseFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &dryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "switch the default profile for subsequent commands (persists to config)",
|
||||
RequiredFlags: []string{"<name> (positional)"},
|
||||
Examples: []string{"weknora profile use staging"},
|
||||
Output: "envelope.data confirms the now-active profile",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user