package modhost import ( "bytes" "encoding/json" "fmt" "os" "os/exec" "strings" ) // Run executes the module binary with args, inheriting stdout/stderr. func Run(bin string, args ...string) error { cmd := exec.Command(bin, args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin if err := cmd.Run(); err != nil { return fmt.Errorf("%s %s: %w", bin, strings.Join(args, " "), err) } return nil } // RunOutput executes the module binary and returns combined stdout. func RunOutput(bin string, args ...string) (string, error) { cmd := exec.Command(bin, args...) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if err := cmd.Run(); err != nil { return stdout.String(), fmt.Errorf("%s %s: %w\n%s", bin, strings.Join(args, " "), err, stderr.String()) } return stdout.String(), nil } // RunDescribe runs `bin describe` and parses JSON. func RunDescribe(bin string) (Describe, error) { out, err := RunOutput(bin, "describe") if err != nil { return Describe{}, err } // Allow log lines before JSON: find first '{'. out = strings.TrimSpace(out) if i := strings.IndexByte(out, '{'); i > 0 { out = out[i:] } var d Describe if err := json.Unmarshal([]byte(out), &d); err != nil { return Describe{}, fmt.Errorf("describe JSON: %w\noutput: %s", err, out) } if d.Protocol != 0 && d.Protocol != ProtocolVersion { return d, fmt.Errorf("module protocol %d unsupported (host wants %d)", d.Protocol, ProtocolVersion) } if d.Protocol == 0 { d.Protocol = ProtocolVersion } return d, nil } // Load builds (if needed) and describes a module by name. func Load(root, name string) (Module, string, Describe, error) { m, err := Find(root, name) if err != nil { return Module{}, "", Describe{}, err } bin, err := EnsureBuilt(m) if err != nil { return m, "", Describe{}, err } d, err := RunDescribe(bin) if err != nil { return m, bin, Describe{}, err } if d.Name == "" { d.Name = m.Name } return m, bin, d, nil }