github.com/go-maxhub/gremlins@v1.0.1-0.20231227222204-b03a6a1e3e09/cmd/gremlins/main.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 main
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  	"os"
    24  	"os/signal"
    25  	"runtime"
    26  	"syscall"
    27  
    28  	"github.com/fatih/color"
    29  
    30  	"github.com/go-maxhub/gremlins/cmd"
    31  	"github.com/go-maxhub/gremlins/core/execution"
    32  	"github.com/go-maxhub/gremlins/core/log"
    33  )
    34  
    35  var version = "dev"
    36  
    37  func main() {
    38  	var exitErr *execution.ExitError
    39  	var exitCode int
    40  	defer func() {
    41  		os.Exit(exitCode)
    42  	}()
    43  	log.Init(color.Output, color.Error)
    44  	ctx := ctxDoneOnSignal()
    45  	err := cmd.Execute(ctx, buildVersion(version))
    46  	if err != nil {
    47  		log.Errorln(err)
    48  		exitCode = 1
    49  	}
    50  	if errors.As(err, &exitErr) {
    51  		exitCode = exitErr.ExitCode()
    52  	}
    53  }
    54  
    55  func ctxDoneOnSignal() context.Context {
    56  	done := make(chan os.Signal, 1)
    57  	signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
    58  	ctx, cancel := context.WithCancel(context.Background())
    59  	go func() {
    60  		<-done
    61  		cancel()
    62  		close(done)
    63  	}()
    64  
    65  	return ctx
    66  }
    67  
    68  func buildVersion(version string) string {
    69  	return fmt.Sprintf("%s %s/%s", version, runtime.GOOS, runtime.GOARCH)
    70  }