github.com/googollee/clic@v0.1.5/config.go (about)

     1  package clic
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"reflect"
     7  )
     8  
     9  type config struct {
    10  	value    reflect.Value
    11  	callback reflect.Value
    12  }
    13  
    14  func newConfigValue(value any) *config {
    15  	if value == nil {
    16  		panic("register with nil value")
    17  	}
    18  
    19  	v := reflect.ValueOf(value)
    20  	if v.Kind() != reflect.Ptr {
    21  		panic(fmt.Sprintf("register with invalid type %T, must be `*Type`", value))
    22  	}
    23  
    24  	return &config{
    25  		value: v,
    26  	}
    27  }
    28  
    29  func newConfigCallback(callback any) *config {
    30  	if callback == nil {
    31  		panic("register with nil callback")
    32  	}
    33  
    34  	f := reflect.ValueOf(callback)
    35  	if f.Kind() != reflect.Func {
    36  		panic(fmt.Sprintf("register with invalid callback %T, must be `func(context.Context, *Type) error`", callback))
    37  	}
    38  
    39  	ft := f.Type()
    40  	if ft.NumIn() != 2 || ft.NumOut() != 1 {
    41  		panic(fmt.Sprintf("register with invalid callback %T, must be `func(context.Context, *Type) error`", callback))
    42  	}
    43  
    44  	if ft.In(0) != reflect.TypeFor[context.Context]() {
    45  		panic(fmt.Sprintf("register with invalid callback %T, must be `func(context.Context, *Type) error`", callback))
    46  	}
    47  
    48  	valType := ft.In(1)
    49  	if valType.Kind() != reflect.Ptr {
    50  		panic(fmt.Sprintf("register with invalid callback %T, must be `func(context.Context, *Type) error`", callback))
    51  	}
    52  
    53  	if ft.Out(0) != reflect.TypeFor[error]() {
    54  		panic(fmt.Sprintf("register with invalid callback %T, must be `func(context.Context, *Type) error`", callback))
    55  	}
    56  
    57  	return &config{
    58  		value:    reflect.New(valType.Elem()),
    59  		callback: f,
    60  	}
    61  }
    62  
    63  func (c *config) Callback(ctx context.Context) error {
    64  	if !c.callback.IsValid() {
    65  		return nil
    66  	}
    67  
    68  	in := []reflect.Value{reflect.ValueOf(ctx), c.value}
    69  	out := c.callback.Call(in)
    70  
    71  	if out[0].IsNil() {
    72  		return nil
    73  	}
    74  
    75  	return out[0].Interface().(error)
    76  }
    77  
    78  func (c *config) Value() reflect.Value {
    79  	return c.value
    80  }