Skip to content

Remove unused flag code in root #1103

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 52 commits into from
Mar 17, 2025

Conversation

samtholiya
Copy link
Collaborator

@samtholiya samtholiya commented Mar 1, 2025

what

  • There is no use of this code here because we set the values already here

why

  • We were suspecting this code to not work anyway and cleaning up the code is much better, it avoids confusion. Especially when we already set the values here

Note: We are not refactoring the whole logging logic here. This is just a clean up that would help us reduce the pr size. Also reducing the places where we repeat setting the values

references

Summary by CodeRabbit

  • New Features

    • Introduced a unified logging helper that provides consistent terminal messaging.
    • Enhanced logging configuration capabilities to allow dynamic adjustments based on environment variables and command-line inputs.
  • Refactor

    • Centralized the logging configuration to pull settings directly from the configuration, improving error handling and message consistency.
    • Added new functions for parsing command-line flags and setting log configuration.
  • Tests

    • Updated CLI log outputs and error messages to reflect revised severity labels and environment details.
    • Adjusted expected outputs in test cases to align with new logging behavior.
  • Chores

    • Removed deprecated environment variable support for overriding logging settings.

@github-actions github-actions bot added the size/s label Mar 1, 2025
@osterman
Copy link
Member

osterman commented Mar 1, 2025

We added this in an emergency patch release. I don’t believe the underlying issue is resolved.

@samtholiya
Copy link
Collaborator Author

We added this in an emergency patch release. I don’t believe the underlying issue is resolved.

So these lines were updated because there was a code that actually assigned these values.
I wanted to check if it already made sense. And i found out it does not.

You are right to say the Patchy work is not getting refactored and that is not the intent of this pr. The intent of this pr is to clear this unwanted condition.

Just cleaning things :)

@samtholiya samtholiya force-pushed the feature/dev-3074-remove-unused-flags-value-code branch from 252686f to 08f1a58 Compare March 1, 2025 15:38
@samtholiya samtholiya force-pushed the feature/dev-3074-remove-unused-flags-value-code branch from 08f1a58 to 3e091f9 Compare March 1, 2025 15:40
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 2, 2025
Copy link

codecov bot commented Mar 2, 2025

Codecov Report

Attention: Patch coverage is 30.00000% with 35 lines in your changes missing coverage. Please review.

Project coverage is 21.64%. Comparing base (56a325b) to head (9e70a8c).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/config/config.go 35.89% 21 Missing and 4 partials ⚠️
internal/exec/terraform_outputs.go 0.00% 4 Missing ⚠️
cmd/root.go 25.00% 2 Missing and 1 partial ⚠️
pkg/utils/log_utils.go 0.00% 2 Missing ⚠️
pkg/config/utils.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1103      +/-   ##
==========================================
+ Coverage   21.29%   21.64%   +0.35%     
==========================================
  Files         172      172              
  Lines       19309    19292      -17     
==========================================
+ Hits         4112     4176      +64     
+ Misses      14425    14336      -89     
- Partials      772      780       +8     
Flag Coverage Δ
unittests 21.64% <30.00%> (+0.35%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Member

@osterman osterman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to distinguish between log output, which is for developers and console output, which is for users. Previously, the code was not clear about this and muddled it by using log levels to control console output. Hence it makes sense why you are condensing it into log statements, but the original logic was flawed.

Please introduce a function so we make it clear and deliberate when we are showing console output as opposed to log output .

For example, in the future, we might introduce a quiet flag, which affects the console output, but does not affect the log output.

@samtholiya samtholiya force-pushed the feature/dev-3074-remove-unused-flags-value-code branch from 4751348 to 69fc1b4 Compare March 5, 2025 22:40
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
pkg/config/config.go (3)

395-410: The log configuration logic looks correct but could benefit from refactoring.

The function appropriately checks environment variables and command-line flags for logging configuration. The priority order (flags override environment variables) is logical.

However, the TODO comment indicates this is a quick patch. Consider revisiting this in a future PR to integrate with Cobra's built-in flag handling system.


418-418: Add period at end of comment.

The static code analyzer correctly flagged this missing period at the end of the comment.

-// Function to manually parse flags with double dash "--" like Cobra
+// Function to manually parse flags with double dash "--" like Cobra.

419-447: Flag parsing implementation could be simplified.

The flag parsing logic works correctly but could be simplified as suggested by static analysis tools.

Consider these improvements:

  1. Simplify the if-else chain using early returns
  2. Use a switch statement for better readability
  3. Return a potential error for better error handling
 func parseFlags() map[string]string {
 	args := os.Args
 	flags := make(map[string]string)
 	for i := 0; i < len(args); i++ {
 		arg := args[i]

 		// Check if the argument starts with '--' (double dash)
 		if strings.HasPrefix(arg, "--") {
 			// Strip the '--' prefix and check if it's followed by a value
 			arg = arg[2:]
-			if strings.Contains(arg, "=") {
-				// Case like --flag=value
-				parts := strings.SplitN(arg, "=", 2)
-				flags[parts[0]] = parts[1]
-			} else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "--") {
-				// Case like --flag value
-				flags[arg] = args[i+1]
-				i++ // Skip the next argument as it's the value
-			} else {
-				// Case where flag has no value, e.g., --flag (we set it to "true")
-				flags[arg] = "true"
-			}
-		} else {
-			// It's a regular argument, not a flag, so we skip
-			continue
+			
+			switch {
+			case strings.Contains(arg, "="):
+				// Case like --flag=value
+				parts := strings.SplitN(arg, "=", 2)
+				flags[parts[0]] = parts[1]
+			case i+1 < len(args) && !strings.HasPrefix(args[i+1], "--"):
+				// Case like --flag value
+				flags[arg] = args[i+1]
+				i++ // Skip the next argument as it's the value
+			default:
+				// Case where flag has no value, e.g., --flag (we set it to "true")
+				flags[arg] = "true"
+			}
+			continue
 		}
+		
+		// It's a regular argument, not a flag, so we skip
 	}
 	return flags
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab7d416 and 4ee23af.

📒 Files selected for processing (2)
  • cmd/root.go (2 hunks)
  • pkg/config/config.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/root.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (4)
pkg/config/config.go (4)

10-10: Appropriate import addition.

New import aligns with the strings manipulation needs in parseFlags function.


389-389: Good integration of log configuration.

Calling setLogConfig at the end of InitCliConfig ensures log settings are applied after all other configuration steps, centralizing the logging configuration.


412-417: Valid concern about manual flag parsing.

The TODO correctly acknowledges that manual flag parsing is not ideal when using Cobra. This approach works for now, but should be revisited in a future refactoring effort.


419-447:

✅ Verification successful

Verify this function handles all use cases in the codebase.

The parseFlags function assumes all flags start with --, but doesn't handle short-form flags (-f). Ensure this matches all flag usage patterns in the codebase.


🏁 Script executed:

#!/bin/bash
# Description: Search for flag pattern usage in the codebase to verify compatibility

# Search for short flags (-f) in the codebase
echo "Searching for short flags that might not be handled by parseFlags..."
rg "flag\.(StringP|BoolP|IntP)" --type go

# Check if Cobra is being used for command-line parsing
echo "Checking for Cobra command-line parsing..."
rg "cobra\.(Command|OnInitialize|AddCommand)" --type go

# Check how flags are defined in the codebase
echo "Checking how flags are registered in the codebase..."
rg "flag\.(String|Bool|Int)" --type go

# Specifically check for logs-level and logs-file flags
echo "Checking for logs-level and logs-file flags..."
rg "(logs-level|logs-file)" --type go

Length of output: 15536


Flag Parsing Approach Verified – Only Long Flags in Use

After a thorough search of our codebase:

  • There are no instances of short-form flag usage (like -f) detected.
  • Flags registered using Go’s flag package consistently use long names (e.g., "--logs-level"), matching the expectations of the parseFlags function.
  • Cobra is employed extensively for command parsing elsewhere, and it manages both long and short flags; however, parseFlags appears to be designed only for contexts where long flags are in use.

Recommendation:
Add a brief comment to the parseFlags function explaining that it is intended solely for long flag formats (e.g., --flag=value or --flag value), clarifying its limitations for any future developers.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 16, 2025
@samtholiya samtholiya force-pushed the feature/dev-3074-remove-unused-flags-value-code branch 2 times, most recently from 9bc24a5 to 27fa69e Compare March 16, 2025 14:37
@samtholiya samtholiya force-pushed the feature/dev-3074-remove-unused-flags-value-code branch from 27fa69e to 2755e69 Compare March 16, 2025 14:38
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 16, 2025
@samtholiya
Copy link
Collaborator Author

samtholiya commented Mar 16, 2025

@samtholiya tests for stderr are failing. Something wrong with the output?|

Fixed that. Happy to have this new test case in the mainline that helped a lot.

Copy link

mergify bot commented Mar 17, 2025

💥 This pull request now has conflicts. Could you fix it @samtholiya? 🙏

@mergify mergify bot added the conflict This PR has conflicts label Mar 17, 2025
@mergify mergify bot removed the conflict This PR has conflicts label Mar 17, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
pkg/config/config.go (2)

396-411: Temporary logging configuration solution needs better documentation.

The function properly centralizes log configuration from both environment variables and command line flags, which is architecturally sound. However, the TODO comment doesn't clearly explain what issue this is patching.

-// TODO: This is a quick patch to mitigate the issue we can look for better code later
+// TODO: This is a quick patch to centralize log configuration handling that was previously 
+// scattered across the codebase. In the future, we should refactor this to use a more 
+// structured approach that integrates better with Cobra's flag handling.

419-446: Manual flag parsing implementation works but has limitations.

This manual flag parsing implementation is functional for basic cases but could become a maintenance burden. It works well for the current use case of extracting logging flags, but be cautious about extending this approach.

Consider limiting the scope of this function to only parse specific logging-related flags rather than all double-dash arguments, which would reduce potential conflicts with Cobra:

-func parseFlags() map[string]string {
+func parseLoggingFlags() map[string]string {
   args := os.Args
   flags := make(map[string]string)
+  loggingFlags := []string{"logs-level", "logs-file"}
   for i := 0; i < len(args); i++ {
     arg := args[i]
     // Check if the argument starts with '--' (double dash)
     if !strings.HasPrefix(arg, "--") {
       continue
     }
     // Strip the '--' prefix and check if it's followed by a value
     arg = arg[2:]
+    // Only process logging-related flags
+    isLoggingFlag := false
+    for _, flagName := range loggingFlags {
+      if arg == flagName || strings.HasPrefix(arg, flagName+"=") {
+        isLoggingFlag = true
+        break
+      }
+    }
+    if !isLoggingFlag {
+      continue
+    }
     switch {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7047e5 and 6bddcfe.

📒 Files selected for processing (2)
  • pkg/config/config.go (2 hunks)
  • pkg/config/utils.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (3)
pkg/config/utils.go (1)

361-361: Consistent logging format update.

The change from u.LogDebug(fmt.Sprintf(...)) to structured logging with log.Debug(..., ...) is a good improvement that aligns with modern logging practices.

pkg/config/config.go (2)

390-390: Good centralization of log configuration.

This call to setLogConfig finalizes the log configuration after all other configurations have been processed, ensuring a consistent approach to logging setup.


413-418: The TODOs accurately acknowledge the flag parsing concerns.

The comments correctly identify that manual flag parsing isn't ideal compared to leveraging Cobra's built-in capabilities.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 17, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
pkg/config/config.go (3)

397-398: Consider improving the TODO comment clarity.

The current TODO comment references an issue without explaining what the actual issue is. This makes it harder for future developers to understand the context without access to the issue tracking system.

-	// TODO: This is a quick patch to mitigate the issue we can look for better code later
-	// Issue: https://linear.app/cloudposse/issue/DEV-3093/create-a-cli-command-core-library
+	// TODO: This is a quick patch to handle log configuration from both environment variables and CLI flags.
+	// A more comprehensive solution will be implemented as part of the CLI command core library.
+	// Issue: https://linear.app/cloudposse/issue/DEV-3093/create-a-cli-command-core-library

421-447: Consider adding error handling to the flag parsing function.

The current implementation of parseFlags() makes certain assumptions about the format of command-line arguments, but doesn't handle potential errors or edge cases such as duplicate flags.

-func parseFlags() map[string]string {
+func parseFlags() (map[string]string, error) {
 	args := os.Args
 	flags := make(map[string]string)
 	for i := 0; i < len(args); i++ {
 		arg := args[i]
 		// Check if the argument starts with '--' (double dash)
 		if !strings.HasPrefix(arg, "--") {
 			continue
 		}
 		// Strip the '--' prefix and check if it's followed by a value
 		arg = arg[2:]
+		// Check if flag name is empty
+		if len(arg) == 0 {
+			return nil, fmt.Errorf("empty flag name found at position %d", i)
+		}
 		switch {
 		case strings.Contains(arg, "="):
 			// Case like --flag=value
 			parts := strings.SplitN(arg, "=", 2)
+			if _, exists := flags[parts[0]]; exists {
+				return nil, fmt.Errorf("duplicate flag: %s", parts[0])
+			}
 			flags[parts[0]] = parts[1]
 		case i+1 < len(args) && !strings.HasPrefix(args[i+1], "--"):
 			// Case like --flag value
+			if _, exists := flags[arg]; exists {
+				return nil, fmt.Errorf("duplicate flag: %s", arg)
+			}
 			flags[arg] = args[i+1]
 			i++ // Skip the next argument as it's the value
 		default:
 			// Case where flag has no value, e.g., --flag (we set it to "true")
+			if _, exists := flags[arg]; exists {
+				return nil, fmt.Errorf("duplicate flag: %s", arg)
+			}
 			flags[arg] = "true"
 		}
 	}
-	return flags
+	return flags, nil
 }

This would require updating the calling code in setLogConfig:

-	flagKeyValue := parseFlags()
+	flagKeyValue, err := parseFlags()
+	if err != nil {
+		u.LogWarning(fmt.Sprintf("error parsing flags: %v", err))
+		flagKeyValue = make(map[string]string)
+	}

402-405: Consider consistent error handling for flag parsing results.

Currently, the code silently accepts whatever value is provided for logs-level without validation. Consider adding validation to ensure the value is a valid log level.

 	flagKeyValue := parseFlags()
 	if v, ok := flagKeyValue["logs-level"]; ok {
+		// Validate log level before setting
+		if _, err := u.ParseLogLevel(v); err != nil {
+			u.LogWarning(fmt.Sprintf("invalid log level: %s", v))
+		} else {
 		atmosConfig.Logs.Level = v
+		}
 	}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6bddcfe and 9e70a8c.

📒 Files selected for processing (1)
  • pkg/config/config.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (3)
pkg/config/config.go (3)

390-390: Good structuring by centralizing log config setting.

The addition of this function call ensures that logging configuration happens at a consistent point in the initialization flow, after all other config sources have been processed.


414-419: Good use of TODO comments for technical debt tracking.

The comments clearly document why manual flag parsing is being used and the intention to revisit this approach in the future.


396-412:

✅ Verification successful

The log config priority logic is clear and straightforward.

The implementation properly handles environment variables and command-line flags for logging configuration, with flags taking priority over environment variables.

Let's verify if there are any calls elsewhere in the codebase that might be setting these same values:


🏁 Script executed:

#!/bin/bash
# Search for other code that might be setting log levels or files
rg -p "atmosConfig.Logs.(Level|File) ?=" --type go

Length of output: 2769


Log configuration priority verified across codebase

The log configuration function in pkg/config/config.go correctly applies environment variables followed by flag overrides. Our review of the repository shows that while several tests and utility files (such as those in pkg/workflow/workflow_test.go, pkg/vender/*, and various files under internal/exec/) reference or assign log levels for validation purposes, none of them conflict with the priority logic established in this function.

  • The tests and internal utilities typically compare against or set a default log level (e.g., u.LogLevelTrace), which verifies the expected behavior rather than interfering with the configuration ordering.
  • This consistent usage confirms that the current implementation is safe and effective.

@osterman osterman merged commit 03ac289 into main Mar 17, 2025
50 checks passed
@osterman osterman deleted the feature/dev-3074-remove-unused-flags-value-code branch March 17, 2025 21:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
patch A minor, backward compatible change size/m
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants