Skip to content

feat: hybrid config yaml and env - #22

Merged
ren0503 merged 3 commits into
masterfrom
feat/ren/21-hybrid-config
Jul 20, 2025
Merged

feat: hybrid config yaml and env#22
ren0503 merged 3 commits into
masterfrom
feat/ren/21-hybrid-config

Conversation

@ren0503

@ren0503 ren0503 commented Jul 20, 2025

Copy link
Copy Markdown
Contributor

No description provided.

@ren0503 ren0503 added this to the Config Release v2.1.0 milestone Jul 20, 2025
@coderabbitai

coderabbitai Bot commented Jul 20, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added new Makefile targets for auditing dependencies, code formatting, linting, tidying modules, running tests, and benchmarking.
    • Introduced a test to verify configuration merging from both YAML and environment files.
  • Improvements

    • Updated a core dependency to a newer version.
    • Enhanced environment configuration handling to support merging multiple sources.
  • Chores

    • Removed the deprecated test-coverage Makefile target.

Walkthrough

The Makefile was expanded with new phony targets for auditing, formatting, linting, tidying, testing, and benchmarking, while the test-coverage target was removed. The go.mod dependency for github.com/tinh-tinh/tinhtinh/v2 was updated. The ForRoot function in module.go now merges multiple configuration sources. A new hybrid configuration test was added.

Changes

File(s) Change Summary
Makefile Added phony targets: audit, format, lint, tidy, test, benchmark; removed test-coverage; reorganized.
go.mod Updated github.com/tinh-tinh/tinhtinh/v2 from v2.0.2 to v2.3.0.
module.go Modified ForRoot to merge multiple environment configs instead of overwriting with last one.
module_test.go Added Test_Hybrid to test loading configuration from both YAML and env files.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test_Hybrid
    participant Core as core.NewModule
    participant Config as config.ForRoot
    participant Module as Module
    Test->>Core: NewModule(config.ForRoot(env.yaml, .env.example))
    Core->>Config: ForRoot(env.yaml, .env.example)
    Config->>Config: Parse YAML and env files into structs
    Config->>Config: Merge structs into one config
    Config-->>Core: Return merged config
    Core-->>Module: Create module with config
    Test->>Module: Get config reference
    Module-->>Test: Return *HybridEnv
Loading

Poem

🐰
New targets in the Makefile hop,
Lint and format—never stop!
Configs now combine with glee,
Hybrid tests for all to see.
Dependencies get a shiny new coat,
Rabbits cheer and take a note!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 36fa816 and beb2432.

📒 Files selected for processing (1)
  • module_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • module_test.go
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov

codecov Bot commented Jul 20, 2025

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
module.go (1)

36-57: Approve the hybrid configuration implementation with suggestions for improvement.

The implementation correctly accumulates multiple configurations and merges them using common.MergeStruct. This enables loading from multiple sources (YAML + env files) as intended.

However, consider these improvements:

 		} else {
 			var envArrs []E
+			// Pre-allocate slice capacity to avoid repeated allocations
+			envArrs = make([]E, 0, len(params))
 			for _, v := range params {
 				if reflect.TypeOf(v).Kind() == reflect.String {
 					val, err := New[E](any(v).(string))
 					if err != nil {
+						log.Printf("Failed to load config from %v: %v", v, err)
 						continue
 					}
 					envArrs = append(envArrs, *val)
 				} else if reflect.TypeOf(v).Kind() == reflect.Struct {
 					opt := any(v).(Options[E])
 					err = godotenv.Load(opt.EnvPath)
 					if err != nil {
+						log.Printf("Failed to load env file %s: %v", opt.EnvPath, err)
 						continue
 					}
 					val := opt.Load()
+					if val == nil {
+						log.Printf("Load function returned nil for %s", opt.EnvPath)
+						continue
+					}
 					envArrs = append(envArrs, *val)
 				}
 			}
 			if len(envArrs) > 0 {
 				value := common.MergeStruct(envArrs...)
 				lastValue = &value
 			}

Improvements suggested:

  1. Performance: Pre-allocate slice capacity to avoid repeated allocations
  2. Debugging: Add detailed error logging to help troubleshoot configuration loading issues
  3. Safety: Add nil check for the Load() function result to prevent potential panics
Makefile (1)

1-32: Excellent Makefile enhancements for development workflow.

The new targets provide a comprehensive development toolkit with auditing, formatting, linting, testing, and benchmarking capabilities. All targets are properly declared as phony and use appropriate tools.

Consider adding the missing standard targets suggested by static analysis:

+.PHONY: all
+all: tidy format lint audit test
+
+.PHONY: clean
+clean:
+	go clean -cache -testcache -modcache
+	rm -rf coverage/
+
 .PHONY: audit

Benefits of suggested additions:

  1. all target: Provides a single command to run the complete development pipeline
  2. clean target: Helps reset the development environment by clearing caches and generated files
  3. Standard compliance: Follows common Makefile conventions expected by developers
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e6de565 and 6474700.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (4)
  • Makefile (1 hunks)
  • go.mod (1 hunks)
  • module.go (2 hunks)
  • module_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
module_test.go (1)
module.go (2)
  • ForRoot (25-75)
  • ENV (12-12)
module.go (1)
config.go (1)
  • New (9-22)
🪛 checkmake (0.2.2)
Makefile

[warning] 29-29: Missing required phony target "all"

(minphony)


[warning] 29-29: Missing required phony target "clean"

(minphony)

🔇 Additional comments (3)
go.mod (1)

8-8: Dependency update verified – no issues found

  • Release notes for v2.1.2–v2.3.0 add only new features (including MergeStruct in v2.1.2) and bug fixes, with no breaking changes documented.
  • GitHub security advisories report no vulnerabilities affecting versions ≤ v2.3.0.

No further action required.

module.go (1)

8-8: LGTM! Import added for hybrid configuration support.

The new import enables the common.MergeStruct functionality needed for merging multiple configuration sources.

module_test.go (1)

4-4: LGTM! Import added for test output.

The fmt import supports the test output in the new hybrid configuration test.

Comment thread module_test.go
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
module_test.go (1)

92-118: Excellent implementation of the hybrid configuration test!

This test effectively addresses all the concerns from the previous review:

  • ✅ Comprehensive assertions validate merged configuration values
  • ✅ Clear comments indicate source of each value
  • ✅ Proper use of t.Logf for test output
  • ✅ Robust validation of the merged result

The test demonstrates proper hybrid configuration loading from multiple sources (YAML and env files).

Consider adding a small enhancement for robustness:

	require.Equal(t, "development", cfg.NodeEnv) // From YAML file
	require.Equal(t, 3000, cfg.Port)            // From YAML file  
	require.True(t, cfg.Log)                    // From YAML file
-	require.NotEmpty(t, cfg.Special)            // From env file (if SPECIAL is set)
+	// Check if SPECIAL env var is set, otherwise verify it's handled gracefully
+	if os.Getenv("SPECIAL") != "" {
+		require.NotEmpty(t, cfg.Special)        // From env file
+	} else {
+		t.Logf("SPECIAL env var not set, got: %q", cfg.Special)
+	}

This ensures the test handles cases where the SPECIAL environment variable might not be set in the test environment.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6474700 and 36fa816.

📒 Files selected for processing (1)
  • module_test.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: build (1.22.x)
module_test.go

[failure] 4-4:
"fmt" imported and not used

🪛 GitHub Actions: Go
module_test.go

[error] 4-4: Go test error: "fmt" imported and not used.

Comment thread module_test.go Outdated
@ren0503 ren0503 linked an issue Jul 20, 2025 that may be closed by this pull request
@ren0503
ren0503 merged commit 607d9ba into master Jul 20, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support Hybrid Config Env and Yaml

1 participant