Skip to content

Commit

Permalink
(feat): Ensured errors are logged with logrus ERROR level.
Browse files Browse the repository at this point in the history
Signed-off-by: Camila Macedo <[email protected]>
  • Loading branch information
camilamacedo86 authored and Camila Macedo committed Sep 28, 2023
1 parent 5405c0e commit d943d74
Show file tree
Hide file tree
Showing 22 changed files with 51 additions and 47 deletions.
5 changes: 3 additions & 2 deletions cmd/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"fmt"
"github.com/sirupsen/logrus"
"os"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -34,7 +35,7 @@ func doGenRstDocs(cmd *cobra.Command, args []string) {
rootCmd.DisableAutoGenTag = true
err := doc.GenReSTTreeCustom(rootCmd, outDir, filePrepender, linkHandler)
if err != nil {
fmt.Println("ERROR:", err)
logrus.Error("ERROR:", err)
os.Exit(1)
}
}
Expand All @@ -57,7 +58,7 @@ func doGenMdDocs(cmd *cobra.Command, args []string) {
rootCmd.DisableAutoGenTag = true
err := doc.GenMarkdownTree(rootCmd, outDir)
if err != nil {
fmt.Println("ERROR:", err)
logrus.Error("ERROR:", err)
os.Exit(1)
}
}
9 changes: 5 additions & 4 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,13 @@ func Execute() {
}

if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
logrus.Error(err)
os.Exit(1)
}
}

func init() {
logrus.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true})
cobra.OnInitialize(initConfig)

rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $HOME/.config/fioctl.yaml)")
Expand Down Expand Up @@ -103,12 +104,12 @@ func init() {
func getConfigDir() string {
config, err := homedir.Expand("~/.config")
if err != nil {
fmt.Println(err)
logrus.Error(err)
os.Exit(1)
}
if _, err := os.Stat(config); errors.Is(err, fs.ErrNotExist) {
if err := os.Mkdir(config, 0755); err != nil {
fmt.Println(err)
logrus.Error(err)
os.Exit(1)
}
}
Expand Down Expand Up @@ -137,7 +138,7 @@ func initConfig() {
logrus.Debug("Config file not found")
} else {
// Config file was found but another error was produced
fmt.Println("ERROR: ", err)
logrus.Error("ERROR: ", err)
os.Exit(1)
}
}
Expand Down
4 changes: 2 additions & 2 deletions subcommands/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func DieNotNil(err error, message ...string) {
parts = append(parts, p)
}
parts = append(parts, err)
fmt.Println(parts...)
logrus.Error(parts...)
for _, w := range onLastWill {
w()
}
Expand Down Expand Up @@ -177,7 +177,7 @@ func AssertWritable(path string) {
DieNotNil(err)
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, st.Mode())
if err != nil {
fmt.Println("ERROR: File is not writeable:", path)
logrus.Error("ERROR: File is not writeable:", path)
os.Exit(1)
}
f.Close()
Expand Down
2 changes: 1 addition & 1 deletion subcommands/config/wireguard.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func (w *WireguardServerConfig) Unmarshall(configVal string) {
} else if k == "enabled" {
w.Enabled = v != "0"
} else {
fmt.Println("ERROR: Unexpected client config key: ", k)
logrus.Error("ERROR: Unexpected client config key: ", k)
os.Exit(1)
}
}
Expand Down
12 changes: 6 additions & 6 deletions subcommands/devices/config_wireguard.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (w *WireguardClientConfig) Unmarshall(configVal string) {
} else if k == "pubkey" {
w.PublicKey = strings.TrimSpace(parts[1])
} else {
fmt.Println("ERROR: Unexpected client config key: ", k)
logrus.Error("ERROR: Unexpected client config key: ", k)
os.Exit(1)
}
}
Expand Down Expand Up @@ -105,13 +105,13 @@ func factoryIps(factory string) map[uint32]bool {
func findVpnAddress(factory string) string {
wsc := config.LoadWireguardServerConfig(factory, api)
if len(wsc.VpnAddress) == 0 || !wsc.Enabled {
fmt.Println("ERROR: A wireguard server has not been configured for this factory")
logrus.Error("ERROR: A wireguard server has not been configured for this factory")
os.Exit(1)
}
logrus.Debugf("VPN server address is: %s", wsc.VpnAddress)
serverIp, err := ipToUint32(wsc.VpnAddress)
if err != nil {
fmt.Println("ERROR: Wireguard server has an invalid IP Address: ", wsc.VpnAddress)
logrus.Error("ERROR: Wireguard server has an invalid IP Address: ", wsc.VpnAddress)
os.Exit(1)
}

Expand All @@ -123,7 +123,7 @@ func findVpnAddress(factory string) string {
}
}

fmt.Println("ERROR: Unable to find unique IP address for VPN")
logrus.Error("ERROR: Unable to find unique IP address for VPN")
os.Exit(1)
return ""
}
Expand All @@ -144,7 +144,7 @@ func doConfigWireguard(cmd *cobra.Command, args []string) {
}
os.Exit(0)
} else if args[1] != "enable" && args[1] != "disable" {
fmt.Printf("Invalid argument: '%s'. Must be 'enable' or 'disable'\n", args[1])
logrus.Errorf("Invalid argument: '%s'. Must be 'enable' or 'disable'\n", args[1])
os.Exit(0)
}

Expand All @@ -161,7 +161,7 @@ func doConfigWireguard(cmd *cobra.Command, args []string) {

if args[1] == "enable" {
if len(wcc.PublicKey) == 0 {
fmt.Println("ERROR: Device has no public key for VPN")
logrus.Error("ERROR: Device has no public key for VPN")
os.Exit(1)
}
wcc.Enabled = true
Expand Down
2 changes: 1 addition & 1 deletion subcommands/devices/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func doDelete(cmd *cobra.Command, args []string) {
for _, name := range args {
fmt.Printf("Deleting %s .. ", name)
if err := api.DeviceDelete(factory, name); err != nil {
fmt.Printf("failed\n%s", err)
logrus.Errorf("failed\n%s", err)
os.Exit(1)
} else {
fmt.Printf("ok\n")
Expand Down
2 changes: 1 addition & 1 deletion subcommands/devices/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func showDeviceList(dl *client.DeviceList, showColumns []string) {
var cols = make([]interface{}, len(showColumns))
for idx, c := range showColumns {
if _, ok := Columns[c]; !ok {
fmt.Println("ERROR: Invalid column name:", c)
logrus.Error("ERROR: Invalid column name:", c)
os.Exit(1)
}
cols[idx] = strings.ToUpper(c)
Expand Down
3 changes: 1 addition & 2 deletions subcommands/devices/rename.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package devices

import (
"fmt"
"os"

"github.com/sirupsen/logrus"
Expand All @@ -23,7 +22,7 @@ func doRename(cmd *cobra.Command, args []string) {
logrus.Debugf("Renaming %s -> %s", args[0], args[1])

if err := api.DeviceRename(factory, args[0], args[1]); err != nil {
fmt.Printf("failed\n%s", err)
logrus.Errorf("failed\n%s", err)
os.Exit(1)
}
}
1 change: 1 addition & 0 deletions subcommands/docker/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ func RunCredsHelper() int {
if subcommands.Config.ClientCredentials.ClientSecret == "" {
msg := "ERROR: Your fioctl configuration does not appear to include oauth2 credentials. Please run `fioctl login` to configure and then try again.\n"
os.Stderr.WriteString(msg)
logrus.Error(msg)
os.Exit(1)
}
subcommands.Login(NewCommand()) // Ensure a fresh oauth2 access token
Expand Down
1 change: 1 addition & 0 deletions subcommands/git/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ func RunCredsHelper() int {
if subcommands.Config.ClientCredentials.ClientSecret == "" {
msg := "ERROR: Your fioctl configuration does not appear to include oauth2 credentials. Please run `fioctl login` to configure and then try again.\n"
os.Stderr.WriteString(msg)
logrus.Error(msg)
os.Exit(1)
}
subcommands.Login(NewCommand()) // Ensure a fresh oauth2 access tokenA
Expand Down
4 changes: 2 additions & 2 deletions subcommands/keys/ca_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ This is optional.`,

func writeFile(filename, contents string, mode os.FileMode) {
if err := os.WriteFile(filename, []byte(contents), mode); err != nil {
fmt.Printf("ERROR: Creating %s: %s", filename, err)
logrus.Errorf("ERROR: Creating %s: %s", filename, err)
os.Exit(1)
}
}
Expand All @@ -84,7 +84,7 @@ func doCreateCA(cmd *cobra.Command, args []string) {

if len(hsmModule) > 0 {
if len(hsmPin) == 0 {
fmt.Println("ERROR: --hsm-pin is required with --hsm-module")
logrus.Error("ERROR: --hsm-pin is required with --hsm-module")
os.Exit(1)
}
os.Setenv("HSM_MODULE", hsmModule)
Expand Down
4 changes: 2 additions & 2 deletions subcommands/login/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func doLogin(cmd *cobra.Command, args []string) {
}

if creds.Config.ClientId == "" || creds.Config.ClientSecret == "" {
fmt.Println("Cannot execute login without client ID or client secret.")
logrus.Error("Cannot execute login without client ID or client secret.")
os.Exit(1)
}

Expand Down Expand Up @@ -106,7 +106,7 @@ func promptForCreds(credsUrl string) (string, string) {
clientSecret := strings.Trim(scanner.Text(), " ")

if clientId == "" || clientSecret == "" {
fmt.Println("Client ID and client credentials are both required.")
logrus.Error("ERROR: Client ID and client credentials are both required.")
os.Exit(1)
}

Expand Down
3 changes: 1 addition & 2 deletions subcommands/secrets/list.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package secrets

import (
"fmt"
"os"

"github.com/cheynewallace/tabby"
Expand Down Expand Up @@ -34,7 +33,7 @@ func doList(cmd *cobra.Command, args []string) {
t.AddLine(secret.Name)
}
} else if len(triggers) != 0 {
fmt.Println("ERROR: Factory configuration issue. Factory has unexpected number of triggers.")
logrus.Error("ERROR: Factory configuration issue. Factory has unexpected number of triggers.")
os.Exit(1)
}
t.Print()
Expand Down
5 changes: 2 additions & 3 deletions subcommands/secrets/update.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package secrets

import (
"fmt"
"os"
"strings"

Expand Down Expand Up @@ -42,7 +41,7 @@ func doUpdate(cmd *cobra.Command, args []string) {
for i, arg := range args {
parts := strings.SplitN(arg, "=", 2)
if len(parts) != 2 {
fmt.Println("ERROR: Invalid key=value argument: ", arg)
logrus.Error("ERROR: Invalid key=value argument: ", arg)
os.Exit(1)
}
secrets[i].Name = parts[0]
Expand All @@ -67,7 +66,7 @@ func doUpdate(cmd *cobra.Command, args []string) {
} else if len(triggers) == 1 {
pt = triggers[0]
} else {
fmt.Println("ERROR: Factory configuration issue. Factory has unexpected number of triggers.")
logrus.Error("ERROR: Factory configuration issue. Factory has unexpected number of triggers.")
os.Exit(1)
}

Expand Down
2 changes: 1 addition & 1 deletion subcommands/targets/artifacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (d *DlStatus) Write(p []byte) (int, error) {
func downloadArtifact(factory string, target int, artifact string) {
firstSlash := strings.Index(artifact, "/")
if firstSlash < 1 {
fmt.Println("ERROR: Invalid artifact path:", artifact)
logrus.Error("ERROR: Invalid artifact path:", artifact)
os.Exit(1)
}
run := artifact[0:firstSlash]
Expand Down
12 changes: 6 additions & 6 deletions subcommands/targets/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,16 @@ func doEdit(cmd *cobra.Command, args []string) {
// Create temp file to edit with
tmpfile, err := os.CreateTemp("", "targets.*.json")
if err != nil {
fmt.Println("Unable to create tempfile: ", err)
logrus.Error("Unable to create tempfile: ", err)
os.Exit(1)
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.Write(orig); err != nil {
fmt.Println("Unable to write tempfile: ", err)
logrus.Error("Unable to write tempfile: ", err)
os.Exit(1)
}
if err := tmpfile.Close(); err != nil {
fmt.Println("Unable to close tempfile: ", err)
logrus.Error("Unable to close tempfile: ", err)
os.Exit(1)
}

Expand All @@ -72,7 +72,7 @@ func doEdit(cmd *cobra.Command, args []string) {
// Read it and see if its changed
content, err := os.ReadFile(tmpfile.Name())
if err != nil {
fmt.Println("ERROR: Unable to re-read tempfile:", err)
logrus.Error("ERROR: Unable to re-read tempfile:", err)
}
if bytes.Equal(content, orig) {
fmt.Println("No changes found, exiting.")
Expand All @@ -83,7 +83,7 @@ func doEdit(cmd *cobra.Command, args []string) {
var newTargets tuf.Files
err = json.Unmarshal(content, &newTargets)
if err != nil {
fmt.Println("Unable to parse new targets: ", err)
logrus.Error("Unable to parse new targets: ", err)
os.Exit(1)
}
type TargetsUp struct {
Expand All @@ -92,7 +92,7 @@ func doEdit(cmd *cobra.Command, args []string) {
upload := TargetsUp{newTargets}
content, err = json.Marshal(upload)
if err != nil {
fmt.Println("Unable to marshall targets data: ", err)
logrus.Error("Unable to marshall targets data: ", err)
os.Exit(1)
}

Expand Down
4 changes: 2 additions & 2 deletions subcommands/targets/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ func validateAppShortlist() {
pattern := `^[a-zA-Z0-9-_,]+$`
re := regexp.MustCompile(pattern)
if len(appsShortlist) > 0 && !re.MatchString(appsShortlist) {
fmt.Println("ERROR: Invalid value for apps:", appsShortlist)
fmt.Println(" apps must be ", pattern)
logrus.Error("ERROR: Invalid value for apps:", appsShortlist)
logrus.Error(" apps must be ", pattern)
os.Exit(1)
}
}
Expand Down
2 changes: 1 addition & 1 deletion subcommands/targets/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func doList(cmd *cobra.Command, args []string) {
var cols = make([]interface{}, len(showColumns))
for idx, c := range showColumns {
if _, ok := Columns[c]; !ok {
fmt.Println("ERROR: Invalid column name:", c)
logrus.Error("ERROR: Invalid column name:", c)
os.Exit(1)
}
cols[idx] = strings.ToUpper(c)
Expand Down
5 changes: 3 additions & 2 deletions subcommands/targets/prune.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package targets

import (
"fmt"
"github.com/sirupsen/logrus"
"os"
"sort"
"strconv"
Expand Down Expand Up @@ -98,7 +99,7 @@ func doPrune(cmd *cobra.Command, args []string) {
for _, name := range target_names {
parts := strings.SplitN(name, "lmp-", 2)
if len(parts) != 2 {
fmt.Printf("Unable to decode target name: %s\n", name)
logrus.Errorf("Unable to decode target name: %s\n", name)
os.Exit(1)
}
custom, _ := api.TargetCustom(targets[name])
Expand Down Expand Up @@ -132,7 +133,7 @@ func doPrune(cmd *cobra.Command, args []string) {
} else {
for _, name := range args {
if _, ok := targets[name]; !ok {
fmt.Printf("Target(%s) not found in targets.json\n", name)
logrus.Errorf("Target(%s) not found in targets.json\n", name)
os.Exit(1)
}
}
Expand Down
Loading

0 comments on commit d943d74

Please sign in to comment.