Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
220 changes: 220 additions & 0 deletions builder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
package taskgraph

import (
"errors"
"fmt"
)

// TaskBuilder helps construct taskgraph Tasks with a fluent API.
type TaskBuilder[T any] struct {
name string
resultKey Key[T]
depends []any
fn any
condition Condition
defaultVal T
defaultSet bool
defaultBindings []Binding
}

// NewTaskBuilder creates a new builder for a task that produces a result of type T.
func NewTaskBuilder[T any](name string, key Key[T]) *TaskBuilder[T] {
return &TaskBuilder[T]{
name: name,
resultKey: key,
}
}

// DependsOn adds dependencies to the task.
func (b *TaskBuilder[T]) DependsOn(deps ...any) *TaskBuilder[T] {
b.depends = append(b.depends, deps...)
return b
}

// Run sets the function to execute. The function signature must match the dependencies.
func (b *TaskBuilder[T]) Run(fn any) *TaskBuilder[T] {
b.fn = fn
return b
}

// RunIf sets a condition for the task execution.
func (b *TaskBuilder[T]) RunIf(cond Condition) *TaskBuilder[T] {
b.condition = cond
return b
}

// RunIfAll sets a ConditionAnd (logical AND) for the task execution using the provided keys.
func (b *TaskBuilder[T]) RunIfAll(keys ...ReadOnlyKey[bool]) *TaskBuilder[T] {
b.condition = ConditionAnd(keys)
return b
}

// RunIfAny sets a ConditionOr (logical OR) for the task execution using the provided keys.
func (b *TaskBuilder[T]) RunIfAny(keys ...ReadOnlyKey[bool]) *TaskBuilder[T] {
b.condition = ConditionOr(keys)
return b
}

// Default sets the default value for the result key if the condition is false.
func (b *TaskBuilder[T]) Default(val T) *TaskBuilder[T] {
b.defaultVal = val
b.defaultSet = true
return b
}

// WithDefaultBindings adds arbitrary default bindings if the condition is false.
func (b *TaskBuilder[T]) WithDefaultBindings(bindings ...Binding) *TaskBuilder[T] {
b.defaultBindings = append(b.defaultBindings, bindings...)
return b
}

// Build constructs and returns the Task.
func (b *TaskBuilder[T]) Build() (TaskSet, error) {
reflect := Reflect[T]{
Name: b.name,
ResultKey: b.resultKey,
Depends: b.depends,
Fn: b.fn,
}
reflect.location = getLocation(2)

// Eagerly build to validate and get the underlying task
task, err := reflect.Build()
if err != nil {
return nil, err
}
var ts TaskSet = task

if b.condition != nil {
conditional := Conditional{
Wrapped: ts,
Condition: b.condition,
}

if b.defaultSet {
conditional.DefaultBindings = append(
conditional.DefaultBindings,
b.resultKey.Bind(b.defaultVal),
)
}
conditional.DefaultBindings = append(conditional.DefaultBindings, b.defaultBindings...)

conditional.location = getLocation(2)
ts = conditional
}

return ts, nil
}

// Tasks satisfies the TaskSet interface to avoid the need to call Build(). It is equivalent to
// calling Must(Build()).Tasks().
func (b *TaskBuilder[T]) Tasks() []Task {
return Must(b.Build()).Tasks()
}

// MultiTaskBuilder helps construct taskgraph Tasks that provide multiple outputs or perform side effects.
type MultiTaskBuilder struct {
name string
depends []any
fn any
provides []ID
condition Condition
defaultBindings []Binding
errors []error
}

// NewMultiTaskBuilder creates a new builder for a multi-output or side-effect task.
func NewMultiTaskBuilder(name string) *MultiTaskBuilder {
return &MultiTaskBuilder{
name: name,
}
}

// DependsOn adds dependencies to the task.
func (b *MultiTaskBuilder) DependsOn(deps ...any) *MultiTaskBuilder {
b.depends = append(b.depends, deps...)
return b
}

// Provides declares the keys that this task provides.
func (b *MultiTaskBuilder) Provides(keys ...any) *MultiTaskBuilder {
for _, k := range keys {
rk, err := newReflectKey(k)
if err != nil {
b.errors = append(b.errors, fmt.Errorf("invalid key passed to Provides: %w", err))
continue
}
id, err := rk.ID()
if err != nil {
b.errors = append(b.errors, fmt.Errorf("invalid key ID in Provides: %w", err))
continue
}
b.provides = append(b.provides, id)
}
return b
}

// Run sets the function to execute. The function signature must match the dependencies.
// Fn must return []Binding or ([]Binding, error).
func (b *MultiTaskBuilder) Run(fn any) *MultiTaskBuilder {
b.fn = fn
return b
}

// RunIf sets a condition for the task execution.
func (b *MultiTaskBuilder) RunIf(cond Condition) *MultiTaskBuilder {
b.condition = cond
return b
}

// RunIfAll sets a ConditionAnd (logical AND) for the task execution using the provided keys.
func (b *MultiTaskBuilder) RunIfAll(keys ...ReadOnlyKey[bool]) *MultiTaskBuilder {
b.condition = ConditionAnd(keys)
return b
}

// RunIfAny sets a ConditionOr (logical OR) for the task execution using the provided keys.
func (b *MultiTaskBuilder) RunIfAny(keys ...ReadOnlyKey[bool]) *MultiTaskBuilder {
b.condition = ConditionOr(keys)
return b
}

// WithDefaultBindings adds arbitrary default bindings if the condition is false.
func (b *MultiTaskBuilder) WithDefaultBindings(bindings ...Binding) *MultiTaskBuilder {
b.defaultBindings = append(b.defaultBindings, bindings...)
return b
}

// Build constructs and returns the Task.
func (b *MultiTaskBuilder) Build() (TaskSet, error) {
if len(b.errors) > 0 {
return nil, errors.Join(b.errors...)
}

reflect := ReflectMulti{
Name: b.name,
Depends: b.depends,
Fn: b.fn,
Provides: b.provides,
}
reflect.location = getLocation(2)
var task TaskSet = reflect

if b.condition != nil {
conditional := Conditional{
Wrapped: task,
Condition: b.condition,
DefaultBindings: b.defaultBindings,
}
conditional.location = getLocation(2)
task = conditional
}

return task, nil
}

// Tasks satisfies the TaskSet interface to avoid the need to call Build(). It is equivalent to
// calling Must(Build()).Tasks().
func (b *MultiTaskBuilder) Tasks() []Task {
return Must(b.Build()).Tasks()
}
74 changes: 74 additions & 0 deletions builder_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package taskgraph

import (
"testing"
)

func TestTaskBuilder_RunIfAll(t *testing.T) {
k1 := NewKey[bool]("k1")
k2 := NewKey[bool]("k2")
res := NewKey[string]("res")

task, err := NewTaskBuilder[string]("test", res).
Run(func() string { return "ok" }).
RunIfAll(k1, k2).
Default("default").
Build()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

// Simulate execution (simplified verification)
tasks := task.Tasks()
if len(tasks) != 1 {
t.Fatalf("expected 1 task, got %d", len(tasks))
}
}

func TestMultiTaskBuilder_Provides(t *testing.T) {
k1 := NewKey[string]("k1")
k2 := NewKey[int]("k2")

task, err := NewMultiTaskBuilder("multi").
Provides(k1, k2).
Run(func() ([]Binding, error) {
return []Binding{k1.Bind("s"), k2.Bind(1)}, nil
}).
Build()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

tasks := task.Tasks()
if len(tasks) != 1 {
t.Fatalf("expected 1 task, got %d", len(tasks))
}
provided := tasks[0].Provides()
if len(provided) != 2 {
t.Fatalf("expected 2 provided keys, got %d", len(provided))
}
}

func TestMultiTaskBuilder_Provides_InvalidKey(t *testing.T) {
_, err := NewMultiTaskBuilder("fail").Provides("not a key").Build()
if err == nil {
t.Errorf("expected error on invalid key")
}
}

func TestMultiTaskBuilder_RunIfAny(t *testing.T) {
k1 := NewKey[bool]("k1")
k2 := NewKey[bool]("k2")

task, err := NewMultiTaskBuilder("multi_cond").
RunIfAny(k1, k2).
Run(func() []Binding { return nil }).
Build()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

if task == nil {
t.Fatal("expected task to be built")
}
}
10 changes: 5 additions & 5 deletions key.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func (k *key[T]) Get(b Binder) (T, error) {
func NewKey[T any](id string) Key[T] {
return &key[T]{
id: newID("", id),
location: getLocation(),
location: getLocation(2),
}
}

Expand All @@ -109,7 +109,7 @@ func NewKey[T any](id string) Key[T] {
func NewNamespacedKey[T any](namespace, id string) Key[T] {
return &key[T]{
id: newID(namespace, id),
location: getLocation(),
location: getLocation(2),
}
}

Expand All @@ -130,7 +130,7 @@ func (k *presenceKey[T]) Get(b Binder) (bool, error) {
func Presence[T any](key ReadOnlyKey[T]) ReadOnlyKey[bool] {
return &presenceKey[T]{
ReadOnlyKey: key,
location: getLocation(),
location: getLocation(2),
}
}

Expand Down Expand Up @@ -159,7 +159,7 @@ func Mapped[In, Out any](key ReadOnlyKey[In], fn func(In) Out) ReadOnlyKey[Out]
return &mappedKey[In, Out]{
ReadOnlyKey: key,
fn: fn,
location: getLocation(),
location: getLocation(2),
}
}

Expand Down Expand Up @@ -188,6 +188,6 @@ func (k *optionalKey[T]) Get(b Binder) (Maybe[T], error) {
func Optional[T any](base ReadOnlyKey[T]) ReadOnlyKey[Maybe[T]] {
return &optionalKey[T]{
ReadOnlyKey: base,
location: getLocation(),
location: getLocation(2),
}
}
4 changes: 2 additions & 2 deletions reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ type Reflect[T any] struct {
// Locate annotates the Reflect with its location in the source code, to make error messages
// easier to understand. Calling it is recommended but not required if wrapped in a Conditional
func (r Reflect[T]) Locate() Reflect[T] {
r.location = getLocation()
r.location = getLocation(2)
return r
}

Expand Down Expand Up @@ -337,7 +337,7 @@ type ReflectMulti struct {
// Locate annotates the ReflectMulti with its location in the source code, to make error messages
// easier to understand. Calling it is recommended but not required if wrapped in a Conditional
func (r ReflectMulti) Locate() ReflectMulti {
r.location = getLocation()
r.location = getLocation(2)
return r
}

Expand Down
Loading