go-hep.org/x/hep@v0.38.1/fwk/cmd/fwk-new-comp/main.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 main
     6  
     7  import (
     8  	"flag"
     9  	"fmt"
    10  	"log"
    11  	"os"
    12  	"path/filepath"
    13  )
    14  
    15  var (
    16  	g_type = flag.String("c", "task", "type of component to generate (task|svc)")
    17  	g_pkg  = flag.String("p", "", "name of the package holding the component")
    18  )
    19  
    20  type Component struct {
    21  	Package string
    22  	Name    string
    23  	Type    string
    24  }
    25  
    26  func main() {
    27  	log.SetFlags(0)
    28  	log.SetPrefix("fwk-new-comp: ")
    29  
    30  	flag.Usage = func() {
    31  		fmt.Fprintf(os.Stderr, `Usage: %[1]s [options] <component-name>
    32  
    33  ex:
    34   $ %[1]s -c=task -p=mypackage mytask
    35   $ %[1]s -c=task -p mypackage mytask >| mytask.go
    36   $ %[1]s -c=svc  -p mypackage mysvc  >| mysvc.go
    37  
    38  options:
    39  `,
    40  			os.Args[0],
    41  		)
    42  		flag.PrintDefaults()
    43  	}
    44  
    45  	flag.Parse()
    46  	sc := run()
    47  	os.Exit(sc)
    48  }
    49  
    50  func run() int {
    51  	if *g_type != "svc" && *g_type != "task" {
    52  		log.Printf("**error** invalid component type [%s]\n", *g_type)
    53  		flag.Usage()
    54  		return 1
    55  	}
    56  
    57  	if *g_pkg == "" {
    58  		// take directory name
    59  		wd, err := os.Getwd()
    60  		if err != nil {
    61  			log.Printf("**error** could not get directory name: %v\n", err)
    62  			return 1
    63  		}
    64  		*g_pkg = filepath.Base(wd)
    65  
    66  		if *g_pkg == "" || *g_pkg == "." {
    67  			log.Printf(
    68  				"**error** invalid package name %q. please specify via the '-p' flag.",
    69  				*g_pkg,
    70  			)
    71  			return 1
    72  		}
    73  	}
    74  
    75  	args := flag.Args()
    76  	if len(args) <= 0 {
    77  		log.Printf("**error** you need to give a component name\n")
    78  		flag.Usage()
    79  		return 1
    80  	}
    81  
    82  	c := Component{
    83  		Package: *g_pkg,
    84  		Name:    args[0],
    85  		Type:    *g_type,
    86  	}
    87  
    88  	var err error
    89  	switch *g_type {
    90  	case "svc":
    91  		err = gen_svc(c)
    92  	case "task":
    93  		err = gen_task(c)
    94  	default:
    95  		log.Printf("**error** invalid component type [%s]\n", *g_type)
    96  		flag.Usage()
    97  		return 1
    98  	}
    99  
   100  	if err != nil {
   101  		log.Printf("**error** generating %q: %v\n", c.Name, err)
   102  		return 1
   103  	}
   104  
   105  	return 0
   106  }