Skip to content

Commit 24ec2f9

Browse files
authored
Merge pull request #38 from ccremer/unnamed
Add new anonymous pipeline that just executes functions
2 parents 03522f6 + 9cc78ae commit 24ec2f9

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

simple.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package pipeline
2+
3+
import (
4+
"context"
5+
"reflect"
6+
"runtime"
7+
"strings"
8+
)
9+
10+
// NewAnonymous creates a pipeline from the given anonymous functions.
11+
// This is meant to quickly set up a Pipeline that executes error-prone functions in a fail-first fashion.
12+
// The context allows to carry over values.
13+
//
14+
// Note: You may want to use Pipeline.WithOptions(DisableErrorWrapping) to suppress function names as step names in errors.
15+
func NewAnonymous(funcs ...func(ctx context.Context) error) *Pipeline {
16+
steps := make([]Step, len(funcs))
17+
for i := 0; i < len(funcs); i++ {
18+
fn := funcs[i]
19+
steps[i] = NewStepFromFunc(getFunctionName(fn), func(ctx context.Context) error {
20+
return fn(ctx)
21+
})
22+
}
23+
return NewPipeline().WithSteps(steps...)
24+
}
25+
26+
func getFunctionName(temp interface{}) string {
27+
strs := strings.Split(runtime.FuncForPC(reflect.ValueOf(temp).Pointer()).Name(), ".")
28+
return strs[len(strs)-1]
29+
}

simple_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package pipeline
2+
3+
import (
4+
"context"
5+
"fmt"
6+
)
7+
8+
func ExampleNewAnonymous() {
9+
p := NewAnonymous(
10+
func(ctx context.Context) error {
11+
return nil
12+
},
13+
func(ctx context.Context) error {
14+
return fmt.Errorf("fail")
15+
}).WithOptions(DisableErrorWrapping)
16+
result := p.Run()
17+
fmt.Printf("Name: %s, Err: %v", result.Name(), result.Err())
18+
// Output: Name: func2, Err: fail
19+
}

0 commit comments

Comments
 (0)