Skip to content

Commit

Permalink
chore: directly handle ignored errs and nolint intentionally ignored …
Browse files Browse the repository at this point in the history
…errs (zarf-dev#2993)

Signed-off-by: Kit Patella <[email protected]>
Signed-off-by: ittacco <[email protected]>
  • Loading branch information
mkcp authored and ittacco committed Oct 18, 2024
1 parent 64af250 commit 9df409f
Show file tree
Hide file tree
Showing 37 changed files with 349 additions and 121 deletions.
13 changes: 10 additions & 3 deletions src/cmd/destroy.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ var destroyCmd = &cobra.Command{
Aliases: []string{"d"},
Short: lang.CmdDestroyShort,
Long: lang.CmdDestroyLong,
// TODO(mkcp): refactor and de-nest this function.
RunE: func(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
timeoutCtx, cancel := context.WithTimeout(cmd.Context(), cluster.DefaultTimeout)
Expand Down Expand Up @@ -57,7 +58,10 @@ var destroyCmd = &cobra.Command{

// Run all the scripts!
pattern := regexp.MustCompile(`(?mi)zarf-clean-.+\.sh$`)
scripts, _ := helpers.RecursiveFileList(config.ZarfCleanupScriptsPath, pattern, true)
scripts, err := helpers.RecursiveFileList(config.ZarfCleanupScriptsPath, pattern, true)
if err != nil {
return err
}
// Iterate over all matching zarf-clean scripts and exec them
for _, script := range scripts {
// Run the matched script
Expand All @@ -71,8 +75,11 @@ var destroyCmd = &cobra.Command{
return fmt.Errorf("received an error when executing the script %s: %w", script, err)
}

// Try to remove the script, but ignore any errors
_ = os.Remove(script)
// Try to remove the script, but ignore any errors and debug log them
err = os.Remove(script)
if err != nil {
message.WarnErr(err, fmt.Sprintf("Unable to remove script. script=%s", script))
}
}
} else {
// Perform chart uninstallation
Expand Down
28 changes: 21 additions & 7 deletions src/cmd/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,13 @@ var devSha256SumCmd = &cobra.Command{
Aliases: []string{"s"},
Short: lang.CmdDevSha256sumShort,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, args []string) (err error) {
hashErr := errors.New("unable to compute the SHA256SUM hash")

fileName := args[0]

var tmp string
var data io.ReadCloser
var err error

if helpers.IsURL(fileName) {
message.Warn(lang.CmdDevSha256sumRemoteWarning)
Expand All @@ -182,7 +181,10 @@ var devSha256SumCmd = &cobra.Command{

fileName = downloadPath

defer os.RemoveAll(tmp)
defer func(path string) {
errRemove := os.RemoveAll(path)
err = errors.Join(err, errRemove)
}(tmp)
}

if extractPath != "" {
Expand All @@ -191,7 +193,10 @@ var devSha256SumCmd = &cobra.Command{
if err != nil {
return errors.Join(hashErr, err)
}
defer os.RemoveAll(tmp)
defer func(path string) {
errRemove := os.RemoveAll(path)
err = errors.Join(err, errRemove)
}(tmp)
}

extractedFile := filepath.Join(tmp, extractPath)
Expand All @@ -208,7 +213,10 @@ var devSha256SumCmd = &cobra.Command{
if err != nil {
return errors.Join(hashErr, err)
}
defer data.Close()
defer func(data io.ReadCloser) {
errClose := data.Close()
err = errors.Join(err, errClose)
}(data)

hash, err := helpers.GetSHA256Hash(data)
if err != nil {
Expand Down Expand Up @@ -323,8 +331,14 @@ func init() {
// use the package create config for this and reset it here to avoid overwriting the config.CreateOptions.SetVariables
devFindImagesCmd.Flags().StringToStringVar(&pkgConfig.CreateOpts.SetVariables, "set", v.GetStringMapString(common.VPkgCreateSet), lang.CmdDevFlagSet)

devFindImagesCmd.Flags().MarkDeprecated("set", "this field is replaced by create-set")
devFindImagesCmd.Flags().MarkHidden("set")
err := devFindImagesCmd.Flags().MarkDeprecated("set", "this field is replaced by create-set")
if err != nil {
message.Debug("Unable to mark dev-find-images flag as set", "error", err)
}
err = devFindImagesCmd.Flags().MarkHidden("set")
if err != nil {
message.Debug("Unable to mark dev-find-images flag as hidden", "error", err)
}
devFindImagesCmd.Flags().StringVarP(&pkgConfig.CreateOpts.Flavor, "flavor", "f", v.GetString(common.VPkgCreateFlavor), lang.CmdPackageCreateFlagFlavor)
devFindImagesCmd.Flags().StringToStringVar(&pkgConfig.CreateOpts.SetVariables, "create-set", v.GetStringMapString(common.VPkgCreateSet), lang.CmdDevFlagSet)
devFindImagesCmd.Flags().StringToStringVar(&pkgConfig.PkgOpts.SetVariables, "deploy-set", v.GetStringMapString(common.VPkgDeploySet), lang.CmdPackageDeployFlagSet)
Expand Down
35 changes: 20 additions & 15 deletions src/cmd/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,27 @@ func findInitPackage(ctx context.Context, initPackageName string) (string, error
}

// Create the cache directory if it doesn't exist
if helpers.InvalidPath(config.GetAbsCachePath()) {
if err := helpers.CreateDirectory(config.GetAbsCachePath(), helpers.ReadExecuteAllWriteUser); err != nil {
return "", fmt.Errorf("unable to create the cache directory %s: %w", config.GetAbsCachePath(), err)
absCachePath, err := config.GetAbsCachePath()
if err != nil {
return "", err
}
// Verify that we can write to the path
if helpers.InvalidPath(absCachePath) {
// Create the directory if the path is invalid
err = helpers.CreateDirectory(absCachePath, helpers.ReadExecuteAllWriteUser)
if err != nil {
return "", fmt.Errorf("unable to create the cache directory %s: %w", absCachePath, err)
}
}

// Next, look in the cache directory
if !helpers.InvalidPath(filepath.Join(config.GetAbsCachePath(), initPackageName)) {
return filepath.Join(config.GetAbsCachePath(), initPackageName), nil
if !helpers.InvalidPath(filepath.Join(absCachePath, initPackageName)) {
// join and return
return filepath.Join(absCachePath, initPackageName), nil
}

// Finally, if the init-package doesn't exist in the cache directory, suggest downloading it
downloadCacheTarget, err := downloadInitPackage(ctx, config.GetAbsCachePath())
downloadCacheTarget, err := downloadInitPackage(ctx, absCachePath)
if err != nil {
if errors.Is(err, lang.ErrInitNotFound) {
return "", err
Expand All @@ -121,22 +129,19 @@ func downloadInitPackage(ctx context.Context, cacheDirectory string) (string, er
return "", lang.ErrInitNotFound
}

var confirmDownload bool
url := zoci.GetInitPackageURL(config.CLIVersion)

// Give the user the choice to download the init-package and note that this does require an internet connection
message.Question(fmt.Sprintf(lang.CmdInitPullAsk, url))

message.Note(lang.CmdInitPullNote)

// Prompt the user if --confirm not specified
if !confirmDownload {
prompt := &survey.Confirm{
Message: lang.CmdInitPullConfirm,
}
if err := survey.AskOne(prompt, &confirmDownload); err != nil {
return "", fmt.Errorf("confirm download canceled: %w", err)
}
var confirmDownload bool
prompt := &survey.Confirm{
Message: lang.CmdInitPullConfirm,
}
if err := survey.AskOne(prompt, &confirmDownload); err != nil {
return "", fmt.Errorf("confirm download canceled: %w", err)
}

// If the user wants to download the init-package, download it
Expand Down
9 changes: 6 additions & 3 deletions src/cmd/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,8 @@ var isValidHostname = &cobra.Command{
Short: lang.CmdInternalIsValidHostnameShort,
RunE: func(_ *cobra.Command, _ []string) error {
if valid := helpers.IsValidHostName(); !valid {
hostname, _ := os.Hostname()
return fmt.Errorf("the hostname %s is not valid. Ensure the hostname meets RFC1123 requirements https://www.rfc-editor.org/rfc/rfc1123.html", hostname)
hostname, err := os.Hostname()
return fmt.Errorf("the hostname %s is not valid. Ensure the hostname meets RFC1123 requirements https://www.rfc-editor.org/rfc/rfc1123.html, error=%w", hostname, err)
}
return nil
},
Expand Down Expand Up @@ -388,6 +388,9 @@ func addHiddenDummyFlag(cmd *cobra.Command, flagDummy string) {
if cmd.PersistentFlags().Lookup(flagDummy) == nil {
var dummyStr string
cmd.PersistentFlags().StringVar(&dummyStr, flagDummy, "", "")
cmd.PersistentFlags().MarkHidden(flagDummy)
err := cmd.PersistentFlags().MarkHidden(flagDummy)
if err != nil {
message.Debug("Unable to add hidden dummy flag", "error", err)
}
}
}
50 changes: 41 additions & 9 deletions src/cmd/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,10 @@ var packageInspectCmd = &cobra.Command{
if err != nil {
return fmt.Errorf("failed to inspect package: %w", err)
}
utils.ColorPrintYAML(output, nil, false)
err = utils.ColorPrintYAML(output, nil, false)
if err != nil {
return err
}
return nil
},
}
Expand Down Expand Up @@ -382,9 +385,23 @@ func choosePackage(args []string) (string, error) {
prompt := &survey.Input{
Message: lang.CmdPackageChoose,
Suggest: func(toComplete string) []string {
files, _ := filepath.Glob(config.ZarfPackagePrefix + toComplete + "*.tar")
zstFiles, _ := filepath.Glob(config.ZarfPackagePrefix + toComplete + "*.tar.zst")
splitFiles, _ := filepath.Glob(config.ZarfPackagePrefix + toComplete + "*.part000")
tarPath := config.ZarfPackagePrefix + toComplete + "*.tar"
files, err := filepath.Glob(tarPath)
if err != nil {
message.Debug("Unable to glob", "tarPath", tarPath, "error", err)
}

zstPath := config.ZarfPackagePrefix + toComplete + "*.tar.zst"
zstFiles, err := filepath.Glob(zstPath)
if err != nil {
message.Debug("Unable to glob", "zstPath", zstPath, "error", err)
}

splitPath := config.ZarfPackagePrefix + toComplete + "*.part000"
splitFiles, err := filepath.Glob(splitPath)
if err != nil {
message.Debug("Unable to glob", "splitPath", splitPath, "error", err)
}

files = append(files, zstFiles...)
files = append(files, splitFiles...)
Expand All @@ -409,7 +426,10 @@ func getPackageCompletionArgs(cmd *cobra.Command, _ []string, _ string) ([]strin

ctx := cmd.Context()

deployedZarfPackages, _ := c.GetDeployedZarfPackages(ctx)
deployedZarfPackages, err := c.GetDeployedZarfPackages(ctx)
if err != nil {
message.Debug("Unable to get deployed zarf packages for package completion args", "error", err)
}
// Populate list of package names
for _, pkg := range deployedZarfPackages {
pkgCandidates = append(pkgCandidates, pkg.Name)
Expand Down Expand Up @@ -478,9 +498,18 @@ func bindCreateFlags(v *viper.Viper) {

createFlags.IntVar(&pkgConfig.PkgOpts.Retries, "retries", v.GetInt(common.VPkgRetries), lang.CmdPackageFlagRetries)

createFlags.MarkHidden("output-directory")
createFlags.MarkHidden("key")
createFlags.MarkHidden("key-pass")
errOD := createFlags.MarkHidden("output-directory")
if errOD != nil {
message.Debug("Unable to mark flag output-directory", "error", errOD)
}
errKey := createFlags.MarkHidden("key")
if errKey != nil {
message.Debug("Unable to mark flag key", "error", errKey)
}
errKP := createFlags.MarkHidden("key-pass")
if errKP != nil {
message.Debug("Unable to mark flag key-pass", "error", errKP)
}
}

func bindDeployFlags(v *viper.Viper) {
Expand All @@ -501,7 +530,10 @@ func bindDeployFlags(v *viper.Viper) {
deployFlags.StringVar(&pkgConfig.PkgOpts.SGetKeyPath, "sget", v.GetString(common.VPkgDeploySget), lang.CmdPackageDeployFlagSget)
deployFlags.BoolVar(&pkgConfig.PkgOpts.SkipSignatureValidation, "skip-signature-validation", false, lang.CmdPackageFlagSkipSignatureValidation)

deployFlags.MarkHidden("sget")
err := deployFlags.MarkHidden("sget")
if err != nil {
message.Debug("Unable to mark flag sget", "error", err)
}
}

func bindMirrorFlags(v *viper.Viper) {
Expand Down
5 changes: 4 additions & 1 deletion src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ var rootCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
zarfLogo := message.GetLogo()
_, _ = fmt.Fprintln(os.Stderr, zarfLogo)
cmd.Help()
err := cmd.Help()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}

if len(args) > 0 {
if strings.Contains(args[0], config.ZarfPackagePrefix) || strings.Contains(args[0], "zarf-init") {
Expand Down
7 changes: 6 additions & 1 deletion src/cmd/tools/helm.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ package tools
import (
"os"

"github.com/zarf-dev/zarf/src/pkg/message"

"github.com/zarf-dev/zarf/src/cmd/tools/helm"
"github.com/zarf-dev/zarf/src/config/lang"
"helm.sh/helm/v3/pkg/action"
Expand All @@ -24,7 +26,10 @@ func init() {
helmArgs = os.Args[3:]
}
// The inclusion of Helm in this manner should be changed once https://github.com/helm/helm/pull/12725 is merged
helmCmd, _ := helm.NewRootCmd(actionConfig, os.Stdout, helmArgs)
helmCmd, err := helm.NewRootCmd(actionConfig, os.Stdout, helmArgs)
if err != nil {
message.Debug("Failed to initialize helm command", "error", err)
}
helmCmd.Short = lang.CmdToolsHelmShort
helmCmd.Long = lang.CmdToolsHelmLong
helmCmd.AddCommand(newVersionCmd("helm", helmVersion))
Expand Down
12 changes: 8 additions & 4 deletions src/cmd/tools/zarf.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,15 @@ var clearCacheCmd = &cobra.Command{
Aliases: []string{"c"},
Short: lang.CmdToolsClearCacheShort,
RunE: func(_ *cobra.Command, _ []string) error {
message.Notef(lang.CmdToolsClearCacheDir, config.GetAbsCachePath())
if err := os.RemoveAll(config.GetAbsCachePath()); err != nil {
return fmt.Errorf("unable to clear the cache directory %s: %w", config.GetAbsCachePath(), err)
cachePath, err := config.GetAbsCachePath()
if err != nil {
return err
}
message.Notef(lang.CmdToolsClearCacheDir, cachePath)
if err := os.RemoveAll(cachePath); err != nil {
return fmt.Errorf("unable to clear the cache directory %s: %w", cachePath, err)
}
message.Successf(lang.CmdToolsClearCacheSuccess, config.GetAbsCachePath())
message.Successf(lang.CmdToolsClearCacheSuccess, cachePath)
return nil
},
}
Expand Down
13 changes: 8 additions & 5 deletions src/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,19 @@ func GetDataInjectionMarker() string {
}

// GetAbsCachePath gets the absolute cache path for images and git repos.
func GetAbsCachePath() string {
func GetAbsCachePath() (string, error) {
return GetAbsHomePath(CommonOptions.CachePath)
}

// GetAbsHomePath replaces ~ with the absolute path to a user's home dir
func GetAbsHomePath(path string) string {
homePath, _ := os.UserHomeDir()
func GetAbsHomePath(path string) (string, error) {
homePath, err := os.UserHomeDir()
if err != nil {
return "", err
}

if strings.HasPrefix(path, "~") {
return strings.Replace(path, "~", homePath, 1)
return strings.Replace(path, "~", homePath, 1), nil
}
return path
return path, nil
}
3 changes: 2 additions & 1 deletion src/internal/git/repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ func TestRepository(t *testing.T) {
require.NoError(t, err)
_, err = newFile.Write([]byte("Hello World"))
require.NoError(t, err)
newFile.Close()
err = newFile.Close()
require.NoError(t, err)
_, err = w.Add(filePath)
require.NoError(t, err)
_, err = w.Commit("Initial commit", &git.CommitOptions{
Expand Down
9 changes: 7 additions & 2 deletions src/internal/gitea/gitea.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -47,7 +48,7 @@ func NewClient(endpoint, username, password string) (*Client, error) {
}

// DoRequest performs a request to the Gitea API at the given path.
func (g *Client) DoRequest(ctx context.Context, method string, path string, body []byte) ([]byte, int, error) {
func (g *Client) DoRequest(ctx context.Context, method string, path string, body []byte) (_ []byte, _ int, err error) {
u, err := g.endpoint.Parse(path)
if err != nil {
return nil, 0, err
Expand All @@ -63,7 +64,11 @@ func (g *Client) DoRequest(ctx context.Context, method string, path string, body
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
defer func() {
errClose := resp.Body.Close()
err = errors.Join(err, errClose)
}()

b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, 0, err
Expand Down
Loading

0 comments on commit 9df409f

Please sign in to comment.