Skip to content
Open
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
15 changes: 15 additions & 0 deletions mg/deps.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,26 @@ func (o *onceMap) LoadOrStore(f Fn) *onceFun {
return one
}

func (o *onceMap) Reset() {
o.mu.Lock()
defer o.mu.Unlock()

o.m = map[onceKey]*onceFun{}
}

var onces = &onceMap{
mu: &sync.Mutex{},
m: map[onceKey]*onceFun{},
}

// ResetDeps clears the dependency cache used by Deps, CtxDeps, SerialDeps, and
// SerialCtxDeps. It is intended for tests that need to run the same dependencies
// more than once in a single process. Do not call ResetDeps while dependencies
// are running.
func ResetDeps() {
onces.Reset()
}

// SerialDeps is like Deps except it runs each dependency serially, instead of
// in parallel. This can be useful for resource intensive dependencies that
// shouldn't be run at the same time.
Expand Down
19 changes: 19 additions & 0 deletions mg/deps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,25 @@ func TestDepsRunOnce(t *testing.T) {
}
}

func TestResetDepsAllowsDependenciesToRunAgain(t *testing.T) {
var calls int64
f := func() {
atomic.AddInt64(&calls, 1)
}

Deps(f)
Deps(f)
if calls != 1 {
t.Fatalf("expected dependency to run once before reset, ran %d times", calls)
}

ResetDeps()
Deps(f)
if calls != 2 {
t.Fatalf("expected dependency to run again after reset, ran %d times", calls)
}
}

func TestDepsOfDeps(t *testing.T) {
ch := make(chan string, 3)
// this->f->g->h
Expand Down