ExecuteWithStream runs the engine and streams output line-by-line via onOutput.
(ctx context.Context, args []string, onOutput func(string))
| 38 | |
| 39 | // ExecuteWithStream runs the engine and streams output line-by-line via onOutput. |
| 40 | func (p *BuiltinCoderPlugin) ExecuteWithStream(ctx context.Context, args []string, onOutput func(string)) (string, error) { |
| 41 | if len(args) == 0 { |
| 42 | return "", fmt.Errorf("subcommand required") |
| 43 | } |
| 44 | |
| 45 | subcmd := args[0] |
| 46 | var subArgs []string |
| 47 | if len(args) > 1 { |
| 48 | subArgs = args[1:] |
| 49 | } |
| 50 | |
| 51 | var fullOutput strings.Builder |
| 52 | var mu sync.Mutex |
| 53 | |
| 54 | emit := func(line string, isError bool) { |
| 55 | mu.Lock() |
| 56 | defer mu.Unlock() |
| 57 | if onOutput != nil { |
| 58 | prefix := "" |
| 59 | if isError { |
| 60 | prefix = "ERR: " |
| 61 | } |
| 62 | onOutput(prefix + line) |
| 63 | } |
| 64 | fullOutput.WriteString(line) |
| 65 | fullOutput.WriteString("\n") |
| 66 | } |
| 67 | |
| 68 | outWriter := engine.NewStreamWriter(func(line string) { |
| 69 | emit(line, false) |
| 70 | }) |
| 71 | errWriter := engine.NewStreamWriter(func(line string) { |
| 72 | emit(line, true) |
| 73 | }) |
| 74 | |
| 75 | eng := engine.NewEngine(outWriter, errWriter, "") |
| 76 | err := eng.Execute(ctx, subcmd, subArgs) |
| 77 | |
| 78 | outWriter.Flush() |
| 79 | errWriter.Flush() |
| 80 | |
| 81 | output := fullOutput.String() |
| 82 | if err != nil { |
| 83 | return output, fmt.Errorf("plugin execution failed: %w", err) |
| 84 | } |
| 85 | return output, nil |
| 86 | } |