Skip to content
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

fix(cli-utils): Baseline - create parent directory if needed #4833

Merged
merged 1 commit into from
Nov 12, 2024

Conversation

vio
Copy link
Member

@vio vio commented Nov 12, 2024

Summary by CodeRabbit

  • New Features
    • Introduced a new test suite for the writeBaseline function to ensure its reliability.
  • Improvements
    • Enhanced the writeBaseline function to create the necessary directory structure before saving files, improving error handling.

Copy link

coderabbitai bot commented Nov 12, 2024

Walkthrough

This pull request introduces a new test suite for the writeBaseline function within the baseline module, utilizing the memfs library for in-memory file system operations. It ensures that the function can correctly save a baseline JSON file while verifying that the necessary directory structure exists before writing. The changes enhance the function's robustness by preventing errors related to non-existent directories and include mocking of file system operations during testing.

Changes

File Path Change Summary
packages/cli-utils/src/tests/baseline.test.ts Added a new test suite for writeBaseline, utilizing memfs for in-memory file operations and verifying baseline saving.
packages/cli-utils/src/baseline.ts Modified writeBaseline to ensure the target directory exists before writing the file, enhancing error handling.

Poem

In the burrow deep where the code does flow,
A new test was born, with a gentle glow.
With memfs we play, in a world so bright,
Saving baselines with all of our might.
No more worries of paths gone astray,
Our code hops forward, come what may! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

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: 2

🧹 Outside diff range and nitpick comments (2)
packages/cli-utils/src/__tests__/baseline.test.ts (1)

7-14: Consider adding more test cases with varied data structures.

While the current test data is valid, consider adding test cases that cover:

  • Empty assets array
  • Multiple assets
  • Different file types and sizes
  • Edge cases (e.g., very long file names, special characters)
const TEST_CASES = [
  {
    name: 'empty assets',
    data: { assets: [] }
  },
  {
    name: 'multiple assets',
    data: {
      assets: [
        { name: 'main.js', size: 12 * 1024 },
        { name: 'style.css', size: 5 * 1024 },
        { name: 'very-long-filename-with-special-chars!@#$.min.js', size: 1 }
      ]
    }
  }
];
packages/cli-utils/src/baseline.ts (1)

47-47: Remove unnecessary empty options object.

The empty options object passed to fs.writeFile doesn't serve any purpose and can be removed for better code clarity.

-  return fs.writeFile(baselineFilepath, JSON.stringify(data), {});
+  return fs.writeFile(baselineFilepath, JSON.stringify(data));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d8bd840 and b564138.

📒 Files selected for processing (2)
  • packages/cli-utils/src/__tests__/baseline.test.ts (1 hunks)
  • packages/cli-utils/src/baseline.ts (1 hunks)
🔇 Additional comments (4)
packages/cli-utils/src/__tests__/baseline.test.ts (3)

1-5: LGTM! Good test setup with virtual file system.

The use of memfs for testing file operations and mocking of fs/promises is appropriate and follows testing best practices.


16-19: LGTM! Good test isolation.

Resetting the virtual file system before each test ensures proper test isolation.


3-3: Verify the implementation of writeBaseline function.

Let's ensure the actual implementation in baseline.ts handles directory creation correctly.

✅ Verification successful

writeBaseline implementation verified to handle directory creation correctly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the implementation exists and handles directory creation
ast-grep --pattern 'export async function writeBaseline($_, $_) {
  $$$
  mkdir($$$)
  $$$
}'

# Look for related tests or implementations
rg -l "writeBaseline" --type ts

Length of output: 236


Script:

#!/bin/bash
# Extract the implementation of writeBaseline function
ast-grep --pattern 'export async function writeBaseline($_, $_) { $$$ }' packages/cli-utils/src/baseline.ts

# Check for directory creation within the writeBaseline function
rg "mkdir" packages/cli-utils/src/baseline.ts

Length of output: 226

packages/cli-utils/src/baseline.ts (1)

46-46: LGTM! Good practice to ensure directory exists.

Creating the parent directory recursively before writing the file is a robust approach that prevents potential ENOENT errors.

Comment on lines +21 to +23
test('should save baseline', async () => {
const baselineFilepath = 'new-baseline-dir/baseline.json';
await writeBaseline(SOURCE_CURRENT as any, baselineFilepath);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove type assertion and add proper typing.

The as any type assertion should be avoided. Instead, define proper types for the baseline data structure.

interface Asset {
  name: string;
  size: number;
}

interface BaselineData {
  assets: Asset[];
}

const SOURCE_CURRENT: BaselineData = {
  // ... existing data
};

await writeBaseline(SOURCE_CURRENT, baselineFilepath);

Comment on lines +21 to +27
test('should save baseline', async () => {
const baselineFilepath = 'new-baseline-dir/baseline.json';
await writeBaseline(SOURCE_CURRENT as any, baselineFilepath);

const baselineFile = await vol.promises.readFile(baselineFilepath);
expect(JSON.parse(baselineFile.toString())).toEqual(SOURCE_CURRENT);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add more test cases to verify PR objectives and error handling.

The test suite is missing critical test cases:

  1. Verify that parent directories are created (main PR objective)
  2. Test error handling scenarios
  3. Validate directory existence after write

Add these test cases:

test('should create parent directory if it doesn\'t exist', async () => {
  const deepPath = 'deep/nested/directory/baseline.json';
  await writeBaseline(SOURCE_CURRENT, deepPath);
  
  const dirExists = await vol.promises.stat('deep/nested/directory');
  expect(dirExists.isDirectory()).toBe(true);
});

test('should handle file system errors gracefully', async () => {
  // Mock a file system error
  vol.promises.mkdir = jest.fn().mockRejectedValue(new Error('Mock FS error'));
  
  await expect(
    writeBaseline(SOURCE_CURRENT, 'error/baseline.json')
  ).rejects.toThrow('Mock FS error');
});

Copy link

relativeci bot commented Nov 12, 2024

#11663 Bundle Size — 381.32KiB (0%).

b564138(current) vs 624e4fa master#11661(baseline)

Warning

Bundle contains 2 duplicate packages – View duplicate packages

Bundle metrics  no changes
                 Current
#11663
     Baseline
#11661
No change  Initial JS 334.44KiB 334.44KiB
No change  Initial CSS 46.89KiB 46.89KiB
No change  Cache Invalidation 0% 0%
No change  Chunks 3 3
No change  Assets 4 4
No change  Modules 699 699
No change  Duplicate Modules 0 0
No change  Duplicate Code 0% 0%
No change  Packages 39 39
No change  Duplicate Packages 1 1
Bundle size by type  no changes
                 Current
#11663
     Baseline
#11661
No change  JS 334.44KiB 334.44KiB
No change  CSS 46.89KiB 46.89KiB

Bundle analysis reportBranch fix-cli-baseline-outputProject dashboard


Generated by RelativeCIDocumentationReport issue

@vio vio merged commit 624676d into master Nov 12, 2024
28 checks passed
@vio vio deleted the fix-cli-baseline-output branch November 12, 2024 17:58
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.

1 participant