github.com/treeverse/lakefs@v1.24.1-0.20240520134607-95648127bfb0/pkg/actions/lua/hook/lib.go (about)

     1  package hook
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/Shopify/go-lua"
     7  )
     8  
     9  // helpers for writing lua actions
    10  
    11  // ErrHookFailure indicates an explicit failure from a hook
    12  // (as opposed to a generic error that occurred during execution)
    13  type ErrHookFailure string
    14  
    15  func (e ErrHookFailure) Error() string {
    16  	return string(e)
    17  }
    18  
    19  func Open(l *lua.State) {
    20  	open := func(l *lua.State) int {
    21  		lua.NewLibrary(l, library)
    22  		return 1
    23  	}
    24  	lua.Require(l, "hook", open, false)
    25  	l.Pop(1)
    26  }
    27  
    28  var library = []lua.RegistryFunction{
    29  	{Name: "fail", Function: fail},
    30  }
    31  
    32  func fail(l *lua.State) int {
    33  	p := lua.CheckString(l, 1)
    34  	lua.Errorf(l, "<HookFailure>%s</HookFailure>", p)
    35  	panic("unreachable")
    36  }
    37  
    38  func Unwrap(err error) error {
    39  	switch err.(type) {
    40  	case lua.RuntimeError, *lua.RuntimeError:
    41  		str := err.Error()
    42  		_, after, found := strings.Cut(str, "<HookFailure>")
    43  		if found {
    44  			before, _, _ := strings.Cut(after, "</HookFailure>")
    45  			return ErrHookFailure(before)
    46  		}
    47  	}
    48  	return err
    49  }