template / commit
Starting to add logging, made a lot of reporting messages into debug logs.
.vscode/launch.json | 8 +++++--- extras.go | 6 +----- extras_test.go | 6 ++---- file.go | 6 ++++-- go.mod | 2 ++ go.sum | 6 ++++++ main.go | 43 ++++++++++++++++++++++++++++++++++++++----- profile.go | 15 +++++++++++---- 8 files changed, 69 insertions(+), 23 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index b51d111..60b8f44 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -68,7 +68,7 @@ ] }, { - "name": "Run: template --profile work --project testProj --default-config", + "name": "Run: template --profile work --project testProj", "type": "go", "request": "launch", "mode": "auto", @@ -92,7 +92,7 @@ ] }, { - "name": "Run: template test blah", + "name": "Run: template --profile test --name blah --extras-yaml extras-test.yaml --log-level debug", "type": "go", "request": "launch", "mode": "auto", @@ -104,7 +104,9 @@ "blah", "--extras-yaml", "extras-test.yaml", - "--default-config" + "--log-level", + "debug", + ] ] } ] diff --git a/extras.go b/extras.go index 087ae1e..018c0f6 100644 --- a/extras.go +++ b/extras.go @@ -12,11 +12,7 @@ func loadExtras(path string) (map[string]string, error) { file, err := os.ReadFile(path) if err != nil { - if os.IsNotExist(err) { - fmt.Printf("extras file %s does not exist, extras not being used\n", path) - return emptyMap, nil - } - return emptyMap, err + return emptyMap, fmt.Errorf("error reading extras file %v: %v", path, err) } result := make(map[string]string) diff --git a/extras_test.go b/extras_test.go index 5fe946c..0cbb92b 100644 --- a/extras_test.go +++ b/extras_test.go @@ -51,12 +51,10 @@ func TestExtras(t *testing.T) { assert.Equal(t, extras, loadedExtras) // test path errors - extras, err = loadExtras("non-existent-file.yaml") - assert.Nil(t, err, "Expected to load extras") - assert.Empty(t, extras, "Expected to load empty extras") + _, err = loadExtras("non-existent-file.yaml") + assert.NotNil(t, err, "Expected error loading non-existent file") os.WriteFile(file.Name(), []byte("invalid yaml"), 0644) - _, err = loadExtras(fileName) assert.NotNil(t, err, "Expected to fail to parse extras, but succeeded") } diff --git a/file.go b/file.go index aa65f9b..817a8a4 100644 --- a/file.go +++ b/file.go @@ -5,6 +5,8 @@ import ( "os" "strings" "text/template" + + log "github.com/sirupsen/logrus" ) func createFile( @@ -14,7 +16,7 @@ func createFile( useTemplate := file.Template != "" if useTemplate { postPatternData := createPostPatternData(fullPath, prePatternData) - fmt.Printf("Creating file '%v' from template string\n", fullPath) + log.WithFields(log.Fields{"fullPath": fullPath}).Debug("Creating file from template string\n", fullPath) // parse template template, err := template.New("text-template").Parse(string(file.Template)) @@ -32,7 +34,7 @@ func createFile( templateString := sb.String() monkey.OSWriteFile(fullPath, []byte(templateString), os.ModePerm) } else { - fmt.Printf("Creating empty file: %v\n", fullPath) + log.WithFields(log.Fields{"fullPath": fullPath}).Debug("Creating empty file", fullPath) monkey.OSWriteFile(fullPath, []byte{}, os.ModePerm) } return nil diff --git a/go.mod b/go.mod index d26de5c..4288d69 100644 --- a/go.mod +++ b/go.mod @@ -14,5 +14,7 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/sirupsen/logrus v1.9.0 // indirect github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect + golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect ) diff --git a/go.sum b/go.sum index 536755f..18bab4e 100644 --- a/go.sum +++ b/go.sum @@ -7,8 +7,11 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= @@ -18,6 +21,9 @@ github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRT github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= golang.org/x/exp v0.0.0-20220921164117-439092de6870 h1:j8b6j9gzSigH28O5SjSpQSSh9lFd6f5D/q0aHjNTulc= golang.org/x/exp v0.0.0-20220921164117-439092de6870/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 2a9468a..51a8044 100644 --- a/main.go +++ b/main.go @@ -2,17 +2,18 @@ package main import ( "fmt" - "log" "os" "os/user" "strings" + log "github.com/sirupsen/logrus" "github.com/urfave/cli/v2" // imports as package "cli" "gopkg.in/yaml.v3" ) const defaultUserConfigPath = "~/.template.user.yaml" const defaultConfigPath = "~/.template.yaml" +const defaultLogLevel = "info" type ArgumentValues struct { profile string @@ -20,6 +21,7 @@ type ArgumentValues struct { configFilePath string userConfigPath string extrasFilePath string + logLevel string } type Settings struct { ArgumentValues @@ -75,6 +77,13 @@ func main() { Value: "~/.template-extras.yaml", Destination: &argumentValues.extrasFilePath, }, + &cli.StringFlag{ + Name: "log-level", + Aliases: []string{"l"}, + Usage: "log level", + Value: defaultLogLevel, + Destination: &argumentValues.logLevel, + }, }, Action: func(context *cli.Context) error { settings, err := parseArguments(argumentValues, context) @@ -104,7 +113,29 @@ func parseArguments( // read args args := context.Args() - fmt.Println("Args:", args) + + // configure logging + switch settings.logLevel { + case "debug": + log.SetLevel(log.DebugLevel) + case "info": + log.SetLevel(log.InfoLevel) + case "warn": + log.SetLevel(log.WarnLevel) + case "error": + log.SetLevel(log.ErrorLevel) + case "fatal": + log.SetLevel(log.FatalLevel) + case "panic": + log.SetLevel(log.PanicLevel) + default: + fmt.Printf("invalid log level specified %v, using info", settings.logLevel) + log.SetLevel(log.InfoLevel) + } + log.SetOutput(os.Stdout) + // log.SetFormatter(&log.JSONFormatter{}) + + log.WithFields(log.Fields{"args": args}).Debug("Args parsed") // get profile name from args // if not set explicitly, use first arg, if present @@ -154,9 +185,11 @@ func mainLogic(settings Settings) error { if err == nil { userConfig, err := loadConfig(fullUserConfigPath) if err != nil { - fmt.Printf("error loading user config from %v: %v\n", fullUserConfigPath, err) + return fmt.Errorf("error loading user config from %v: %w", fullUserConfigPath, err) } else { - fmt.Printf("loaded user config from %v, combining with global config\n", fullUserConfigPath) + log.WithFields(log.Fields{ + "fullUserConfigPath": fullUserConfigPath, + }).Debug("loaded user config, combining with global config") config, err = mergeConfigs(config, userConfig) if err != nil { return fmt.Errorf("error merging configs: %w", err) @@ -175,7 +208,6 @@ func mainLogic(settings Settings) error { // get profile information if settings.profile == "get" { - fmt.Printf("Profile '%v':\n", settings.projectName) index, err := findProfileIndex(config.Profiles, settings.projectName) if err != nil { return fmt.Errorf("profile '%v' not found", settings.projectName) @@ -190,6 +222,7 @@ func mainLogic(settings Settings) error { } yamlText := writer.String() + fmt.Printf("Profile '%v':\n", settings.projectName) fmt.Println(yamlText) return nil } diff --git a/profile.go b/profile.go index 1fff7f4..1a1ac07 100644 --- a/profile.go +++ b/profile.go @@ -10,6 +10,7 @@ import ( "strings" "time" + log "github.com/sirupsen/logrus" "golang.org/x/exp/slices" ) @@ -178,7 +179,10 @@ func createEntity( profileType := profile.Type fullPath := filepath.Join(cwd, newName) if profileType == FolderType { - fmt.Printf("Creating directory: %v\n", fullPath) + log.WithFields(log.Fields{ + "fullPath": fullPath, + "profileType": profileType, + }).Debug("Creating directory") err := monkey.OSMkdir(fullPath, os.ModePerm) if err != nil { return "", fmt.Errorf("error creating directory: %v", err) @@ -190,7 +194,10 @@ func createEntity( // create files in the new folder if len(profile.Files) > 0 { - fmt.Printf("Creating files in directory: %v\n", fullPath) + log.WithFields(log.Fields{ + "fullPath": fullPath, + "fileCount": len(profile.Files), + }).Debug("Creating files in directory") for index, file := range profile.Files { fileName, filePrePatternData, err := createNewNameForPatterns(now, projectName, []ParameterizedText{file.Name}, extras, []string{}) if err != nil { @@ -199,7 +206,7 @@ func createEntity( subFilePath := filepath.Join(fullPath, fileName) err = createFile(filePrePatternData, file.File, subFilePath) if err != nil { - return "", err + return "", fmt.Errorf("error creating file %v: %v", subFilePath, err) } } } @@ -209,7 +216,7 @@ func createEntity( return "", err } } else { - fmt.Printf("Profile type is script, doing nothing during main phase\n") + log.Debug("Profile type is script, doing nothing during main phase") } return fullPath, nil }