go-hep.org/x/hep@v0.38.1/fwk/utils/builder/templates.go (about)

     1  // Copyright ©2017 The go-hep Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package builder
     6  
     7  import (
     8  	"io"
     9  	"strings"
    10  	"text/template"
    11  )
    12  
    13  const (
    14  	tmpl = `// template for a fwk-app main
    15  
    16  package main
    17  
    18  import (
    19  	"flag"
    20  	"fmt"
    21  	"os"
    22  	"runtime/pprof"
    23  
    24  	_ "go-hep.org/x/hep/fwk"
    25  	"go-hep.org/x/hep/fwk/job"
    26  )
    27  
    28  var (
    29  	g_lvl      = flag.String("l", "INFO", "log level (DEBUG|INFO|WARN|ERROR)")
    30  	g_evtmax   = flag.Int("evtmax", -1, "number of events to process")
    31  	g_nprocs   = flag.Int("nprocs", 0, "number of concurrent events to process")
    32  	g_cpu_prof = flag.Bool("cpu-prof", false, "enable CPU profiling")
    33  )
    34  
    35  func main() {
    36  	flag.Usage = func() {
    37  		fmt.Fprintf(os.Stderr, {{.Usage | gen_usage}}, os.Args[0])
    38  		flag.PrintDefaults()
    39  	}
    40  
    41  	flag.Parse()
    42  
    43  	fmt.Printf("::: {{.Name}}...\n")
    44  	if *g_cpu_prof {
    45  		f, err := os.Create("cpu.prof")
    46  		if err != nil {
    47  			panic(err)
    48  		}
    49  		defer f.Close()
    50  		pprof.StartCPUProfile(f)
    51  		defer pprof.StopCPUProfile()
    52  	}
    53  
    54  	app := job.New(job.P{
    55  		"EvtMax":   int64(*g_evtmax),
    56  		"NProcs":   *g_nprocs,
    57  		"MsgLevel": job.MsgLevel(*g_lvl),
    58  	})
    59  
    60      {{with .SetupFuncs}}{{. | gen_setups}}{{end}}
    61  
    62  	app.Run()
    63  	fmt.Printf("::: {{.Name}}... [done]\n")
    64  }
    65  `
    66  )
    67  
    68  func render(w io.Writer, text string, data any) error {
    69  	t := template.New("fwk-main")
    70  	t.Funcs(template.FuncMap{
    71  		"trim":       strings.TrimSpace,
    72  		"gen_setups": gen_setups,
    73  		"gen_usage":  gen_usage,
    74  	})
    75  	template.Must(t.Parse(text))
    76  	return t.Execute(w, data)
    77  }
    78  
    79  func gen_setups(setups []string) string {
    80  	str := make([]string, 0, len(setups))
    81  	for _, setup := range setups {
    82  		str = append(str,
    83  			"\t"+setup+"(app)",
    84  		)
    85  	}
    86  	return strings.Join(str, "\n")
    87  }
    88  
    89  func gen_usage(usage string) string {
    90  	return "`" + usage + "`"
    91  }