Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

chore: proper logging (colored slog) #38

Merged
merged 4 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions cmd/spawn/local-interchain.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"fmt"
"os"
"os/exec"
"path"
Expand Down Expand Up @@ -31,30 +30,32 @@ var LocalICCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
debugBinaryLoc, _ := cmd.Flags().GetBool(FlagLocationPath)

logger := GetLogger()

loc := whereIsLocalICInstalled()
if loc == "" {
fmt.Println("local-ic not found. Please run `make get-localic`")
logger.Error("local-ic not found. Please run `make get-localic`")
return
}

if debugBinaryLoc {
fmt.Println(loc)
logger.Debug("local-ic binary", "location", loc)
return
}

if err := os.Chmod(loc, 0755); err != nil {
fmt.Println("Error setting local-ic permissions:", err)
logger.Error("Error setting local-ic permissions", "err", err)
}

// set to use the current dir if it is not overrriden
if os.Getenv("ICTEST_HOME") == "" {
if err := os.Setenv("ICTEST_HOME", "."); err != nil {
fmt.Println("Error setting ICTEST_HOME:", err)
logger.Error("Error setting ICTEST_HOME", "err", err)
}
}

if err := spawn.ExecCommand(loc, args...); err != nil {
fmt.Println("Error calling local-ic:", err)
logger.Error("Error calling local-ic", "err", err)
}
},
}
Expand Down
51 changes: 51 additions & 0 deletions cmd/spawn/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,52 @@ package main
import (
"fmt"
"log"
"log/slog"
"os"
"strings"
"time"

"github.com/lmittmann/tint"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
)

// Set in the makefile ld_flags on compile
var SpawnVersion = ""

var LogLevelFlag = "log-level"

func main() {
rootCmd.AddCommand(newChain)
rootCmd.AddCommand(LocalICCmd)
rootCmd.AddCommand(versionCmd)

rootCmd.PersistentFlags().String(LogLevelFlag, "info", "log level (debug, info, warn, error)")

if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "error while executing your CLI. Err: %v\n", err)
os.Exit(1)
}
}

func GetLogger() *slog.Logger {
w := os.Stderr

logLevel := parseLogLevelFromFlags()

slog.SetDefault(slog.New(
// TODO: Windows support colored logs: https://github.com/mattn/go-colorable `tint.NewHandler(colorable.NewColorable(w), nil)`
tint.NewHandler(w, &tint.Options{
Level: logLevel,
TimeFormat: time.Kitchen,
// Enables colors only if the terminal supports it
NoColor: !isatty.IsTerminal(w.Fd()),
}),
))

return slog.Default()
}

var rootCmd = &cobra.Command{
Use: "spawn",
Short: "Entry into the Interchain",
Expand All @@ -42,3 +69,27 @@ var versionCmd = &cobra.Command{
fmt.Println(SpawnVersion)
},
}

func parseLogLevelFromFlags() slog.Level {
logLevel, err := rootCmd.PersistentFlags().GetString(LogLevelFlag)
if err != nil {
log.Fatal(err)
}

var lvl slog.Level

switch strings.ToLower(logLevel) {
case "debug", "d", "dbg":
lvl = slog.LevelDebug
case "info", "i", "inf":
lvl = slog.LevelInfo
case "warn", "w", "wrn":
lvl = slog.LevelWarn
case "error", "e", "err", "fatal", "f", "ftl":
lvl = slog.LevelError
default:
lvl = slog.LevelInfo
}

return lvl
}
9 changes: 5 additions & 4 deletions cmd/spawn/new-chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,23 @@ var newChain = &cobra.Command{
Args: cobra.ExactArgs(1),
Aliases: []string{"new", "init", "create"},
Run: func(cmd *cobra.Command, args []string) {
logger := GetLogger()

projName := strings.ToLower(args[0])
homeDir := "." + projName

disabled, _ := cmd.Flags().GetStringSlice(FlagDisabled)
walletPrefix, _ := cmd.Flags().GetString(FlagWalletPrefix)
binName, _ := cmd.Flags().GetString(FlagBinDaemon)
denom, _ := cmd.Flags().GetString(FlagTokenDenom)
debug, _ := cmd.Flags().GetBool(FlagDebugging)
ignoreGitInit, _ := cmd.Flags().GetBool(FlagNoGit)
githubOrg, _ := cmd.Flags().GetString(FlagGithubOrg)

bypassPrompt, _ := cmd.Flags().GetBool(FlagBypassPrompt)
if len(disabled) == 0 && !bypassPrompt {
items, err := selectItems(0, SupportedFeatures, true)
if err != nil {
fmt.Println("Error selecting disabled:", err)
logger.Error("Error selecting disabled", "err", err)
return
}
disabled = items.NOTSlice()
Expand All @@ -80,13 +81,13 @@ var newChain = &cobra.Command{
HomeDir: homeDir,
BinDaemon: binName,
Denom: denom,
Debug: debug,
GithubOrg: githubOrg,
IgnoreGitInit: ignoreGitInit,
DisabledModules: disabled,
Logger: logger,
}
if err := cfg.Validate(); err != nil {
fmt.Println("Error validating config:", err)
logger.Error("Error validating config", "err", err)
return
}

Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ require (
github.com/chzyer/readline v1.5.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lmittmann/tint v1.0.4 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
golang.org/x/sys v0.17.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/lmittmann/tint v1.0.4 h1:LeYihpJ9hyGvE0w+K2okPTGUdVLfng1+nDNVR4vWISc=
github.com/lmittmann/tint v1.0.4/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA=
github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
Expand All @@ -27,6 +31,7 @@ github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcU
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
Expand Down
36 changes: 18 additions & 18 deletions spawn/chain_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"embed"
"fmt"
"io/fs"
"log/slog"
"os"
"path"
"strings"
Expand All @@ -30,24 +31,29 @@ type NewChainConfig struct {
GithubOrg string
// IgnoreGitInit is a flag to ignore git init
IgnoreGitInit bool
// Debug is a flag to enable debug logging
Debug bool

DisabledModules []string

Logger *slog.Logger
}

func (cfg *NewChainConfig) Validate() error {
if strings.ContainsAny(cfg.ProjectName, `~!@#$%^&*()_+{}|:"<>?/.,;'[]\=-`) {
return fmt.Errorf("project name cannot contain special characters %s", cfg.ProjectName)
}

if cfg.Logger == nil {
cfg.Logger = slog.Default()
}

return nil
}

func (cfg *NewChainConfig) AnnounceSuccessfulBuild() {
projName := cfg.ProjectName
bin := cfg.BinDaemon

// no logger here, straight to stdout
fmt.Printf("\n\n🎉 New blockchain '%s' generated!\n", projName)
fmt.Println("🏅Getting started:")
fmt.Println(" - $ cd " + projName)
Expand All @@ -64,20 +70,21 @@ func (cfg *NewChainConfig) GithubPath() string {
func (cfg *NewChainConfig) NewChain() {
NewDirName := cfg.ProjectName
disabled := cfg.DisabledModules
logger := cfg.Logger

fmt.Println("Spawning new app:", NewDirName)
fmt.Println("Disabled features:", disabled)
logger.Info("Spawning new app", "app", NewDirName)
logger.Info("Disabled features", "features", disabled)

if err := os.MkdirAll(NewDirName, 0755); err != nil {
panic(err)
}

if err := cfg.SetupMainChainApp(); err != nil {
fmt.Println(fmt.Errorf("error setting up main chain app: %s", err))
logger.Error("Error setting up main chain app", "err", err)
}

if err := cfg.SetupInterchainTest(); err != nil {
fmt.Println(fmt.Errorf("error setting up interchain test: %s", err))
logger.Error("Error setting up interchain test", "err", err)
}

if !cfg.IgnoreGitInit {
Expand Down Expand Up @@ -117,13 +124,12 @@ func (cfg *NewChainConfig) SetupMainChainApp() error {
// *All Files
fc.ReplaceEverywhere(cfg)

return fc.Save(cfg.Debug)
return fc.Save()
})
}

func (cfg *NewChainConfig) SetupInterchainTest() error {
newDirName := cfg.ProjectName
debug := cfg.Debug

// Interchaintest e2e is a nested submodule. go.mod is renamed to go.mod_ to avoid conflicts
// It will be unwound during unpacking to properly nest it.
Expand Down Expand Up @@ -153,14 +159,14 @@ func (cfg *NewChainConfig) SetupInterchainTest() error {
fc.ReplaceAll(`Binary = "wasmd"`, fmt.Sprintf(`Binary = "%s"`, cfg.BinDaemon)) // else it would replace the Cosmwasm/wasmd import path
fc.ReplaceAll(`Bech32 = "wasm"`, fmt.Sprintf(`Bech32 = "%s"`, cfg.Bech32Prefix))

fc.FindAndReplaceAddressBech32("wasm", cfg.Bech32Prefix, debug)
fc.FindAndReplaceAddressBech32("wasm", cfg.Bech32Prefix)

}

// Removes any modules references after we modify interchaintest values
fc.RemoveDisabledFeatures(cfg)

return fc.Save(cfg.Debug)
return fc.Save()
})
}

Expand All @@ -173,19 +179,13 @@ func (cfg *NewChainConfig) getFileContent(newFilePath string, fs embed.FS, relPa
return nil, nil
}

fc := NewFileContent(relPath, newFilePath)
fc := NewFileContent(cfg.Logger, relPath, newFilePath)

if fc.HasIgnoreFile() {
if cfg.Debug {
fmt.Println("[!] Ignoring File: ", fc.NewPath)
}
cfg.Logger.Debug("Ignoring file", "file", fc.NewPath)
return nil, nil
}

if cfg.Debug {
fmt.Println(fc)
}

// Read the file contents from the embedded FS
if fileContent, err := fs.ReadFile(relPath); err != nil {
return nil, err
Expand Down
9 changes: 4 additions & 5 deletions spawn/command.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package spawn

import (
"fmt"
"os"
"os/exec"
)
Expand All @@ -15,15 +14,15 @@ func ExecCommand(command string, args ...string) error {

func (cfg *NewChainConfig) GitInitNewProjectRepo() {
if err := ExecCommand("git", "init", cfg.ProjectName, "--quiet"); err != nil {
fmt.Println("Error initializing git:", err)
cfg.Logger.Error("Error initializing git", "err", err)
}
if err := os.Chdir(cfg.ProjectName); err != nil {
fmt.Println("Error changing to project directory:", err)
cfg.Logger.Error("Error changing to project directory", "err", err)
}
if err := ExecCommand("git", "add", "."); err != nil {
fmt.Println("Error adding files to git:", err)
cfg.Logger.Error("Error adding files to git", "err", err)
}
if err := ExecCommand("git", "commit", "-m", "initial commit", "--quiet"); err != nil {
fmt.Println("Error committing initial files:", err)
cfg.Logger.Error("Error committing initial files", "err", err)
}
}
Loading
Loading