1
0
mirror of https://github.com/gluster/glusterd2.git synced 2026-02-05 12:45:38 +01:00
Files
glusterd2/pkg/testutils/patch.go
Prashanth Pai 2ba871f723 Remove heketitests as dependency
...as we were using only the Patch() function.

Signed-off-by: Prashanth Pai <ppai@redhat.com>
2017-11-21 17:57:08 +05:30

34 lines
940 B
Go

// From https://gist.github.com/imosquera/6716490#sthash.O4z2aQQp.LUHz2Cbb.dpuf
package testutils
import "reflect"
// Restorer holds a function that can be used
// to restore some previous state.
type Restorer func()
// Restore restores some previous state.
func (r Restorer) Restore() {
r()
}
// Patch sets the value pointed to by the given destination to the given
// value, and returns a function to restore it to its original value. The
// value must be assignable to the element type of the destination.
func Patch(dest, value interface{}) Restorer {
destv := reflect.ValueOf(dest).Elem()
oldv := reflect.New(destv.Type()).Elem()
oldv.Set(destv)
valuev := reflect.ValueOf(value)
if !valuev.IsValid() {
// This isn't quite right when the destination type is not
// nilable, but it's better than the complex alternative.
valuev = reflect.Zero(destv.Type())
}
destv.Set(valuev)
return func() {
destv.Set(oldv)
}
}