github.com/chyroc/anb@v0.3.0/internal/config/if.go (about)

     1  package config
     2  
     3  import (
     4  	"os"
     5  	"strings"
     6  
     7  	"github.com/chyroc/anbko/env"
     8  	"github.com/chyroc/anbko/vm"
     9  )
    10  
    11  // IfExpr 是 if 表达式,输入: string,输出: bool
    12  //
    13  // IfExpr 支持下面几个函数和操作符
    14  // 	函数:exist
    15  // 	操作符:&& || !
    16  //
    17  // 示例
    18  // if: exist("/path")
    19  // if: exist(/path)
    20  // if: !exist(/path)
    21  // if: exist(/path1) && !exist(/path2)
    22  // if: (exist(/path1) || !exist(/path2)) && exist(/path3)
    23  type IfExpr string
    24  
    25  func (r IfExpr) IsTrue(vals Any) (bool, error) {
    26  	s := strings.TrimSpace(string(r))
    27  	return ExecBoolScript(s, vals)
    28  }
    29  
    30  type Any map[string]interface{}
    31  
    32  func ExecBoolScript(script string, val Any) (bool, error) {
    33  	e := env.NewEnv()
    34  
    35  	if err := e.Define("exist", func(path string) bool {
    36  		f, _ := os.Lstat(path)
    37  		return f != nil
    38  	}); err != nil {
    39  		return false, err
    40  	}
    41  	// err := e.DefineGlobal("$ab", "/Users/chyroc/code/chyroc/anb/README.md")
    42  	for k, v := range val {
    43  		if err := e.DefineGlobal(k, v); err != nil {
    44  			return false, err
    45  		}
    46  	}
    47  	res, err := vm.Execute(e, nil, script)
    48  	if err != nil {
    49  		return false, err
    50  	}
    51  	b, _ := res.(bool)
    52  	return b, nil
    53  }