WeKnora deployment source with the reviewed wiki identity, summary and recovery fixes
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-weknora) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-weknora) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-weknora) / End-to-end inside dsh (latest, advisory) (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Build & Publish (dsh-weknora) / Publish to npm (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-weknora) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-weknora) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-weknora) / End-to-end inside dsh (latest, advisory) (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Build & Publish (dsh-weknora) / Publish to npm (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
// Package linkcmd — dryrun_validation_test.go asserts that --dry-run on
|
||||
// link / unlink rejects identically to the live path. Before the surrounding
|
||||
// fix, validation lived in runX() and was reached only after HandleDryRun
|
||||
// short-circuited, so --dry-run accepted invocations the live path rejects.
|
||||
package linkcmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// linkDryRunFactory builds a Factory whose Client closure panics if invoked —
|
||||
// dry-run must early-exit before any SDK call.
|
||||
func linkDryRunFactory(t *testing.T, cfg *config.Config) *cmdutil.Factory {
|
||||
t.Helper()
|
||||
return &cmdutil.Factory{
|
||||
Config: func() (*config.Config, error) { return cfg, nil },
|
||||
Client: func() (*sdk.Client, error) {
|
||||
t.Fatal("dry-run path must not call Factory.Client(); SDK side effect leaked")
|
||||
return nil, nil
|
||||
},
|
||||
Prompter: func() prompt.Prompter {
|
||||
t.Fatal("dry-run path must not call Factory.Prompter(); confirm-prompt side effect leaked")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// withRootHarnessLink wraps a link subcommand under a synthetic root cmd
|
||||
// that registers the global persistent flags.
|
||||
func withRootHarnessLink(sub *cobra.Command, args ...string) *cobra.Command {
|
||||
root := &cobra.Command{Use: "weknora"}
|
||||
pf := root.PersistentFlags()
|
||||
pf.BoolP("yes", "y", false, "")
|
||||
pf.String("format", "", "")
|
||||
pf.StringP("jq", "q", "", "")
|
||||
root.AddCommand(sub)
|
||||
root.SetArgs(append([]string{sub.Name()}, args...))
|
||||
root.SetContext(context.Background())
|
||||
root.SilenceErrors = true
|
||||
root.SilenceUsage = true
|
||||
return root
|
||||
}
|
||||
|
||||
// TestLink_DryRun_RejectsNoCurrentProfile: link with no active profile →
|
||||
// live path returns auth.unauthenticated; --dry-run must do the same.
|
||||
func TestLink_DryRun_RejectsNoCurrentProfile(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
cfg := &config.Config{}
|
||||
root := withRootHarnessLink(NewCmd(linkDryRunFactory(t, cfg)),
|
||||
"--kb", "00000000-0000-0000-0000-000000000001", "--dry-run", "--format", "json")
|
||||
err := root.Execute()
|
||||
require.Error(t, err, "dry-run must reject when no current profile")
|
||||
var typed *cmdutil.Error
|
||||
require.True(t, errors.As(err, &typed), "expected *cmdutil.Error, got %T %v", err, err)
|
||||
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
|
||||
}
|
||||
|
||||
// TestLink_DryRun_RejectsNoKBNoTTY: --kb omitted on non-TTY → live path
|
||||
// returns local.kb_id_required; --dry-run must do the same.
|
||||
func TestLink_DryRun_RejectsNoKBNoTTY(t *testing.T) {
|
||||
iostreams.SetForTest(t) // non-TTY
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "prod",
|
||||
Profiles: map[string]config.Profile{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
root := withRootHarnessLink(NewCmd(linkDryRunFactory(t, cfg)),
|
||||
"--dry-run", "--format", "json")
|
||||
err := root.Execute()
|
||||
require.Error(t, err, "dry-run must reject missing --kb on non-TTY")
|
||||
var typed *cmdutil.Error
|
||||
require.True(t, errors.As(err, &typed))
|
||||
assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
|
||||
}
|
||||
|
||||
// TestUnlink_DryRun_RejectsMissingLink: cwd has no .weknora/project.yaml →
|
||||
// live path returns input.invalid_argument; --dry-run must do the same.
|
||||
func TestUnlink_DryRun_RejectsMissingLink(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
// Change to an empty temp dir so projectlink.Discover finds nothing.
|
||||
tmp := t.TempDir()
|
||||
prev, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(tmp))
|
||||
t.Cleanup(func() { _ = os.Chdir(prev) })
|
||||
|
||||
root := withRootHarnessLink(NewCmdUnlink(),
|
||||
"--dry-run", "--format", "json")
|
||||
err = root.Execute()
|
||||
require.Error(t, err, "dry-run must reject when no project link present")
|
||||
var typed *cmdutil.Error
|
||||
require.True(t, errors.As(err, &typed))
|
||||
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// Package linkcmd implements `weknora link` - binds the current working
|
||||
// directory to a knowledge base by writing .weknora/project.yaml. Always
|
||||
// overwrites an existing link silently rather than refusing when one is
|
||||
// already present. The cobra Long: text covers the user-facing modes
|
||||
// (--kb / TTY / non-TTY).
|
||||
package linkcmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||
)
|
||||
|
||||
// linkFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `link`. Tracks the small linkResult struct.
|
||||
var linkFields = []string{"profile", "kb_id", "kb_name", "project_link_path"}
|
||||
|
||||
type Options struct {
|
||||
KB string // --kb: KB UUID or name; empty triggers interactive prompt on TTY
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// linkResult is the typed payload emitted under data.
|
||||
type linkResult struct {
|
||||
Profile string `json:"profile"`
|
||||
KBID string `json:"kb_id"`
|
||||
KBName string `json:"kb_name,omitempty"`
|
||||
ProjectLinkPath string `json:"project_link_path"`
|
||||
}
|
||||
|
||||
// NewCmd builds the `weknora link` command.
|
||||
func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &Options{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "link [kb]",
|
||||
Short: "Bind the current directory to a knowledge base",
|
||||
Long: `Writes .weknora/project.yaml in the current working directory pointing
|
||||
at the supplied knowledge base. Subsequent commands run from this directory
|
||||
(or any subdirectory) automatically resolve --kb from the link unless
|
||||
overridden by the --kb flag or WEKNORA_KB_ID env var.
|
||||
|
||||
Pass the knowledge base as a positional argument (weknora link <id-or-name>) or
|
||||
via --kb — the two are equivalent — for non-interactive use (scripts, CI). Run
|
||||
on a TTY without either to be prompted from the list of available KBs. Always
|
||||
overwrites any existing link - re-run to switch.
|
||||
|
||||
AI agents: link writes to the user's working directory. Only run it when the
|
||||
user explicitly asked to bind this directory; don't run it as a side effect.`,
|
||||
Example: ` weknora link a32a63ff-fb36-4874-bcaa-30f48570a694 # positional UUID
|
||||
weknora link engineering # positional name → id
|
||||
weknora link --kb engineering # --kb form (equivalent)
|
||||
weknora link # interactive (TTY)`,
|
||||
// The knowledge base may be given as a positional arg (matching every
|
||||
// other <id> command) or via --kb; the two are equivalent.
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
// Accept the KB as a positional (consistent with `kb view <id>`,
|
||||
// `doc view <id>`, …) in addition to --kb. Reject supplying both.
|
||||
if len(args) == 1 {
|
||||
if opts.KB != "" && opts.KB != args[0] {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
|
||||
"specify the knowledge base once: as a positional argument or --kb, not both")
|
||||
}
|
||||
opts.KB = args[0]
|
||||
}
|
||||
// Pure-local validation runs before the dry-run gate so --dry-run
|
||||
// rejects identically to the live path. resolveProfile only reads
|
||||
// config; the non-TTY-without-`--kb` check is a flag-shape error.
|
||||
// Same typed errors as runLink (kept there for direct callers).
|
||||
if _, err := resolveProfile(f); err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.KB == "" && !iostreams.IO.IsStdoutTTY() {
|
||||
return cmdutil.NewError(cmdutil.CodeKBIDRequired, "--kb is required (no TTY for interactive prompt)")
|
||||
}
|
||||
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
|
||||
Action: "link",
|
||||
Args: map[string]any{
|
||||
"kb": opts.KB,
|
||||
},
|
||||
}); handled {
|
||||
return err
|
||||
}
|
||||
return runLink(c.Context(), opts, fopts, f)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.KB, "kb", "", "Knowledge base UUID or name; omit on a TTY for interactive prompt")
|
||||
cmdutil.AddFormatFlag(cmd, linkFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Bind the current directory to a knowledge base by writing .weknora/project.yaml. Give the KB as a positional arg or --kb (non-interactive); only run when the user explicitly asks to link this directory.",
|
||||
RequiredFlags: []string{"<kb> positional or --kb (required when no TTY)"},
|
||||
Examples: []string{"weknora link engineering", "weknora link --kb a32a63ff-fb36-4874-bcaa-30f48570a694"},
|
||||
Output: "envelope.data has profile, kb_id, kb_name, project_link_path",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runLink(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "get cwd")
|
||||
}
|
||||
linkPath := filepath.Join(cwd, projectlink.DirName, projectlink.FileName)
|
||||
|
||||
profileName, err := resolveProfile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kbID, kbName, err := resolveKB(ctx, opts, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
link := &projectlink.Project{
|
||||
Profile: profileName,
|
||||
KBID: kbID,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
if err := projectlink.Save(linkPath, link); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write project link")
|
||||
}
|
||||
|
||||
r := linkResult{
|
||||
Profile: profileName,
|
||||
KBID: kbID,
|
||||
KBName: kbName,
|
||||
ProjectLinkPath: linkPath,
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, r, nil)
|
||||
}
|
||||
if kbName != "" {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb=%s, id=%s)\n", linkPath, profileName, kbName, kbID)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Linked %s to %s (kb_id=%s)\n", linkPath, profileName, kbID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolveProfile picks the active profile to record in the link. There is no
|
||||
// per-invocation override flag on `weknora link` itself - to record under a
|
||||
// different profile, use the global persistent flag (`weknora --profile
|
||||
// staging link --kb my-kb`); the active profile at link time is what gets
|
||||
// written.
|
||||
func resolveProfile(f *cmdutil.Factory) (string, error) {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if cfg.CurrentProfile == "" {
|
||||
// `link` binds a directory to a profile+KB, so it needs a configured
|
||||
// profile — env credentials (WEKNORA_API_KEY) alone have no profile to
|
||||
// record. Point at profile setup (not `auth login`, which loops with no
|
||||
// profile) and name the headless alternative so an env-cred agent isn't
|
||||
// stranded on a misleading hint.
|
||||
return "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
"`link` records an active profile, but none is configured").
|
||||
WithHint("register one with `weknora profile add <name> --host <url> --use`; for a headless (WEKNORA_API_KEY) workflow, skip `link` and pass --kb per command or set WEKNORA_KB_ID").
|
||||
WithRetryArgv([]string{"weknora", "profile", "add", "--help"})
|
||||
}
|
||||
return cfg.CurrentProfile, nil
|
||||
}
|
||||
|
||||
// resolveKB resolves --kb to (kbID, kbName). Name is empty when the user
|
||||
// passed an id directly. Falls through to an interactive prompt on a TTY
|
||||
// when --kb is empty; errors on non-TTY.
|
||||
func resolveKB(ctx context.Context, opts *Options, f *cmdutil.Factory) (string, string, error) {
|
||||
if opts.KB != "" {
|
||||
if cmdutil.IsKBID(opts.KB) {
|
||||
return opts.KB, "", nil
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
id, err := cmdutil.ResolveKBNameToID(ctx, cli, opts.KB)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return id, opts.KB, nil
|
||||
}
|
||||
if !iostreams.IO.IsStdoutTTY() {
|
||||
return "", "", cmdutil.NewError(cmdutil.CodeKBIDRequired, "--kb is required (no TTY for interactive prompt)")
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return promptForKB(ctx, cli, f)
|
||||
}
|
||||
|
||||
// promptForKB lists available knowledge bases on stderr, then asks the user
|
||||
// for an id or name. Resolved against the listed set so a typed name is
|
||||
// converted to the canonical id.
|
||||
func promptForKB(ctx context.Context, svc cmdutil.KBLister, f *cmdutil.Factory) (string, string, error) {
|
||||
kbs, err := svc.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
return "", "", cmdutil.WrapHTTP(err, "list knowledge bases")
|
||||
}
|
||||
if len(kbs) == 0 {
|
||||
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, "no knowledge bases visible to active profile; create one first")
|
||||
}
|
||||
fmt.Fprintln(iostreams.IO.Err, "Available knowledge bases:")
|
||||
for _, kb := range kbs {
|
||||
fmt.Fprintf(iostreams.IO.Err, " %s %s\n", kb.ID, kb.Name)
|
||||
}
|
||||
p := f.Prompter()
|
||||
answer, err := p.Input("Knowledge base id or name", "")
|
||||
if err != nil {
|
||||
return "", "", cmdutil.Wrapf(cmdutil.CodeInputMissingFlag, err, "kb prompt")
|
||||
}
|
||||
for _, kb := range kbs {
|
||||
if kb.ID == answer || kb.Name == answer {
|
||||
return kb.ID, kb.Name, nil
|
||||
}
|
||||
}
|
||||
return "", "", cmdutil.NewError(cmdutil.CodeKBNotFound, fmt.Sprintf("knowledge base not found: %s", answer))
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package linkcmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
func chdir(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
prev, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chdir(dir))
|
||||
t.Cleanup(func() { _ = os.Chdir(prev) })
|
||||
}
|
||||
|
||||
func fakeKBServer(t *testing.T, kbs []sdk.KnowledgeBase) *httptest.Server {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/knowledge-bases", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(sdk.KnowledgeBaseListResponse{Success: true, Data: kbs})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func newFactory(currentCtx string, client *sdk.Client) *cmdutil.Factory {
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: currentCtx,
|
||||
Profiles: map[string]config.Profile{
|
||||
currentCtx: {Host: "https://example"},
|
||||
},
|
||||
}
|
||||
return &cmdutil.Factory{
|
||||
Config: func() (*config.Config, error) { return cfg, nil },
|
||||
Client: func() (*sdk.Client, error) {
|
||||
if client == nil {
|
||||
return nil, errors.New("client not configured")
|
||||
}
|
||||
return client, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestLink_ByID(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
chdir(t, dir)
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
f := newFactory("default", nil)
|
||||
opts := &Options{KB: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"}
|
||||
require.NoError(t, runLink(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f))
|
||||
|
||||
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
|
||||
p, err := projectlink.Load(linkPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", p.KBID)
|
||||
assert.Equal(t, "default", p.Profile)
|
||||
assert.Contains(t, out.String(), "✓")
|
||||
}
|
||||
|
||||
func TestLink_ByName(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
chdir(t, dir)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
srv := fakeKBServer(t, []sdk.KnowledgeBase{
|
||||
{ID: "kb_a", Name: "foo"},
|
||||
{ID: "kb_b", Name: "bar"},
|
||||
})
|
||||
cli := sdk.NewClient(srv.URL)
|
||||
f := newFactory("default", cli)
|
||||
opts := &Options{KB: "foo"}
|
||||
require.NoError(t, runLink(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f))
|
||||
|
||||
p, err := projectlink.Load(filepath.Join(dir, ".weknora", "project.yaml"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "kb_a", p.KBID)
|
||||
}
|
||||
|
||||
func TestLink_KBNotFound(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
chdir(t, dir)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
srv := fakeKBServer(t, []sdk.KnowledgeBase{{ID: "kb_a", Name: "foo"}})
|
||||
cli := sdk.NewClient(srv.URL)
|
||||
f := newFactory("default", cli)
|
||||
opts := &Options{KB: "missing"}
|
||||
err := runLink(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeKBNotFound, typed.Code)
|
||||
}
|
||||
|
||||
func TestLink_OverwritesExisting(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
chdir(t, dir)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
// Pre-existing link.
|
||||
linkPath := filepath.Join(dir, ".weknora", "project.yaml")
|
||||
require.NoError(t, projectlink.Save(linkPath, &projectlink.Project{
|
||||
Profile: "default", KBID: "11111111-1111-4111-8111-111111111111",
|
||||
}))
|
||||
|
||||
f := newFactory("default", nil)
|
||||
opts := &Options{KB: "22222222-2222-4222-8222-222222222222"}
|
||||
require.NoError(t, runLink(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f))
|
||||
|
||||
p, err := projectlink.Load(linkPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "22222222-2222-4222-8222-222222222222", p.KBID, "link should overwrite silently")
|
||||
}
|
||||
|
||||
// TestLink_NonInteractive_NoKB exercises the non-TTY-without-flag error path.
|
||||
// SetForTest gives us a non-TTY iostreams, so omitting --kb must error rather
|
||||
// than hang on a prompt.
|
||||
func TestLink_NonInteractive_NoKB(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
chdir(t, dir)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
f := newFactory("default", nil)
|
||||
opts := &Options{} // no KB
|
||||
err := runLink(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeKBIDRequired, typed.Code)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package linkcmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||
)
|
||||
|
||||
// unlinkFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `unlink`. Tracks the small unlinkResult struct.
|
||||
var unlinkFields = []string{"project_link_path"}
|
||||
|
||||
type UnlinkOptions struct {
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// unlinkResult is the typed payload emitted under data.
|
||||
type unlinkResult struct {
|
||||
ProjectLinkPath string `json:"project_link_path"`
|
||||
}
|
||||
|
||||
// NewCmdUnlink builds `weknora unlink`. Walks up from cwd so a user in
|
||||
// a subdirectory of a linked project can unlink without cd-ing up first.
|
||||
func NewCmdUnlink() *cobra.Command {
|
||||
opts := &UnlinkOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "unlink",
|
||||
Short: "Remove the directory's knowledge-base binding",
|
||||
Long: `Removes the .weknora/project.yaml that ` + "`weknora link`" + ` previously
|
||||
wrote, so subsequent commands no longer auto-resolve --kb from the link.
|
||||
|
||||
Walks up from the current directory until a link is found, mirroring the
|
||||
discovery that ` + "`--kb`" + ` resolution uses; you do not need to cd to the
|
||||
project root to unlink. Errors with input.invalid_argument when no link
|
||||
is present anywhere in the parent chain.`,
|
||||
Example: ` weknora unlink # remove the binding for this project
|
||||
weknora unlink --format json # bare JSON (CI / agents)`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
// Pure-local validation runs before the dry-run gate so --dry-run
|
||||
// rejects identically to the live path. projectlink.Discover only
|
||||
// reads the filesystem (no SDK / network).
|
||||
cwd, cwdErr := os.Getwd()
|
||||
if cwdErr != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, cwdErr, "get cwd")
|
||||
}
|
||||
_, found, discErr := projectlink.Discover(cwd)
|
||||
if discErr != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, discErr, "discover project link")
|
||||
}
|
||||
if !found {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("no %s/%s found at or above %s", projectlink.DirName, projectlink.FileName, cwd),
|
||||
Hint: "run `weknora link --kb <id>` first, or check you're in the right directory",
|
||||
}
|
||||
}
|
||||
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
|
||||
Action: "unlink",
|
||||
Args: map[string]any{},
|
||||
}); handled {
|
||||
return err
|
||||
}
|
||||
return runUnlink(opts, fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, unlinkFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Remove the .weknora/project.yaml KB binding from the current directory tree. No flags required; walks up from cwd to find the link.",
|
||||
Output: "envelope.data has project_link_path of the removed file",
|
||||
Examples: []string{
|
||||
"weknora unlink",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runUnlink(opts *UnlinkOptions, fopts *cmdutil.FormatOptions) error {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "get cwd")
|
||||
}
|
||||
linkPath, found, err := projectlink.Discover(cwd)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "discover project link")
|
||||
}
|
||||
if !found {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("no %s/%s found at or above %s", projectlink.DirName, projectlink.FileName, cwd),
|
||||
Hint: "run `weknora link --kb <id>` first, or check you're in the right directory",
|
||||
}
|
||||
}
|
||||
if err := projectlink.Remove(linkPath); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "remove %s", linkPath)
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, unlinkResult{ProjectLinkPath: linkPath}, nil)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Unlinked %s\n", linkPath)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package linkcmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/projectlink"
|
||||
)
|
||||
|
||||
// mkLinkFile seeds .weknora/project.yaml in dir so the unlink path has
|
||||
// something to remove. Returns the absolute file path.
|
||||
func mkLinkFile(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
full := filepath.Join(dir, projectlink.DirName, projectlink.FileName)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
if err := projectlink.Save(full, &projectlink.Project{Profile: "default", KBID: "kb_abc"}); err != nil {
|
||||
t.Fatalf("save: %v", err)
|
||||
}
|
||||
return full
|
||||
}
|
||||
|
||||
func TestUnlink_RemovesLinkInCwd(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
tmp := t.TempDir()
|
||||
linkPath := mkLinkFile(t, tmp)
|
||||
t.Chdir(tmp)
|
||||
|
||||
if err := runUnlink(&UnlinkOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runUnlink: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(linkPath); !os.IsNotExist(err) {
|
||||
t.Errorf("link file should be gone, got err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlink_WalksUpFromSubdir(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
root := t.TempDir()
|
||||
linkPath := mkLinkFile(t, root)
|
||||
sub := filepath.Join(root, "deep", "nested")
|
||||
if err := os.MkdirAll(sub, 0o755); err != nil {
|
||||
t.Fatalf("mkdir sub: %v", err)
|
||||
}
|
||||
t.Chdir(sub)
|
||||
|
||||
if err := runUnlink(&UnlinkOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runUnlink: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(linkPath); !os.IsNotExist(err) {
|
||||
t.Errorf("parent link file should be gone, got err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlink_NoLink_Errors(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
tmp := t.TempDir()
|
||||
t.Chdir(tmp)
|
||||
|
||||
err := runUnlink(&UnlinkOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatal("expected error when no link present")
|
||||
}
|
||||
var typed *cmdutil.Error
|
||||
if !errors.As(err, &typed) {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
||||
}
|
||||
if typed.Code != cmdutil.CodeInputInvalidArgument {
|
||||
t.Errorf("expected CodeInputInvalidArgument, got %s", typed.Code)
|
||||
}
|
||||
if !strings.Contains(typed.Message, projectlink.DirName) {
|
||||
t.Errorf("error message should name the missing path; got %q", typed.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlink_JSON_BareObject(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
tmp := t.TempDir()
|
||||
mkLinkFile(t, tmp)
|
||||
t.Chdir(tmp)
|
||||
|
||||
if err := runUnlink(&UnlinkOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
|
||||
t.Fatalf("runUnlink: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(got), &env); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, got)
|
||||
}
|
||||
if !env.OK {
|
||||
t.Errorf("envelope.ok must be true, got %q", got)
|
||||
}
|
||||
for _, want := range []string{`"project_link_path"`, projectlink.DirName} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q in output:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user