Skip to content

Add shctx package that mirrors sh and adds a context.Context param#554

Open
sybrenstuvel wants to merge 1 commit into
magefile:masterfrom
sybrenstuvel:sybren/sh-with-context
Open

Add shctx package that mirrors sh and adds a context.Context param#554
sybrenstuvel wants to merge 1 commit into
magefile:masterfrom
sybrenstuvel:sybren/sh-with-context

Conversation

@sybrenstuvel
Copy link
Copy Markdown

@sybrenstuvel sybrenstuvel commented May 27, 2026

Add a new package shctx that mirrors the sh API, with the addition that each function (where it makes sense) takes a context.Context parameter. This can then be used for cancellations, timeouts, etc.

Unit tests that were in sh have been moved to shctx. The sh package now no longer has unit tests, because the only thing it does is call into the shctx package, and the real work happens there (and is tested).

Ref: #228

Related: #444 also adds context support, but has a different approach.

Example use, where two commands are running in parallel, both closing when either one of them has an error or the user presses Ctrl+C (so Mage closes the context):

//go:build mage

package main

import (
	"context"

	"github.com/magefile/mage/shctx"
	"golang.org/x/sync/errgroup"
)

func Devserver(ctx context.Context) error {
	group, ctx := errgroup.WithContext(ctx)

	group.Go(func() error {
		return shctx.RunV(ctx, "npm", "run", "dev")
	})

	group.Go(func() error {
		// Run another cmd that can be run by itself as well,
		// hence is in a separate function.
		return DataWatch(ctx)
	})

	return group.Wait()
}

Add a new package `shctx`  that mirrors the `sh` API, with the addition
that each function (where it makes sense) takes a `context.Context`
parameter. This can then be used for cancellations, timeouts, etc.

Unit tests that were in `sh` have been moved to `shctx`. The `sh`
package now no longer has unit tests, because the only thing it does is
call into the `shctx` package, and the real work happens there (and is
tested).

Ref: magefile#228

Related: magefile#444 also adds context support, but has a different approach.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant