github.com/nektos/act@v0.2.83/pkg/common/job_error.go (about) 1 package common 2 3 import ( 4 "context" 5 ) 6 7 type jobErrorContextKey string 8 9 const jobErrorContextKeyVal = jobErrorContextKey("job.error") 10 11 type jobCancelCtx string 12 13 const JobCancelCtxVal = jobCancelCtx("job.cancel") 14 15 // JobError returns the job error for current context if any 16 func JobError(ctx context.Context) error { 17 val := ctx.Value(jobErrorContextKeyVal) 18 if val != nil { 19 if container, ok := val.(map[string]error); ok { 20 return container["error"] 21 } 22 } 23 return nil 24 } 25 26 func SetJobError(ctx context.Context, err error) { 27 ctx.Value(jobErrorContextKeyVal).(map[string]error)["error"] = err 28 } 29 30 // WithJobErrorContainer adds a value to the context as a container for an error 31 func WithJobErrorContainer(ctx context.Context) context.Context { 32 container := map[string]error{} 33 return context.WithValue(ctx, jobErrorContextKeyVal, container) 34 } 35 36 func WithJobCancelContext(ctx context.Context, cancelContext context.Context) context.Context { 37 return context.WithValue(ctx, JobCancelCtxVal, cancelContext) 38 } 39 40 func JobCancelContext(ctx context.Context) context.Context { 41 val := ctx.Value(JobCancelCtxVal) 42 if val != nil { 43 if container, ok := val.(context.Context); ok { 44 return container 45 } 46 } 47 return nil 48 } 49 50 // EarlyCancelContext returns a new context based on ctx that is canceled when the first of the provided contexts is canceled. 51 func EarlyCancelContext(ctx context.Context) (context.Context, context.CancelFunc) { 52 val := JobCancelContext(ctx) 53 if val != nil { 54 context, cancel := context.WithCancel(ctx) 55 go func() { 56 defer cancel() 57 select { 58 case <-context.Done(): 59 case <-ctx.Done(): 60 case <-val.Done(): 61 } 62 }() 63 return context, cancel 64 } 65 return ctx, func() {} 66 }