Introduce an App struct that executes core business logic

The Cobra commands are now a light wrapper around the App struct.

Co-authored-by: Jose Garcia <josebalius@github.com>
This commit is contained in:
Mislav Marohnić 2021-09-24 16:03:44 +02:00
parent 8807b3a73a
commit ca0f89d3bc
15 changed files with 557 additions and 175 deletions

View file

@ -4,22 +4,45 @@ import (
"errors"
"fmt"
"io"
"net/http"
"os"
"github.com/github/ghcs/cmd/ghcs"
"github.com/github/ghcs/cmd/ghcs/output"
"github.com/github/ghcs/internal/api"
"github.com/spf13/cobra"
)
func main() {
rootCmd := ghcs.NewRootCmd()
token := os.Getenv("GITHUB_TOKEN")
rootCmd := ghcs.NewRootCmd(ghcs.NewApp(
output.NewLogger(os.Stdout, os.Stderr, false),
api.New(token, http.DefaultClient),
))
// Require GITHUB_TOKEN through a Cobra pre-run hook so that Cobra's help system for commands can still
// function without the token set.
oldPreRun := rootCmd.PersistentPreRunE
rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if token == "" {
return errTokenMissing
}
if oldPreRun != nil {
return oldPreRun(cmd, args)
}
return nil
}
if cmd, err := rootCmd.ExecuteC(); err != nil {
explainError(os.Stderr, err, cmd)
os.Exit(1)
}
}
var errTokenMissing = errors.New("GITHUB_TOKEN is missing")
func explainError(w io.Writer, err error, cmd *cobra.Command) {
if errors.Is(err, ghcs.ErrTokenMissing) {
if errors.Is(err, errTokenMissing) {
fmt.Fprintln(w, "The GITHUB_TOKEN environment variable is required. Create a Personal Access Token at https://github.com/settings/tokens/new?scopes=repo")
fmt.Fprintln(w, "Make sure to enable SSO for your organizations after creating the token.")
return