clustvirt/util/cleanup/cleanup.go

56 lines
1.5 KiB
Go
Raw Permalink Normal View History

// Package cleanup collects functions that should be run at the end of program operation
// to clean things up and shut things down properly.
// The default CleanItUp instance is initialized with a size 3 stack, just so it's initialized.
package cleanup
// CleanItUp holds a stack of functions that take no arguments and return no
// values, in order to run the stack at a given point.
// Technically doesn't need to be used for cleanup, but that is it's purpose.
type CleanItUp struct {
stack []EmptyFunc
}
// EmptyFunc is just what you think it is, a function with no arguments and no returns
type EmptyFunc func()
var cleaner *CleanItUp
func init() {
cleaner = &CleanItUp{
stack: make([]EmptyFunc, 3),
}
}
// Push onto the default (global) CleanItUp instance
func Push(f EmptyFunc) {
cleaner.Push(f)
}
// Push adds a function to the end of the function stack
func (c *CleanItUp) Push(f EmptyFunc) {
c.stack = append(c.stack, f)
}
// Stack onto the default (global) CleanItUp instance
func Stack(f EmptyFunc) {
cleaner.Stack(f)
}
// Stack adds a function to the start of the function stack
// not very efficient, doesn't really need to be.
func (c *CleanItUp) Stack(f EmptyFunc) {
c.stack = append([]EmptyFunc{f}, c.stack...)
}
// Clean using the default (global) CleanItUp instance
func Clean() {
cleaner.Clean()
}
// Clean runs the stack in reverse order, using the defer keyword to make sure they all run
func (c *CleanItUp) Clean() {
for i := len(c.stack) - 1; i >= 0; i-- {
defer c.stack[i]()
}
}