Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmd/sync/attachments.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func newAttachmentScopeCmd(client resources.Client, kind syncdomain.AttachmentKi
newWatchCmd(client, scope, help),
newAttachmentAddCmd(client, kind),
newAttachmentDetachCmd(client, kind),
newLinkCmd(client, syncdomain.Kind(kind)),
)
cmd.SetUsageTemplate(resourcescmd.SubcommandUsageTemplate())
return cmd
Expand Down
136 changes: 136 additions & 0 deletions cmd/sync/link.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package sync

import (
"errors"
"fmt"
"strings"

"github.com/spf13/cobra"

"github.com/launchdarkly/ldcli/internal/resources"
syncdomain "github.com/launchdarkly/ldcli/internal/sync"
syncprompt "github.com/launchdarkly/ldcli/internal/sync/prompt"
)

// linkExamples are the examples of the link command of each resource kind.
var linkExamples = map[syncdomain.Kind]string{
syncdomain.KindVariation: ` # Link one Python agent to a prompt variation
ldcli sync prompts link \
--file app/agents.py \
--format python \
--select 'agents[id="support"]' \
--map prompt=instructions \
--project production --config-key support --key default \
--yes --no-input`,
syncdomain.KindTool: ` # Link one TypeScript MCP tool
ldcli sync tools link \
--file src/server.ts \
--format typescript \
--select 'tools[id="lookup_order"]' \
--map description=description \
--project production --key lookup_order \
--yes --no-input`,
syncdomain.KindSkill: ` # Link one Agent Skill file
ldcli sync skills link \
--file .agents/skills/refunds/SKILL.md \
--format agent-skill \
--project production --key refunds \
--yes --no-input`,
}

// newLinkCmd creates the link command of one resource kind. Link records a
// .ref.yaml descriptor for a repository source and then syncs the resource.
func newLinkCmd(client resources.Client, kind syncdomain.Kind) *cobra.Command {
scope, noun, help := syncdomain.ScopePrompts, "prompt variation", questionFlagHelp
if kind != syncdomain.KindVariation {
scope = syncdomain.Scope(kind + "s")
noun = string(kind)
help = attachmentFlagHelp(syncdomain.AttachmentKind(kind), false)
}
cmd := &cobra.Command{
Use: "link",
Short: fmt.Sprintf("Link a repository source to one %s", noun),
Long: fmt.Sprintf("Link a repository source to one %s. "+
"Link reads only the named file, shows the descriptor and the sync plan, and writes the descriptor after you confirm. "+
"It then syncs the %s.", noun, noun),
Example: linkExamples[kind],
Args: validatedArgs(cobra.NoArgs),
RunE: runCommand(client, scope, func(cmd *cobra.Command, _ []string) (syncprompt.CommandAction, error) {
id, err := sourceLinkID(cmd, kind)
if err != nil {
return nil, err
}
fieldMap, err := parseFieldMappings(mustStringArray(cmd, mapFlag))
if err != nil {
return nil, err
}
return syncprompt.SourceLinkAction{
ID: id,
File: mustString(cmd, fileFlag),
Format: mustString(cmd, formatFlag),
Select: mustString(cmd, selectFlag),
Map: fieldMap,
}, nil
}),
}
addTargetFlags(cmd, help)
cmd.Flags().String(fileFlag, "", "Repository source file")
cmd.Flags().String(formatFlag, "", "Source format, for example python, typescript, markdown, or json")
cmd.Flags().String(selectFlag, "", "Source value to select, for example 'agents[id=\"support\"]'")
cmd.Flags().StringArray(mapFlag, nil, "Mapped field in field=path form. Repeat for more fields.")
_ = cmd.MarkFlagRequired(fileFlag)
_ = cmd.MarkFlagRequired(formatFlag)
addApplyFlags(cmd, scope, false)
return cmd
}

// sourceLinkID reads the resource that the target flags name. Link needs
// exactly one resource.
func sourceLinkID(cmd *cobra.Command, kind syncdomain.Kind) (syncdomain.ResourceID, error) {
filter := targetFilter(cmd)
if err := filter.Validate(kind); err != nil {
return syncdomain.ResourceID{}, err
}
if filter.Project == "" {
return syncdomain.ResourceID{}, errors.New("--project is required")
}
if len(filter.Keys) != 1 {
return syncdomain.ResourceID{}, errors.New("link requires exactly one --key")
}
if kind == syncdomain.KindVariation {
if filter.ConfigKey == "" {
return syncdomain.ResourceID{}, errors.New("--config-key is required")
}
return syncdomain.VariationID(filter.Project, filter.ConfigKey, filter.Keys[0]), nil
}
return syncdomain.ResourceID{Kind: kind, ProjectKey: filter.Project, LookupKey: filter.Keys[0]}, nil
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

// parseFieldMappings reads the --map values. Each value is field=path.
func parseFieldMappings(values []string) (map[string]string, error) {
if len(values) == 0 {
return nil, nil
}
fieldMap := make(map[string]string, len(values))
for _, value := range values {
field, path, ok := strings.Cut(value, "=")
if !ok || field == "" || path == "" {
return nil, fmt.Errorf("invalid --map %q; expected field=path", value)
}
if _, duplicate := fieldMap[field]; duplicate {
return nil, fmt.Errorf("--map field %q was provided more than once", field)
}
fieldMap[field] = path
}
return fieldMap, nil
}

func mustString(cmd *cobra.Command, name string) string {
value, _ := cmd.Flags().GetString(name)
return value
}

func mustStringArray(cmd *cobra.Command, name string) []string {
value, _ := cmd.Flags().GetStringArray(name)
return value
}
96 changes: 95 additions & 1 deletion cmd/sync/prompt.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package sync

import (
"encoding/json"
"fmt"
"os"
"strings"
Expand All @@ -12,6 +13,7 @@ import (
"github.com/launchdarkly/ldcli/cmd/cliflags"
resourcescmd "github.com/launchdarkly/ldcli/cmd/resources"
"github.com/launchdarkly/ldcli/cmd/validators"
lderrors "github.com/launchdarkly/ldcli/internal/errors"
"github.com/launchdarkly/ldcli/internal/output"
"github.com/launchdarkly/ldcli/internal/resources"
syncdomain "github.com/launchdarkly/ldcli/internal/sync"
Expand All @@ -26,13 +28,16 @@ const (
descriptionFlag = "description"
diffFlag = "diff"
dryRunFlag = "dry-run"
fileFlag = "file"
formatFlag = "format"
jsonSchemaFlag = "json-schema"
keyFlag = "key"
modelConfigKeyFlag = "model-config-key"
nameFlag = "name"
noInputFlag = "no-input"
resolveFlag = "resolve"
selectFlag = "select"
mapFlag = "map"
toFlag = "to"
yesFlag = "yes"
)
Expand Down Expand Up @@ -67,6 +72,7 @@ func NewPromptCmd(client resources.Client) *cobra.Command {
newAddCmd(client),
newAttachCmd(client),
newDetachCmd(client),
newLinkCmd(client, syncdomain.KindVariation),
)
cmd.SetUsageTemplate(resourcescmd.SubcommandUsageTemplate())

Expand Down Expand Up @@ -119,12 +125,100 @@ func runCommand(client resources.Client, scope syncdomain.Scope, buildAction act
ErrorOutput: cmd.ErrOrStderr(),
})
if err != nil {
return output.NewCmdOutputError(err, outputKind)
return syncCommandOutputError(err, outputKind)
}
return nil
}
}

// syncCommandOutputError renders a sync error with its stable fields. A plan
// error can join several problems, so the output then lists every one of them.
func syncCommandOutputError(err error, outputKind string) error {
problems := syncdomain.ProblemsFrom(err)
var report any
switch {
case len(problems) == 0:
case len(problems) == 1 && len(leafErrors(err)) == 1:
report = problems[0]
if outputKind != "json" {
report = plaintextProblem(problems[0])
}
default:
message := err.Error()
if outputKind != "json" {
message = plaintextMessage(err)
}
report = struct {
*syncdomain.Problem
Problems []*syncdomain.Problem `json:"problems"`
}{
Problem: syncdomain.NewProblem(syncdomain.ErrorMultipleProblems, message, ""),
Problems: problems,
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
if report != nil {
if data, marshalErr := json.Marshal(report); marshalErr == nil {
err = lderrors.NewError(string(data))
}
}
return output.NewCmdOutputError(err, outputKind)
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

// plaintextProblem puts the resource and the source location of a problem
// in its message, because plaintext output prints only the message, the
// code, and the suggestion.
func plaintextProblem(problem *syncdomain.Problem) *syncdomain.Problem {
located := *problem
var context []string
if problem.Resource != "" {
context = append(context, problem.Resource)
}
if problem.File != "" {
location := problem.File
if problem.Line > 0 {
location += fmt.Sprintf(":%d", problem.Line)
if problem.Column > 0 {
location += fmt.Sprintf(":%d", problem.Column)
}
}
context = append(context, location)
}
if len(context) != 0 {
located.Message = strings.Join(context, " ") + ": " + problem.Message
}
return &located
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

// plaintextMessage lists the leaf errors of a joined error, one per line,
// with the resource and the source location of each problem.
func plaintextMessage(err error) string {
var lines []string
for _, leaf := range leafErrors(err) {
if problem, ok := syncdomain.ProblemFrom(leaf); ok {
lines = append(lines, plaintextProblem(problem).Error())
continue
}
lines = append(lines, leaf.Error())
}
return strings.Join(lines, "\n")
}

// leafErrors returns the errors of a tree that wrap nothing else. A plan
// error joins its problems, so a join of one problem has one leaf.
func leafErrors(err error) []error {
if err == nil {
return nil
}
if joined, ok := err.(interface{ Unwrap() []error }); ok {
var leaves []error
for _, child := range joined.Unwrap() {
leaves = append(leaves, leafErrors(child)...)
}
return leaves
}
return []error{err}
}

// newWatchCmd creates the watch command of a scope. help is the help text of
// the target flags of the root sync of the scope.
func newWatchCmd(client resources.Client, scope syncdomain.Scope, help targetFlagHelp) *cobra.Command {
Expand Down
Loading
Loading