Skip to content

Conversation

@creativeprojects
Copy link
Owner

When scheduling a profile with missing drop-in files, an empty configuration was generated before throwing an error.

The empty files weren't deleted by the unschedule command as the service wasn't registered in systemd.

This PR fixes the issue by ignoring missing files (you get an error in the console)

@coderabbitai
Copy link

coderabbitai bot commented May 16, 2025

Walkthrough

The changes introduce file existence checks for systemd drop-in configuration files, ensuring only present files are processed. A new configuration example and an updated YAML reference are added. The JSON schema test is updated to exclude the new example file. A dedicated test verifies the new existence-checking method.

Changes

File(s) Change Summary
config/jsonschema/schema_test.go Updated exclusion regex to skip drop-in-example.conf from JSON schema validation tests.
examples/drop-in-example.conf Added a new configuration snippet setting the RESTIC_PASSWORD_FILE environment variable.
examples/linux.yaml Uncommented the systemd-drop-in-files entry to include drop-in-example.conf in the configuration.
systemd/drop_ins.go Added DropInFileExists method to the Unit type to check for drop-in file existence.
systemd/generate.go Modified logic to filter drop-in files using DropInFileExists, ensuring only existing files are processed.
systemd/drop_ins_test.go Added new tests for DropInFileExists using an in-memory filesystem with various file existence scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant Config as Config Loader
    participant Unit as systemd.Unit
    participant FS as Filesystem

    Config->>Unit: Provide DropInFiles list
    loop For each drop-in file
        Unit->>FS: Check file existence (DropInFileExists)
        alt File exists
            Unit->>Unit: Add to existingFiles
        else File does not exist
            Unit->>Unit: Skip file
        end
    end
    Unit->>Unit: Process only existingFiles for drop-in generation
Loading

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ 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
Copy link

codecov bot commented May 16, 2025

Codecov Report

Attention: Patch coverage is 84.61538% with 2 lines in your changes missing coverage. Please review.

Project coverage is 79.24%. Comparing base (88fcedb) to head (89759e3).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
systemd/drop_ins.go 77.78% 2 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master     #502   +/-   ##
=======================================
  Coverage   79.24%   79.24%           
=======================================
  Files         133      133           
  Lines       13208    13219   +11     
=======================================
+ Hits        10466    10475    +9     
- Misses       2324     2326    +2     
  Partials      418      418           
Flag Coverage Δ
unittests 79.24% <84.62%> (+<0.01%) ⬆️

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

@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: 1

🧹 Nitpick comments (1)
util/collect/collect.go (1)

51-62: New Filter function is well-implemented but needs better documentation

The implementation is efficient and correctly handles edge cases by:

  • Pre-allocating output slice capacity to avoid unnecessary reallocations
  • Properly handling nil/empty inputs
  • Using generics to work with any slice type

However, the documentation is quite minimal compared to other functions in this package.

Consider expanding the documentation to include:

  • How it handles nil/empty inputs
  • That it returns a new slice rather than modifying the input
  • An example of usage
  • The relationship with the similar All function
-// Filter a slice using a filter func (T) => (bool).
+// Filter creates a new slice containing only the elements from input that satisfy filterFunc.
+// Empty or nil input returns nil output.
+// This is similar to All but pre-allocates the output slice for better performance.
func Filter[I ~[]T, T any](input I, filterFunc func(t T) bool) (output []T) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 88fcedb and 7313cd3.

📒 Files selected for processing (7)
  • config/jsonschema/schema_test.go (1 hunks)
  • examples/drop-in-example.conf (1 hunks)
  • examples/linux.yaml (1 hunks)
  • systemd/drop_ins.go (2 hunks)
  • systemd/generate.go (1 hunks)
  • util/collect/collect.go (1 hunks)
  • util/collect/collect_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
util/collect/collect_test.go (1)
util/collect/collect.go (1)
  • Filter (52-62)
systemd/drop_ins.go (1)
systemd/generate.go (1)
  • Unit (115-118)
systemd/generate.go (1)
util/collect/collect.go (2)
  • All (7-14)
  • Not (17-20)
🪛 GitHub Check: codecov/patch
systemd/drop_ins.go

[warning] 30-35: systemd/drop_ins.go#L30-L35
Added lines #L30 - L35 were not covered by tests

🔇 Additional comments (5)
examples/drop-in-example.conf (1)

1-2: Good example of a systemd drop-in file

This is a clean and appropriate example of a systemd drop-in file. The use of the %d specifier correctly references the unit directory for the password file path.

examples/linux.yaml (1)

101-101: Correctly enables the example drop-in file

Uncommented the configuration line to enable the new example drop-in file. This provides a practical test case for the updated drop-in file handling.

config/jsonschema/schema_test.go (1)

150-150: Appropriate schema test exclusion

Correctly updated the exclusion pattern to include the new drop-in example file, preventing schema validation for a file format that doesn't need to conform to the JSON schema.

systemd/generate.go (1)

223-227: Excellent fix to prevent empty configuration files

This change effectively addresses the core issue by filtering for existing drop-in files before processing them. The use of collect.All with the FileExists predicate ensures only actual files are included, preventing empty configurations when files are missing.

The implementation is clean and focused, handling both timer and service drop-in files appropriately.

util/collect/collect_test.go (1)

60-70: Well-designed test covering all edge cases

The test is thorough and covers both the main filtering functionality and important edge cases:

  • Filtering even numbers from a sequence
  • Handling nil slices
  • Handling empty slices
  • Handling a slice where no elements match the filter

The consistent pattern with other tests in this file makes it easy to understand and maintain.

Copy link

@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)
systemd/drop_ins_test.go (3)

44-57: Consider adding test cases for edge conditions.

While the test covers the basic success and failure cases, consider adding tests for edge conditions such as permission errors or when the path is a directory instead of a file to ensure robust error handling.

tests := []struct {
	name          string
	file          string
	setupFs       func() afero.Fs
	expectedValue bool
}{
	// existing test cases...
+	{
+		name: "path is a directory",
+		file: "/path/to/dir",
+		setupFs: func() afero.Fs {
+			testFs := afero.NewMemMapFs()
+			err := testFs.Mkdir("/path/to/dir", 0755)
+			require.NoError(t, err)
+			return testFs
+		},
+		expectedValue: false,
+	},
+	{
+		name: "permission error",
+		file: "/path/to/no-permission-file",
+		setupFs: func() afero.Fs {
+			// You'd need to use a filesystem implementation that can simulate permission errors
+			// This is a simplified example
+			testFs := afero.NewMemMapFs()
+			// Setup code that would result in permission error when accessing file
+			return testFs
+		},
+		expectedValue: false,
+	},
}

53-54: Verify that errors are logged appropriately.

According to the PR objectives, an error message should be displayed in the console when drop-in files are missing. Consider extending the test to verify that appropriate logging occurs when files don't exist.

You could capture log output and verify it contains the expected error message when a file doesn't exist:

result := unit.DropInFileExists(tc.file)
assert.Equal(t, tc.expectedValue, result)
+if !tc.expectedValue {
+   // Assuming there's a way to capture and verify logs in your application
+   // This is a conceptual example; implementation would depend on your logging framework
+   assert.Contains(t, capturedLogs, "Error accessing drop-in file")
+}

1-58: Consider adding integration test for the filtering behavior.

While this unit test covers the file existence check well, consider adding an integration test that verifies the filtering behavior in the context of systemd unit generation. This would ensure that missing files are properly excluded when generating configurations.

You could add a separate test function that:

  1. Sets up a filesystem with both existing and non-existing drop-in files
  2. Calls the relevant function that uses DropInFileExists for filtering
  3. Verifies that only existing files are included in the resulting configuration

This would provide end-to-end validation of the fix described in the PR objectives.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 7313cd3 and dc15fc6.

📒 Files selected for processing (3)
  • systemd/drop_ins.go (2 hunks)
  • systemd/drop_ins_test.go (1 hunks)
  • systemd/generate.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • systemd/generate.go
  • systemd/drop_ins.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build and test (1.24, windows-latest)
🔇 Additional comments (4)
systemd/drop_ins_test.go (4)

1-2: Build constraint is appropriate for systemd tests.

The build constraint correctly excludes this test from running on non-Linux platforms (Darwin and Windows) where systemd is not available.


5-11: Good use of testing libraries.

The test uses appropriate testing libraries including afero for filesystem abstraction, which allows for testing file operations without touching the actual filesystem.


13-15: Good test setup with parallel execution enabled.

Enabling parallel test execution with t.Parallel() is a good practice for improving test efficiency.


16-42: Well-structured test cases using table-driven approach.

The table-driven approach is a good practice in Go for testing multiple scenarios. The test cases cover both when the file exists and when it doesn't exist, which aligns with the PR objective to handle missing drop-in files correctly.

Copy link

@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 (1)
systemd/drop_ins_test.go (1)

13-68: Consider adding a test for permission errors

While the current tests cover basic existence checks, consider adding a test case for permission errors that might occur when checking file existence. This would ensure the method handles permission-related issues correctly.

{
    name: "permission error",
    file: "/path/to/protected",
    setupFs: func() afero.Fs {
        // Use a filesystem implementation that can simulate permission errors
        // or mock the filesystem operations to return a permission error
        testFs := &mockFs{} // Custom mock that returns permission error
        return testFs
    },
    expectedValue: false, // Or however the function should behave with permission errors
},
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between dc15fc6 and 89759e3.

📒 Files selected for processing (1)
  • systemd/drop_ins_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build and test (1.24, windows-latest)
🔇 Additional comments (5)
systemd/drop_ins_test.go (5)

1-2: Good use of build constraints

The build constraints correctly limit this test to run only on Linux platforms, which is appropriate since systemd is specific to Linux operating systems.


5-11: Dependencies are well chosen

The imports are minimal and appropriate for the testing needs:

  • afero for filesystem abstraction
  • testify/assert and testify/require for test assertions

13-15: Good test setup with parallelisation

Using t.Parallel() is good practice for test functions as it allows tests to run concurrently, improving overall test execution time.


16-53: Comprehensive test cases structure

The table-driven test approach is well implemented with clear test case names and expected values. All three critical scenarios are covered:

  1. When the file exists
  2. When the path points to a directory
  3. When the file does not exist

This ensures the DropInFileExists method handles all common path states correctly.


55-67: Proper test execution

The test execution is well structured with:

  • Parallelisation at the subtest level
  • Clean setup of test filesystem for each case
  • Proper unit initialization
  • Clear assertion of results

The code effectively validates the DropInFileExists method's ability to correctly identify existing and non-existing files/directories.

@creativeprojects creativeprojects merged commit c3add93 into master May 16, 2025
9 checks passed
@creativeprojects creativeprojects deleted the ignore-missing-drop-ins branch May 16, 2025 22:19
@creativeprojects creativeprojects added this to the v0.31.0 milestone May 17, 2025
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.

2 participants