go-hep.org/x/hep@v0.38.1/groot/cmd/root-gen-rfunc/main.go (about)

     1  // Copyright ©2020 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  // Command root-gen-rfunc generates a rfunc.Formula based on a function
     6  // signature or an already existing function.
     7  package main // import "go-hep.org/x/hep/groot/cmd/root-gen-rfunc"
     8  
     9  import (
    10  	"flag"
    11  	"fmt"
    12  	"io"
    13  	"log"
    14  	"os"
    15  	"strings"
    16  
    17  	"go-hep.org/x/hep/groot/internal/genroot"
    18  )
    19  
    20  func main() {
    21  	log.SetPrefix("gen-rfunc: ")
    22  	log.SetFlags(0)
    23  
    24  	var (
    25  		pkg = flag.String("p", "", "import path of the package holding the function definition (if any)")
    26  		fct = flag.String("f", "", "name of the function definition or signature of the function")
    27  		n   = flag.String("n", "", "name of the output function")
    28  		o   = flag.String("o", "", "path to output file (if any)")
    29  	)
    30  
    31  	flag.Parse()
    32  	err := generate(*o, *pkg, *fct, *n, flag.Usage)
    33  	if err != nil {
    34  		log.Fatalf("%+v", err)
    35  	}
    36  }
    37  
    38  func generate(oname, pkg, fct, name string, usage func()) error {
    39  	switch {
    40  	case pkg == "" && fct == "":
    41  		usage()
    42  		return fmt.Errorf("missing package import path and/or function name")
    43  	case pkg == "" && !strings.Contains(fct, "func"):
    44  		usage()
    45  		return fmt.Errorf("missing function signature")
    46  	}
    47  
    48  	var out io.Writer
    49  	switch oname {
    50  	case "":
    51  		out = os.Stdout
    52  	default:
    53  		f, err := os.Create(oname)
    54  		if err != nil {
    55  			return fmt.Errorf("could not create output file: %w", err)
    56  		}
    57  		defer f.Close()
    58  		out = f
    59  	}
    60  
    61  	err := genroot.GenRFunc(out, genroot.RFunc{
    62  		Path: pkg,
    63  		Name: name,
    64  		Def:  fct,
    65  	})
    66  	if err != nil {
    67  		return fmt.Errorf("could not generate rfunc formula: %w", err)
    68  	}
    69  
    70  	return nil
    71  }