github.com/go-maxhub/gremlins@v1.0.1-0.20231227222204-b03a6a1e3e09/cmd/gremlins.go (about) 1 /* 2 * Copyright 2022 The Gremlins Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package cmd 18 19 import ( 20 "context" 21 "errors" 22 "os" 23 24 "github.com/MakeNowJust/heredoc" 25 "github.com/spf13/cobra" 26 27 "github.com/go-maxhub/gremlins/cmd/flags" 28 "github.com/go-maxhub/gremlins/core/configuration" 29 30 "github.com/go-maxhub/gremlins/core/log" 31 ) 32 33 const paramConfigFile = "config" 34 35 // Execute initialises a new Cobra root command (gremlins) with a custom version 36 // string used in the `-v` flag results. 37 func Execute(ctx context.Context, version string) error { 38 rootCmd, err := newRootCmd(ctx, version) 39 if err != nil { 40 return err 41 } 42 43 return rootCmd.execute() 44 } 45 46 type gremlinsCmd struct { 47 cmd *cobra.Command 48 } 49 50 func (gc gremlinsCmd) execute() error { 51 var cfgFile string 52 cobra.OnInitialize(func() { 53 err := configuration.Init([]string{cfgFile}) 54 if err != nil { 55 log.Errorf("initialization error: %s\n", err) 56 os.Exit(1) 57 } 58 }) 59 gc.cmd.PersistentFlags().StringVar(&cfgFile, paramConfigFile, "", "override config file") 60 61 return gc.cmd.Execute() 62 } 63 64 func newRootCmd(ctx context.Context, version string) (*gremlinsCmd, error) { 65 if version == "" { 66 return nil, errors.New("expected a version string") 67 } 68 69 cmd := &cobra.Command{ 70 Hidden: true, 71 SilenceUsage: true, 72 SilenceErrors: true, 73 Use: "gremlins", 74 Short: shortExplainer(), 75 Version: version, 76 } 77 78 uc, err := newUnleashCmd(ctx) 79 if err != nil { 80 return nil, err 81 82 } 83 cmd.AddCommand(uc.cmd) 84 85 flag := &flags.Flag{Name: "silent", CfgKey: configuration.GremlinsSilentKey, Shorthand: "s", DefaultV: false, Usage: "suppress output and run in silent mode"} 86 if err := flags.SetPersistent(cmd, flag); err != nil { 87 return nil, err 88 } 89 90 return &gremlinsCmd{ 91 cmd: cmd, 92 }, nil 93 } 94 95 func shortExplainer() string { 96 return heredoc.Doc(` 97 Gremlins is a mutation testing tool for Go projects, made with love by k3rn31 98 and friends. 99 `) 100 }