github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/cmd/hook_gen/main.go (about)

     1  // +build hookgen
     2  
     3  package main // import "github.com/Azareal/Gosora/hook_gen"
     4  
     5  import (
     6  	"fmt"
     7  	"log"
     8  	"runtime/debug"
     9  	"strings"
    10  
    11  	h "github.com/Azareal/Gosora/cmd/common_hook_gen"
    12  	c "github.com/Azareal/Gosora/common"
    13  	_ "github.com/Azareal/Gosora/extend"
    14  )
    15  
    16  // TODO: Make sure all the errors in this file propagate upwards properly
    17  func main() {
    18  	// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
    19  	defer func() {
    20  		if r := recover(); r != nil {
    21  			fmt.Println(r)
    22  			debug.PrintStack()
    23  		}
    24  	}()
    25  
    26  	hooks := make(map[string]int)
    27  	for _, pl := range c.Plugins {
    28  		if len(pl.Meta.Hooks) > 0 {
    29  			for _, hook := range pl.Meta.Hooks {
    30  				hooks[hook]++
    31  			}
    32  			continue
    33  		}
    34  		if pl.Init != nil {
    35  			if e := pl.Init(pl); e != nil {
    36  				log.Print("early plugin init err: ", e)
    37  				return
    38  			}
    39  		}
    40  		if pl.Hooks != nil {
    41  			log.Print("Hooks not nil for ", pl.UName)
    42  			for hook, _ := range pl.Hooks {
    43  				hooks[hook] += 1
    44  			}
    45  		}
    46  	}
    47  	log.Printf("hooks: %+v\n", hooks)
    48  
    49  	imports := []string{"net/http"}
    50  	hookVars := h.HookVars{imports, nil}
    51  	var params2sb strings.Builder
    52  	add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
    53  		first := true
    54  		for _, param := range strings.Split(params, ",") {
    55  			if !first {
    56  				params2sb.WriteRune(',')
    57  			}
    58  			pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param), "  ", " "), " ")
    59  			params2sb.WriteString(pspl[0])
    60  			first = false
    61  		}
    62  		hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2sb.String(), ret, htype, hooks[name] > 0, multiHook, skip, defaultRet, pure})
    63  		params2sb.Reset()
    64  	}
    65  
    66  	h.AddHooks(add)
    67  	h.Write(hookVars)
    68  	log.Println("Successfully generated the hooks")
    69  }