Nine packages each had their own write-temp-then-rename helper with slightly different behaviour (some synced, some did not; some created the parent directory, some did not; modes and temp-file patterns varied). They are replaced by one fsutil.WriteFileAtomic that always syncs before rename, creates the parent directory, and takes the file mode as a parameter.
24 lines
471 B
Go
24 lines
471 B
Go
package builtin
|
|
|
|
import (
|
|
"context"
|
|
)
|
|
|
|
// runWithContext runs fn and returns its result, or ctx.Err() if ctx ends
|
|
// first; fn keeps running in the background. fn is not started if ctx is
|
|
// already done.
|
|
func runWithContext(ctx context.Context, fn func() error) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
|
|
done := make(chan error, 1)
|
|
go func() { done <- fn() }()
|
|
select {
|
|
case err := <-done:
|
|
return err
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|