diff --git a/CLI-IMPLEMENTATION.md b/CLI-IMPLEMENTATION.md index 72b17fd..c9065a6 100644 --- a/CLI-IMPLEMENTATION.md +++ b/CLI-IMPLEMENTATION.md @@ -2,7 +2,8 @@ Status: implementation sequence, updated 2026-11-11. Native Go profiling and binding commands are implemented, with CI coverage for the relocated CLI and shared YAML resources. -System-package distribution, add-ons, and upstream workflow migration remain planned. +The TypeScript add-on runs from PATH (`rc profile typescript`, `rc plugins list`). Add-on descriptors, `rc doctor`, +other languages, system-package distribution, and upstream workflow migration remain planned. Repository: github.com/runtimeconditions/rc-cli; executable and command name: `rc`. System package and Homebrew formula name: `rc-cli`; releases use independent `vMAJOR.MINOR.PATCH` tags. This plan implements [CLI-PLANNING.md](../extensions/tooling/extension-bindings/CLI-PLANNING.md). @@ -59,6 +60,7 @@ rc bindings [flags]` | Run the installed TypeScript profiler. | +| `rc plugins list [--output yaml]` | Show the Go profiler and each add-on's status, version, and path. | + +Everything after `typescript` goes to the add-on unchanged, so it keeps its own flags +(for example `--project` instead of `--dir`). `rc` looks for `rc-profiler-typescript`, then +`runtimeconditions-typescript-profiler`, on `PATH`; `RC_TYPESCRIPT_PROFILER` can name an +absolute path instead. It runs the add-on only if `--version --json` lists the core profile +schema `rc` targets (0.4.0). The add-on's output and exit status pass through. + ## Binding commands ```sh diff --git a/internal/cli/plugins.go b/internal/cli/plugins.go new file mode 100644 index 0000000..902bbbe --- /dev/null +++ b/internal/cli/plugins.go @@ -0,0 +1,179 @@ +package cli + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "strings" + "text/tabwriter" + + "github.com/runtimeconditions/rc-cli/internal/plugins" + "github.com/runtimeconditions/rc-cli/internal/process" + "github.com/spf13/cobra" + "go.yaml.in/yaml/v3" +) + +// coreSchemaVersion is the core profile schema this rc is built against. It is the +// version pinned in distribution/components.lock.yaml and scripts/build.go, and an +// add-on must report it in `--version --json` before rc runs the add-on. +const coreSchemaVersion = "0.4.0" + +// Dependencies are the process-level services optional language commands use. +type Dependencies struct { + Finder plugins.Finder + Runner process.Runner +} + +// DefaultDependencies looks add-ons up on the real PATH and runs real subprocesses. +func DefaultDependencies() Dependencies { + return Dependencies{ + Finder: plugins.Finder{LookPath: exec.LookPath, Getenv: os.Getenv}, + Runner: process.OS{}, + } +} + +// processExit carries an add-on's nonzero exit status out as the exit status of rc. +// The add-on has already printed its own diagnostics, so rc prints nothing more. +type processExit struct{ code int } + +func (e processExit) Error() string { return fmt.Sprintf("add-on exited with status %d", e.code) } + +func commandContext(cmd *cobra.Command) context.Context { + if ctx := cmd.Context(); ctx != nil { + return ctx + } + return context.Background() +} + +// newLanguageCommand runs an installed add-on: `rc profile `. +// Everything after the language word reaches the add-on unchanged, so its own command +// tree, flags, repeated values, and `--` keep their meaning. +func newLanguageCommand(language plugins.Language, deps Dependencies) *cobra.Command { + return &cobra.Command{ + Use: language.ID + " [command] [flags]", + Short: "Generate profiles with the installed " + language.Display + " profiler", + Long: fmt.Sprintf("Run the installed %s profiler. The arguments after %q go to it unchanged, so its own help applies: rc profile %s --help.\n"+ + "It is installed separately, for example with: %s. It must report core profile schema %s.", + language.Display, language.ID, language.ID, language.InstallHint, coreSchemaVersion), + Example: fmt.Sprintf(" rc profile %s generate --project ./service --name orders --workload-uri https://example.com/orders", language.ID), + DisableFlagParsing: true, + Args: cobra.ArbitraryArgs, + ValidArgsFunction: cobra.NoFileCompletions, + RunE: func(cmd *cobra.Command, args []string) error { + ctx := commandContext(cmd) + found, err := deps.Finder.Find(language) + if err != nil { + return err + } + info, err := plugins.Describe(ctx, deps.Runner, found.Path) + if err != nil { + return fmt.Errorf("the %s profiler at %s: %w", language.Display, found.Path, err) + } + if !info.Supports(coreSchemaVersion) { + return fmt.Errorf("the %s profiler %s at %s supports core profile schema %s, but this rc targets %s; install a matching version with: %s", + language.Display, info.Version, found.Path, strings.Join(info.CoreSchemas, ", "), coreSchemaVersion, language.InstallHint) + } + code, err := deps.Runner.Run(ctx, process.Spec{ + Path: found.Path, Args: args, + Stdin: cmd.InOrStdin(), Stdout: cmd.OutOrStdout(), Stderr: cmd.ErrOrStderr(), + }) + if err != nil { + return err + } + if code != 0 { + return processExit{code} + } + return nil + }, + } +} + +type pluginRow struct { + Language string `yaml:"language"` + Status string `yaml:"status"` + Origin string `yaml:"origin,omitempty"` + Path string `yaml:"path,omitempty"` + Version string `yaml:"version,omitempty"` + CoreSchemas []string `yaml:"coreSchemas,omitempty"` + Detail string `yaml:"detail,omitempty"` +} + +func inspectLanguage(ctx context.Context, language plugins.Language, deps Dependencies) pluginRow { + row := pluginRow{Language: language.ID} + found, err := deps.Finder.Find(language) + var missing plugins.NotInstalledError + var runtime plugins.RuntimeMissingError + switch { + case errors.As(err, &missing): + row.Status, row.Detail = "missing", "install with: "+language.InstallHint + return row + case errors.As(err, &runtime): + row.Status, row.Detail = "runtime-missing", err.Error() + return row + case err != nil: + row.Status, row.Detail = "unusable", err.Error() + return row + } + row.Origin, row.Path = found.Origin, found.Path + info, err := plugins.Describe(ctx, deps.Runner, found.Path) + if err != nil { + row.Status, row.Detail = "unreadable", err.Error() + return row + } + row.Version, row.CoreSchemas = info.Version, info.CoreSchemas + if info.Supports(coreSchemaVersion) { + row.Status = "ready" + } else { + row.Status, row.Detail = "incompatible", "this rc targets core profile schema "+coreSchemaVersion + } + return row +} + +// newPluginsCommand lists the profilers rc can use. It reads metadata only: it never +// runs a profiler on a workload. +func newPluginsCommand(deps Dependencies) *cobra.Command { + cmd := &cobra.Command{ + Use: "plugins", Short: "Inspect optional language profilers", + Args: usageArgs(cobra.NoArgs), ValidArgsFunction: cobra.NoFileCompletions, + RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, + } + var output string + list := &cobra.Command{ + Use: "list", Short: "List the Go profiler built into rc and the installed language add-ons", + Args: usageArgs(cobra.NoArgs), ValidArgsFunction: cobra.NoFileCompletions, + RunE: func(cmd *cobra.Command, _ []string) error { + rows := []pluginRow{{ + Language: "go", Status: "built-in", Origin: "linked", + Version: linkedGoProfilerIdentity().Version, CoreSchemas: []string{coreSchemaVersion}, + }} + for _, language := range plugins.Languages() { + rows = append(rows, inspectLanguage(commandContext(cmd), language, deps)) + } + switch output { + case "text": + table := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 4, 2, ' ', 0) + fmt.Fprintln(table, "LANGUAGE\tSTATUS\tVERSION\tPATH") + for _, row := range rows { + fmt.Fprintf(table, "%s\t%s\t%s\t%s\n", row.Language, row.Status, row.Version, row.Path) + } + return table.Flush() + case "yaml": + encoder := yaml.NewEncoder(cmd.OutOrStdout()) + encoder.SetIndent(2) + if err := encoder.Encode(struct { + Plugins []pluginRow `yaml:"plugins"` + }{rows}); err != nil { + return err + } + return encoder.Close() + default: + return usageError{fmt.Errorf("unsupported output format %q; use text or yaml", output)} + } + }, + } + list.Flags().StringVar(&output, "output", "text", "Output format: text or yaml") + cmd.AddCommand(list) + return cmd +} diff --git a/internal/cli/plugins_test.go b/internal/cli/plugins_test.go new file mode 100644 index 0000000..021639a --- /dev/null +++ b/internal/cli/plugins_test.go @@ -0,0 +1,189 @@ +package cli + +import ( + "bytes" + "context" + "errors" + "os" + "slices" + "strings" + "testing" + + "github.com/runtimeconditions/rc-cli/internal/plugins" + "github.com/runtimeconditions/rc-cli/internal/process" + "go.yaml.in/yaml/v3" +) + +// fakeRunner answers `--version --json` itself and records every other invocation. +type fakeRunner struct { + version string + code int + output string + calls []process.Spec +} + +func (f *fakeRunner) Run(_ context.Context, spec process.Spec) (int, error) { + if slices.Equal(spec.Args, []string{"--version", "--json"}) { + spec.Stdout.Write([]byte(f.version)) + return 0, nil + } + f.calls = append(f.calls, spec) + spec.Stdout.Write([]byte(f.output)) + return f.code, nil +} + +const readyVersion = `{"name":"@runtimeconditions/typescript-profiler","version":"0.2.0","coreSchemas":["0.4.0"]}` + +func deps(runner process.Runner, installed ...string) Dependencies { + present := map[string]bool{} + for _, name := range installed { + present[name] = true + } + return Dependencies{ + Finder: plugins.Finder{ + LookPath: func(name string) (string, error) { + if present[name] { + return "/usr/bin/" + name, nil + } + return "", errors.New("not found") + }, + Getenv: func(string) string { return "" }, + }, + Runner: runner, + } +} + +func run(t *testing.T, d Dependencies, args ...string) (int, string, string) { + t.Helper() + var out, errOut bytes.Buffer + code := ExecuteWith(context.Background(), args, BuildInfo{Version: "v0.1.0", Commit: "abc"}, IOStreams{Out: &out, ErrOut: &errOut}, d) + return code, out.String(), errOut.String() +} + +func TestAddOnReceivesItsArgumentsUnchangedAndItsOutputPassesThrough(t *testing.T) { + runner := &fakeRunner{version: readyVersion, output: "profile: yaml\n"} + args := []string{"generate", "--project", "./svc", "--name", "orders", "--workload-uri", "https://example.com/o", "--out", "-h", "--", "--odd", "a b", "--project", "again"} + code, out, errOut := run(t, deps(runner, "rc-profiler-typescript", "node"), append([]string{"profile", "typescript"}, args...)...) + if code != 0 || out != "profile: yaml\n" || errOut != "" { + t.Fatalf("code=%d stdout=%q stderr=%q", code, out, errOut) + } + if len(runner.calls) != 1 || runner.calls[0].Path != "/usr/bin/rc-profiler-typescript" || !slices.Equal(runner.calls[0].Args, args) { + t.Fatalf("calls %+v", runner.calls) + } +} + +func TestAddOnHelpAndVersionFlagsReachTheAddOn(t *testing.T) { + for _, args := range [][]string{{"--help"}, {"-h"}, {"--version"}, {"generate", "--help"}, {}} { + runner := &fakeRunner{version: readyVersion} + if code, _, _ := run(t, deps(runner, "rc-profiler-typescript", "node"), append([]string{"profile", "typescript"}, args...)...); code != 0 { + t.Fatalf("%v: code %d", args, code) + } + if len(runner.calls) != 1 || !slices.Equal(runner.calls[0].Args, args) { + t.Fatalf("%v: calls %+v", args, runner.calls) + } + } +} + +func TestAddOnExitStatusIsTheExitStatusOfRcWithoutExtraMessages(t *testing.T) { + runner := &fakeRunner{version: readyVersion, code: 7} + code, _, errOut := run(t, deps(runner, "rc-profiler-typescript", "node"), "profile", "typescript", "generate") + if code != 7 || errOut != "" { + t.Fatalf("code=%d stderr=%q", code, errOut) + } +} + +func TestMissingAddOnAndMissingRuntimeAreReportedOnceWithWhatToInstall(t *testing.T) { + runner := &fakeRunner{version: readyVersion} + code, _, errOut := run(t, deps(runner, "node"), "profile", "typescript", "generate") + if code != 1 || strings.Count(errOut, "rc:") != 1 || !strings.Contains(errOut, "TypeScript profiler is not installed") || + !strings.Contains(errOut, "npm install --global @runtimeconditions/typescript-profiler") || strings.Contains(errOut, "Usage:") { + t.Fatalf("code=%d stderr=%q", code, errOut) + } + code, _, errOut = run(t, deps(runner, "rc-profiler-typescript"), "profile", "typescript", "generate") + if code != 1 || !strings.Contains(errOut, "needs node") { + t.Fatalf("code=%d stderr=%q", code, errOut) + } + if len(runner.calls) != 0 { + t.Fatalf("nothing may run: %+v", runner.calls) + } +} + +func TestAnAddOnForAnotherCoreSchemaIsRejectedBeforeItRuns(t *testing.T) { + runner := &fakeRunner{version: `{"name":"x","version":"0.1.0","coreSchemas":["0.3.0"]}`} + code, _, errOut := run(t, deps(runner, "rc-profiler-typescript", "node"), "profile", "typescript", "generate") + if code != 1 || !strings.Contains(errOut, "supports core profile schema 0.3.0") || !strings.Contains(errOut, "targets 0.4.0") || len(runner.calls) != 0 { + t.Fatalf("code=%d stderr=%q calls=%+v", code, errOut, runner.calls) + } + runner = &fakeRunner{version: "0.2.0\n"} + code, _, errOut = run(t, deps(runner, "rc-profiler-typescript", "node"), "profile", "typescript", "generate") + if code != 1 || !strings.Contains(errOut, "did not print the expected JSON") || len(runner.calls) != 0 { + t.Fatalf("code=%d stderr=%q", code, errOut) + } +} + +func TestPluginsListReportsEveryStatus(t *testing.T) { + read := func(d Dependencies) []pluginRow { + code, out, errOut := run(t, d, "plugins", "list", "--output", "yaml") + if code != 0 || errOut != "" { + t.Fatalf("code=%d stderr=%q", code, errOut) + } + var document struct { + Plugins []pluginRow `yaml:"plugins"` + } + decoder := yaml.NewDecoder(strings.NewReader(out)) + decoder.KnownFields(true) + if err := decoder.Decode(&document); err != nil { + t.Fatal(err) + } + return document.Plugins + } + ready := read(deps(&fakeRunner{version: readyVersion}, "rc-profiler-typescript", "node")) + if len(ready) != 2 || ready[0].Language != "go" || ready[0].Status != "built-in" || + ready[1].Language != "typescript" || ready[1].Status != "ready" || ready[1].Version != "0.2.0" || + ready[1].Path != "/usr/bin/rc-profiler-typescript" || ready[1].Origin != "path" { + t.Fatalf("%+v", ready) + } + for status, d := range map[string]Dependencies{ + "missing": deps(&fakeRunner{}), + "runtime-missing": deps(&fakeRunner{}, "rc-profiler-typescript"), + "unreadable": deps(&fakeRunner{version: "not json"}, "rc-profiler-typescript", "node"), + "incompatible": deps(&fakeRunner{version: `{"name":"x","version":"1","coreSchemas":["0.3.0"]}`}, "rc-profiler-typescript", "node"), + } { + if rows := read(d); rows[1].Status != status || rows[1].Detail == "" { + t.Errorf("want %s, got %+v", status, rows[1]) + } + } +} + +func TestPluginsListTextAndHelp(t *testing.T) { + code, out, _ := run(t, deps(&fakeRunner{version: readyVersion}, "rc-profiler-typescript", "node"), "plugins", "list") + lines := strings.Split(strings.TrimSpace(out), "\n") + if code != 0 || len(lines) != 3 || !strings.HasPrefix(lines[0], "LANGUAGE") || + !slices.Equal(strings.Fields(lines[2]), []string{"typescript", "ready", "0.2.0", "/usr/bin/rc-profiler-typescript"}) { + t.Fatalf("code=%d %q", code, out) + } + if code, _, errOut := run(t, deps(&fakeRunner{}), "plugins", "list", "--output", "json"); code != 2 || !strings.Contains(errOut, "unsupported output format") { + t.Fatalf("code=%d %q", code, errOut) + } + code, out, _ = run(t, deps(&fakeRunner{}), "profile", "--help") + if code != 0 || !strings.Contains(out, "typescript") || !strings.Contains(out, "go ") { + t.Fatalf("profile help %q", out) + } +} + +func TestCoreSchemaVersionMatchesTheComponentLock(t *testing.T) { + data, err := os.ReadFile("../../distribution/components.lock.yaml") + if err != nil { + t.Fatal(err) + } + var lock struct { + GoProfiler struct { + CoreSchema struct { + Version string `yaml:"version"` + } `yaml:"coreSchema"` + } `yaml:"goProfiler"` + } + if err := yaml.Unmarshal(data, &lock); err != nil || lock.GoProfiler.CoreSchema.Version != coreSchemaVersion { + t.Fatalf("lock says %q, rc targets %q (%v)", lock.GoProfiler.CoreSchema.Version, coreSchemaVersion, err) + } +} diff --git a/internal/cli/profile.go b/internal/cli/profile.go index 1b3c86f..a7fa0be 100644 --- a/internal/cli/profile.go +++ b/internal/cli/profile.go @@ -1,6 +1,9 @@ package cli -import "github.com/spf13/cobra" +import ( + "github.com/runtimeconditions/rc-cli/internal/plugins" + "github.com/spf13/cobra" +) type goProfilerIdentity struct { Name string `yaml:"name"` @@ -13,8 +16,14 @@ type goProfilerIdentity struct { ModuleSum string `yaml:"moduleSum,omitempty"` } -func newProfileCommand() *cobra.Command { - return newGoProfileCommands(linkedGoProfilerAPI()) +// newProfileCommand adds the optional language profilers to the built-in Go profiler. +func newProfileCommand(deps Dependencies) *cobra.Command { + profile := newGoProfileCommands(linkedGoProfilerAPI()) + profile.Long += "\n\nOther languages run an installed add-on: rc profile ... (see rc plugins list)." + for _, language := range plugins.Languages() { + profile.AddCommand(newLanguageCommand(language, deps)) + } + return profile } func newGoProfileCommands(api goProfilerAPI) *cobra.Command { diff --git a/internal/cli/root.go b/internal/cli/root.go index a3fc354..aa1c06c 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -43,8 +43,13 @@ type usageError struct{ error } // Execute reports errors once and returns the process exit code without calling os.Exit. func Execute(ctx context.Context, args []string, build BuildInfo, streams IOStreams) int { + return ExecuteWith(ctx, args, build, streams, DefaultDependencies()) +} + +// ExecuteWith is Execute with explicit process-level dependencies. +func ExecuteWith(ctx context.Context, args []string, build BuildInfo, streams IOStreams, deps Dependencies) int { streams = streams.normalized() - root := NewRootCommand(build, streams) + root := NewRootCommandWith(build, streams, deps) // A non-nil empty slice prevents Cobra from falling back to os.Args. root.SetArgs(append([]string{}, args...)) err := ctx.Err() @@ -55,6 +60,10 @@ func Execute(ctx context.Context, args []string, build BuildInfo, streams IOStre if err == nil { return 0 } + var exit processExit + if errors.As(err, &exit) { + return exit.code + } fmt.Fprintf(streams.ErrOut, "rc: %v\n", err) if errors.Is(err, context.Canceled) { return 130 @@ -71,6 +80,11 @@ func Execute(ctx context.Context, args []string, build BuildInfo, streams IOStre // NewRootCommand returns a fresh command tree. Callers may attach feature commands before execution. func NewRootCommand(build BuildInfo, streams IOStreams) *cobra.Command { + return NewRootCommandWith(build, streams, DefaultDependencies()) +} + +// NewRootCommandWith builds the command tree with explicit process-level dependencies. +func NewRootCommandWith(build BuildInfo, streams IOStreams, deps Dependencies) *cobra.Command { streams = streams.normalized() if build.Version == "" { build.Version = "dev" @@ -95,7 +109,7 @@ func NewRootCommand(build BuildInfo, streams IOStreams) *cobra.Command { root.SetErr(streams.ErrOut) root.SetVersionTemplate("{{printf \"%s %s (%s)\\n\" .Name .Version (index .Annotations \"commit\")}}") root.SetFlagErrorFunc(func(_ *cobra.Command, err error) error { return usageError{err} }) - root.AddCommand(newVersionCommand(build), newCompletionCommand(), newProfileCommand(), newBindingsCommand()) + root.AddCommand(newVersionCommand(build), newCompletionCommand(), newProfileCommand(deps), newPluginsCommand(deps), newBindingsCommand()) root.InitDefaultHelpCmd() for _, cmd := range root.Commands() { if cmd.Name() == "help" { diff --git a/internal/plugins/plugins.go b/internal/plugins/plugins.go new file mode 100644 index 0000000..8e08a13 --- /dev/null +++ b/internal/plugins/plugins.go @@ -0,0 +1,163 @@ +// Package plugins finds optional language profilers and checks that they fit this rc. +// +// A language add-on is a separate executable. rc never enumerates arbitrary files: +// each supported language names the executables it looks for. +package plugins + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/runtimeconditions/rc-cli/internal/process" +) + +// Language is one optional profiler rc can run. +type Language struct { + // ID is the command word: rc profile ... + ID string + // Display is the name used in messages. + Display string + // Executables are looked up on PATH, in order. + Executables []string + // Runtime lists the programs the add-on needs on PATH, such as node. + Runtime []string + // OverrideEnv names an environment variable that holds an absolute executable path. + OverrideEnv string + // InstallHint is the command that installs the add-on with the language's own tooling. + InstallHint string +} + +// TypeScript is the TypeScript profiler, published to npm as @runtimeconditions/typescript-profiler. +var TypeScript = Language{ + ID: "typescript", + Display: "TypeScript", + Executables: []string{"rc-profiler-typescript", "runtimeconditions-typescript-profiler"}, + Runtime: []string{"node"}, + OverrideEnv: "RC_TYPESCRIPT_PROFILER", + InstallHint: "npm install --global @runtimeconditions/typescript-profiler", +} + +// Languages returns the optional languages rc supports. +func Languages() []Language { return []Language{TypeScript} } + +// Finder looks up executables. Tests replace both functions. +type Finder struct { + LookPath func(string) (string, error) + Getenv func(string) string +} + +// Found is an installed add-on. +type Found struct { + Language Language + Path string + // Origin is "override" for an explicit environment path, or "path". + Origin string +} + +// NotInstalledError reports that no executable for the language was found. +type NotInstalledError struct{ Language Language } + +func (e NotInstalledError) Error() string { + l := e.Language + return fmt.Sprintf("the %s profiler is not installed: %s was not found on PATH; install it with: %s; or set %s to its absolute path", + l.Display, strings.Join(l.Executables, " or "), l.InstallHint, l.OverrideEnv) +} + +// RuntimeMissingError reports that the add-on is installed but a program it needs is not. +type RuntimeMissingError struct { + Language Language + Runtime string +} + +func (e RuntimeMissingError) Error() string { + return fmt.Sprintf("the %s profiler needs %s, which was not found on PATH", e.Language.Display, e.Runtime) +} + +// Find returns the add-on for a language. An explicit override wins over PATH. The runtime +// check comes last so a missing add-on and a missing runtime are reported separately. +func (f Finder) Find(language Language) (Found, error) { + found := Found{Language: language} + if override := f.Getenv(language.OverrideEnv); override != "" { + if !filepath.IsAbs(override) { + return Found{}, fmt.Errorf("%s must be an absolute path, got %q", language.OverrideEnv, override) + } + path, err := f.LookPath(override) + if err != nil { + return Found{}, fmt.Errorf("%s=%s is not an executable file: %w", language.OverrideEnv, override, err) + } + found.Path, found.Origin = path, "override" + } else { + for _, name := range language.Executables { + if path, err := f.LookPath(name); err == nil { + found.Path, found.Origin = path, "path" + break + } + } + if found.Path == "" { + return Found{}, NotInstalledError{language} + } + } + for _, runtime := range language.Runtime { + if _, err := f.LookPath(runtime); err != nil { + return Found{}, RuntimeMissingError{Language: language, Runtime: runtime} + } + } + return found, nil +} + +// Info is what an add-on reports about itself for `--version --json`. +type Info struct { + Name string `json:"name" yaml:"name"` + Version string `json:"version" yaml:"version"` + CoreSchemas []string `json:"coreSchemas" yaml:"coreSchemas"` +} + +// Supports reports whether the add-on emits the core profile schema version. +func (i Info) Supports(coreSchema string) bool { return slices.Contains(i.CoreSchemas, coreSchema) } + +const ( + describeTimeout = 15 * time.Second + describeLimit = 64 << 10 +) + +// capped refuses output beyond a limit so a misbehaving add-on cannot fill memory. +type capped struct { + bytes.Buffer + limit int +} + +func (c *capped) Write(p []byte) (int, error) { + if c.Len()+len(p) > c.limit { + return 0, errors.New("output is too large") + } + return c.Buffer.Write(p) +} + +// Describe runs ` --version --json` with a time and size limit and reads the answer. +func Describe(ctx context.Context, runner process.Runner, path string) (Info, error) { + ctx, cancel := context.WithTimeout(ctx, describeTimeout) + defer cancel() + out, errOut := &capped{limit: describeLimit}, &capped{limit: describeLimit} + code, err := runner.Run(ctx, process.Spec{Path: path, Args: []string{"--version", "--json"}, Stdout: out, Stderr: errOut}) + if err != nil { + return Info{}, fmt.Errorf("could not run %s --version --json: %w", path, err) + } + if code != 0 { + return Info{}, fmt.Errorf("%s --version --json exited with status %d: %s", path, code, strings.TrimSpace(errOut.String())) + } + var info Info + if err := json.Unmarshal(out.Bytes(), &info); err != nil { + return Info{}, fmt.Errorf("%s --version --json did not print the expected JSON: %w", path, err) + } + if info.Name == "" || info.Version == "" { + return Info{}, fmt.Errorf("%s --version --json must report name and version", path) + } + return info, nil +} diff --git a/internal/plugins/plugins_test.go b/internal/plugins/plugins_test.go new file mode 100644 index 0000000..24fed1b --- /dev/null +++ b/internal/plugins/plugins_test.go @@ -0,0 +1,141 @@ +package plugins + +import ( + "context" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/runtimeconditions/rc-cli/internal/process" +) + +func finder(installed map[string]string, env map[string]string) Finder { + return Finder{ + LookPath: func(name string) (string, error) { + if path, ok := installed[name]; ok { + return path, nil + } + return "", errors.New("not found") + }, + Getenv: func(name string) string { return env[name] }, + } +} + +func TestFindPrefersTheFirstNamedExecutable(t *testing.T) { + found, err := finder(map[string]string{ + "runtimeconditions-typescript-profiler": "/bin/long", "rc-profiler-typescript": "/bin/short", "node": "/bin/node", + }, nil).Find(TypeScript) + if err != nil || found.Path != "/bin/short" || found.Origin != "path" { + t.Fatalf("%+v %v", found, err) + } + found, err = finder(map[string]string{"runtimeconditions-typescript-profiler": "/bin/long", "node": "/bin/node"}, nil).Find(TypeScript) + if err != nil || found.Path != "/bin/long" { + t.Fatalf("%+v %v", found, err) + } +} + +func TestFindReportsAMissingAddOnWithHowToInstallIt(t *testing.T) { + _, err := finder(map[string]string{"node": "/bin/node"}, nil).Find(TypeScript) + var missing NotInstalledError + if !errors.As(err, &missing) { + t.Fatalf("got %v", err) + } + for _, want := range []string{"TypeScript profiler is not installed", "rc-profiler-typescript", "install it with: " + TypeScript.InstallHint, TypeScript.OverrideEnv} { + if !strings.Contains(err.Error(), want) { + t.Errorf("%q missing from %q", want, err) + } + } +} + +func TestFindReportsAMissingRuntimeSeparately(t *testing.T) { + _, err := finder(map[string]string{"rc-profiler-typescript": "/bin/short"}, nil).Find(TypeScript) + var runtime RuntimeMissingError + if !errors.As(err, &runtime) || runtime.Runtime != "node" || !strings.Contains(err.Error(), "needs node") { + t.Fatalf("got %v", err) + } +} + +func TestAnExplicitOverrideWinsAndMustBeAnAbsoluteExecutable(t *testing.T) { + installed := map[string]string{"rc-profiler-typescript": "/bin/short", "node": "/bin/node", "/opt/ts/profiler": "/opt/ts/profiler"} + found, err := finder(installed, map[string]string{TypeScript.OverrideEnv: "/opt/ts/profiler"}).Find(TypeScript) + if err != nil || found.Path != "/opt/ts/profiler" || found.Origin != "override" { + t.Fatalf("%+v %v", found, err) + } + if _, err := finder(installed, map[string]string{TypeScript.OverrideEnv: "profiler"}).Find(TypeScript); err == nil || !strings.Contains(err.Error(), "absolute path") { + t.Fatalf("relative override: %v", err) + } + if _, err := finder(installed, map[string]string{TypeScript.OverrideEnv: "/opt/gone"}).Find(TypeScript); err == nil || !strings.Contains(err.Error(), "not an executable file") { + t.Fatalf("missing override must not fall back to PATH: %v", err) + } +} + +func TestLanguageIDsDoNotShadowGoCommands(t *testing.T) { + reserved := []string{"go", "generate", "validate-extension", "validate-extensions", "version", "help", "completion"} + seen := map[string]bool{} + for _, language := range Languages() { + if slices.Contains(reserved, language.ID) || seen[language.ID] { + t.Errorf("language id %q is reserved or duplicated", language.ID) + } + seen[language.ID] = true + if len(language.Executables) == 0 || language.OverrideEnv == "" || language.InstallHint == "" { + t.Errorf("%s needs executables, an override variable, and an install hint", language.ID) + } + } +} + +type answer struct { + stdout, stderr string + code int + err error +} + +func (a answer) Run(_ context.Context, spec process.Spec) (int, error) { + if !slices.Equal(spec.Args, []string{"--version", "--json"}) { + return 0, errors.New("unexpected arguments") + } + spec.Stdout.Write([]byte(a.stdout)) + spec.Stderr.Write([]byte(a.stderr)) + return a.code, a.err +} + +func TestDescribeReadsTheVersionAndCoreSchemas(t *testing.T) { + info, err := Describe(context.Background(), answer{stdout: `{"name":"@runtimeconditions/typescript-profiler","version":"0.2.0","coreSchemas":["0.4.0"],"extra":1}` + "\n"}, "/bin/p") + if err != nil || info.Version != "0.2.0" || !info.Supports("0.4.0") || info.Supports("0.3.0") { + t.Fatalf("%+v %v", info, err) + } +} + +func TestDescribeRejectsAnythingElse(t *testing.T) { + for name, a := range map[string]answer{ + "nonzero exit": {code: 2, stderr: "boom"}, + "not json": {stdout: "0.2.0\n"}, + "no version": {stdout: `{"name":"x","coreSchemas":["0.4.0"]}`}, + "run error": {err: errors.New("cannot start")}, + "oversized output": {stdout: strings.Repeat("x", describeLimit+1)}, + "empty": {}, + } { + t.Run(name, func(t *testing.T) { + if _, err := Describe(context.Background(), a, "/bin/p"); err == nil { + t.Fatal("expected an error") + } + }) + } +} + +func TestDescribeRunsARealExecutable(t *testing.T) { + if os.PathSeparator != '/' { + t.Skip("uses a shell script") + } + path := filepath.Join(t.TempDir(), "addon") + body := "#!/bin/sh\n[ \"$1 $2\" = \"--version --json\" ] && echo '{\"name\":\"n\",\"version\":\"1.2.3\",\"coreSchemas\":[\"0.4.0\"]}'\n" + if err := os.WriteFile(path, []byte(body), 0o755); err != nil { + t.Fatal(err) + } + info, err := Describe(context.Background(), process.OS{}, path) + if err != nil || info.Version != "1.2.3" { + t.Fatalf("%+v %v", info, err) + } +} diff --git a/internal/process/runner.go b/internal/process/runner.go new file mode 100644 index 0000000..d30c65e --- /dev/null +++ b/internal/process/runner.go @@ -0,0 +1,61 @@ +// Package process runs the subprocesses behind optional language add-ons. +package process + +import ( + "context" + "errors" + "io" + "os/exec" + "time" +) + +// terminationGrace is how long a child gets to exit after it is asked to stop. +const terminationGrace = 5 * time.Second + +// Spec describes one subprocess invocation. The arguments are passed as a slice and +// never through a shell. An empty Dir and a nil Env inherit the caller's. +type Spec struct { + Path string + Args []string + Dir string + Env []string + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer +} + +// Runner runs a subprocess to completion. A child that exits with a nonzero status +// is not an error: its status is returned. Errors mean the child could not be started, +// its I/O failed, or the context ended first. +type Runner interface { + Run(ctx context.Context, spec Spec) (int, error) +} + +// OS runs real subprocesses. On Unix the child leads its own process group. When the +// context ends it receives SIGTERM, and after a grace period the whole group is killed. +type OS struct{} + +// Run starts the child and waits for it. +func (OS) Run(ctx context.Context, spec Spec) (int, error) { + cmd := exec.CommandContext(ctx, spec.Path, spec.Args...) + cmd.Dir, cmd.Env = spec.Dir, spec.Env + cmd.Stdin, cmd.Stdout, cmd.Stderr = spec.Stdin, spec.Stdout, spec.Stderr + cmd.Cancel = func() error { return terminate(cmd) } + cmd.WaitDelay = terminationGrace + prepare(cmd) + err := cmd.Run() + if cmd.Process != nil && ctx.Err() != nil { + killGroup(cmd) + } + if err == nil { + return 0, nil + } + if ctxErr := ctx.Err(); ctxErr != nil { + return 0, ctxErr + } + var exit *exec.ExitError + if errors.As(err, &exit) { + return exitCode(exit.ProcessState), nil + } + return 0, err +} diff --git a/internal/process/runner_other.go b/internal/process/runner_other.go new file mode 100644 index 0000000..40b6db3 --- /dev/null +++ b/internal/process/runner_other.go @@ -0,0 +1,16 @@ +//go:build !unix + +package process + +import ( + "os" + "os/exec" +) + +func prepare(*exec.Cmd) {} + +func terminate(cmd *exec.Cmd) error { return cmd.Process.Kill() } + +func killGroup(*exec.Cmd) {} + +func exitCode(state *os.ProcessState) int { return state.ExitCode() } diff --git a/internal/process/runner_unix.go b/internal/process/runner_unix.go new file mode 100644 index 0000000..16ce008 --- /dev/null +++ b/internal/process/runner_unix.go @@ -0,0 +1,25 @@ +//go:build unix + +package process + +import ( + "os" + "os/exec" + "syscall" +) + +func prepare(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} } + +// terminate asks the child's whole process group to stop. +func terminate(cmd *exec.Cmd) error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) } + +// killGroup removes any descendants the child left behind. +func killGroup(cmd *exec.Cmd) { _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } + +// exitCode follows the shell convention of 128 plus the signal number for a killed child. +func exitCode(state *os.ProcessState) int { + if status, ok := state.Sys().(syscall.WaitStatus); ok && status.Signaled() { + return 128 + int(status.Signal()) + } + return state.ExitCode() +} diff --git a/internal/process/runner_unix_test.go b/internal/process/runner_unix_test.go new file mode 100644 index 0000000..fbabf15 --- /dev/null +++ b/internal/process/runner_unix_test.go @@ -0,0 +1,86 @@ +//go:build unix + +package process + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func script(t *testing.T, body string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "addon") + if err := os.WriteFile(path, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil { + t.Fatal(err) + } + return path +} + +func TestRunReturnsTheExitStatusAndPassesArgumentsStreamsDirAndEnv(t *testing.T) { + dir := t.TempDir() + path := script(t, `printf '%s|' "$@"; pwd; echo "env=$RC_TEST" >&2; read line; echo "in=$line"; exit 3`) + var out, errOut bytes.Buffer + code, err := OS{}.Run(context.Background(), Spec{ + Path: path, Args: []string{"a b", "--", "-x", ""}, Dir: dir, Env: []string{"RC_TEST=yes"}, + Stdin: strings.NewReader("typed\n"), Stdout: &out, Stderr: &errOut, + }) + if err != nil || code != 3 { + t.Fatalf("code=%d err=%v", code, err) + } + resolved, _ := filepath.EvalSymlinks(dir) + if got, want := out.String(), "a b|--|-x||"+resolved+"\nin=typed\n"; got != want { + t.Fatalf("stdout %q, want %q", got, want) + } + if errOut.String() != "env=yes\n" { + t.Fatalf("stderr %q", errOut.String()) + } +} + +func TestRunReportsAKilledChildAsTheShellDoes(t *testing.T) { + code, err := OS{}.Run(context.Background(), Spec{Path: script(t, `kill -TERM $$`)}) + if err != nil || code != 128+int(syscall.SIGTERM) { + t.Fatalf("code=%d err=%v", code, err) + } +} + +func TestRunFailsWhenTheChildCannotStart(t *testing.T) { + code, err := OS{}.Run(context.Background(), Spec{Path: filepath.Join(t.TempDir(), "missing")}) + if err == nil || code != 0 { + t.Fatalf("code=%d err=%v", code, err) + } +} + +func TestCancellationStopsTheChildAndItsDescendants(t *testing.T) { + pidFile := filepath.Join(t.TempDir(), "pid") + path := script(t, `sleep 60 & echo $! > "`+pidFile+`"; wait`) + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + start := time.Now() + _, err := OS{}.Run(ctx, Spec{Path: path}) + if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 4*time.Second { + t.Fatalf("err=%v after %v", err, time.Since(start)) + } + data, readErr := os.ReadFile(pidFile) + if readErr != nil { + t.Fatal(readErr) + } + pid, _ := strconv.Atoi(strings.TrimSpace(string(data))) + deadline := time.Now().Add(3 * time.Second) + for { + if err := syscall.Kill(pid, 0); errors.Is(err, syscall.ESRCH) { + return + } + if time.Now().After(deadline) { + t.Fatalf("descendant %d is still running", pid) + } + time.Sleep(50 * time.Millisecond) + } +}