🌐 RunWithContext
Executes a Composer command within a specified context.Context, providing maximum control over timeout and cancellation.
When to use
Use this when you need to manually cancel a long-running command, or integrate a command into a larger context-based schedule. It is the most controllable method in the Run family, and RunWithTimeout is also implemented on top of it.
Signature
go
func (c *Composer) RunWithContext(ctx context.Context, args ...string) (string, error)Parameters
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | The context, usable for timeout or cancellation |
args | ...string | Command arguments; the first argument is the Composer subcommand |
Return value
| Return value | Type | Description |
|---|---|---|
| First return value | string | The standard output of the command (including merged stderr) |
| Second return value | error | Returned when the command fails or the context is cancelled; use errors.Is(err, context.Canceled) to detect cancellation |
Example
go
package main
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/scagogogo/composer-skills/pkg/composer"
)
func main() {
comp, err := composer.New(composer.DefaultOptions())
if err != nil {
log.Fatalf("init failed: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
output, err := comp.RunWithContext(ctx, "update")
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
log.Fatalf("update timed out")
}
log.Fatalf("execution failed: %v", err)
}
fmt.Println(output)
}Advanced
- If you only need timeout control, use the simpler RunWithTimeout.
- If you do not need a context, use Run.
- This method is intercepted by the test mock mechanism: when mock output is set, it returns the mock data directly.