-
-
Notifications
You must be signed in to change notification settings - Fork 643
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
feat: add tests for build post list script #3284
base: master
Are you sure you want to change the base?
Conversation
✅ Deploy Preview for asyncapi-website ready!Built without sensitive environment variables
To edit notification comments on pull requests, go to your Netlify site configuration. |
WalkthroughThe pull request introduces significant modifications to the Changes
Possibly related PRs
Suggested labels
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
⚡️ Lighthouse report for the changes in this PR:
Lighthouse ran on https://deploy-preview-3284--asyncapi-website.netlify.app/ |
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## master #3284 +/- ##
===========================================
+ Coverage 49.14% 61.86% +12.71%
===========================================
Files 21 21
Lines 647 653 +6
===========================================
+ Hits 318 404 +86
+ Misses 329 249 -80 ☔ View full report in Codecov by Sentry. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Outside diff range and nitpick comments (9)
scripts/index.js (3)
11-15
: LGTM! Consider extractingpostDirectories
for improved maintainability.The new
postDirectories
array provides a clear and flexible way to define the directories to be processed bybuildPostList
. This change enhances the configurability of the script.For improved maintainability, consider extracting this array to a separate configuration file. This would allow easier updates to the directory list without modifying the main script. For example:
const { postDirectories } = require('../config/build-config.js');
16-17
: LGTM! Consider usingresolve
forbasePath
as well.The introduction of
basePath
andwriteFilePath
variables improves the flexibility of the script by allowing easy configuration of input and output paths.For consistency, consider using
resolve
forbasePath
as well:const basePath = resolve(__dirname, '..', 'pages');This ensures that the path is always resolved correctly, regardless of the current working directory.
19-19
: LGTM! Consider adding error handling.The updated
buildPostList
function call correctly uses the new parameters, providing more flexibility in the post list building process.Consider adding error handling to manage potential failures in the
buildPostList
function:try { await buildPostList(postDirectories, basePath, writeFilePath); } catch (error) { console.error('Error building post list:', error); // Optionally, you might want to throw the error or handle it in a way that's appropriate for your application }This will help in identifying and debugging any issues that may occur during the post list building process.
tests/build-post-list.test.js (5)
37-53
: LGTM with suggestion: Consider enhancing assertion specificityThe test case effectively verifies the basic functionality of buildPostList. It checks for the existence of the output file and the presence of expected properties in the output.
To further improve the test, consider adding more specific assertions about the content of the output. For example, you could check for the exact number of entries in each category or verify specific fields of the blog entry beyond just the title.
55-82
: LGTM with suggestion: Enhance negative test casesThese test cases effectively cover important scenarios: handling directories with only section files and processing multiple release notes. The assertions verify the presence of expected entries in the output.
To make these tests more robust, consider adding negative assertions. For example, in the "handles multiple release notes correctly" test, you could also verify that no unexpected release notes are present in the output.
84-101
: LGTM with suggestions: Enhance error handling test and expand slugifyToC testsThe error handling test and slugifyToC tests are good additions to the test suite. However, there are opportunities for improvement:
For the error handling test, consider asserting on the specific type of error thrown, not just that an error is thrown.
The slugifyToC tests cover various input scenarios well. Consider adding a test case for a regular heading without an ID to ensure the function behaves correctly in this common scenario.
Example:
it('handles regular headings without ids', () => { const input = '## My Regular Heading'; expect(slugifyToC(input)).toBe('my-regular-heading'); });
148-189
: LGTM with suggestion: Enhance error message assertionsThese additional error handling tests are valuable additions to the test suite, covering important scenarios such as unreadable directories, unparseable front matter, and the case where no post directories are provided.
To further improve these tests, consider making the error message assertions more specific. Instead of just checking for a partial match with "Error while building post list", you could assert on more detailed error messages that provide information about the specific error condition. This would ensure that the function is not only throwing errors but also providing helpful error messages for debugging.
Example:
expect(error.message).toMatch(/Error while building post list: Unable to read directory/);
1-191
: Great job on the comprehensive test suite!This test suite for the buildPostList and slugifyToC functions is well-structured and covers a wide range of scenarios, including both happy paths and error cases. The use of beforeEach and afterEach hooks for setup and teardown is commendable.
To further enhance the test suite, consider adding the following:
- Performance test: Add a test case with a large number of files to ensure the function performs well under load.
- Edge case: Test with very long file names or paths to ensure there are no issues with path length limits.
- Internationalization: If relevant, add tests with non-ASCII characters in file names and content to ensure proper handling of international content.
These additions would make an already strong test suite even more robust.
scripts/build-post-list.js (1)
39-40
: Remove commented out codeThere is a commented-out
console.log
statement at line 39. If it's no longer needed, consider removing it to keep the code clean.Apply this diff to remove the commented code:
- // console.log(inspect(result, { depth: null, colors: true }))
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
- scripts/build-post-list.js (6 hunks)
- scripts/index.js (1 hunks)
- tests/build-post-list.test.js (1 hunks)
- tests/index.test.js (1 hunks)
🧰 Additional context used
🔇 Additional comments (8)
tests/index.test.js (2)
Line range hint
1-35
: LGTM! The changes are consistent throughout the file.The updated import statement for
buildPostList
is the only change in this file, and it's correctly reflected in the rest of the code. The test cases and mocks usebuildPostList
directly, which is consistent with the new named import. The overall structure and functionality of the tests remain intact.
2-2
: LGTM! Verify the corresponding export in the source file.The change from default import to named import is a good practice and improves code clarity. This change suggests that
buildPostList
is now exported as a named export in thebuild-post-list.js
file.To ensure consistency, please verify that the export in
scripts/build-post-list.js
matches this import style. You can run the following script to check:✅ Verification successful
Export Style Verified
The
scripts/build-post-list.js
file correctly exportsbuildPostList
as a named export:module.exports = {slugifyToC, buildPostList}🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the export style of buildPostList in the source file # Test: Search for the export of buildPostList. Expect: Named export rg --type javascript 'exports?.buildPostList|module\.exports.*buildPostList' scripts/build-post-list.jsLength of output: 140
Script:
#!/bin/bash # Description: Verify the export style of buildPostList in the source file without specifying file type # Test: Search for the export of buildPostList. Expect: Named export rg 'exports?.buildPostList|module\.exports.*buildPostList' scripts/build-post-list.jsLength of output: 132
scripts/index.js (2)
4-19
: Summary: Good refactoring, ensure consistency across the codebase.The changes to
scripts/index.js
significantly improve the flexibility and configurability of the post list building process. The introduction ofpostDirectories
,basePath
, andwriteFilePath
variables, along with the updatedbuildPostList
function call, allow for easier maintenance and future extensions.To ensure consistency across the codebase:
- Verify that all files importing
buildPostList
have been updated to use the new named import syntax.- Check if there are any other scripts or components that might be affected by these changes and update them accordingly.
- Update any documentation or comments related to the post list building process to reflect these new configurations.
Run the following script to identify potential areas that might need updates:
#!/bin/bash # Description: Identify potential areas affected by the changes # Test 1: Find all files that import from build-post-list.js echo "Files importing from build-post-list.js:" rg --type js "from ['\"].*build-post-list['\"]" # Test 2: Find all files that mention buildPostList echo "Files mentioning buildPostList:" rg --type js "buildPostList" # Test 3: Check for any hardcoded paths related to blog, docs, or about pages echo "Files with hardcoded paths:" rg --type js "pages/(blog|docs|about)"Review the output of this script to ensure all affected areas are properly updated.
4-4
: Verify the export change inbuild-post-list.js
and update other imports.The import statement for
buildPostList
has been changed from a default import to a named import. This suggests a corresponding change in thebuild-post-list.js
file.Please run the following script to verify the export in
build-post-list.js
and check for any other import statements in the codebase that might need updating:Ensure that all occurrences are updated to use the new named import syntax.
✅ Verification successful
Export and Imports Verified Successfully.
The
build-post-list.js
file correctly exportsbuildPostList
as a named export, and all import statements in the codebase, includingscripts/index.js
, have been appropriately updated. No further issues were detected.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the export in build-post-list.js and check for other imports # Test 1: Check the export in build-post-list.js echo "Checking export in build-post-list.js:" rg --type js "export.*buildPostList" scripts/build-post-list.js # Test 2: Check for other import statements in the codebase echo "Checking for other import statements:" rg --type js "import.*buildPostList.*from ['\"]./build-post-list['\"]" --glob '!scripts/index.js'Length of output: 2201
tests/build-post-list.test.js (2)
1-35
: LGTM: Well-structured test setupThe import statements and describe block setup are well-organized. The use of beforeEach and afterEach hooks to create and clean up a temporary directory structure ensures isolated and repeatable tests. This approach follows testing best practices.
103-146
: LGTM: Comprehensive coverage of specification file handlingThese tests effectively verify that the buildPostList function correctly handles various types of specification files that should not be processed. The tests cover files without a title, files with "next-spec" in the filename, and files with "explorer" in the filename. The consistent approach across these tests and the verification of the absence of these entries in the output demonstrate thorough testing of this functionality.
scripts/build-post-list.js (2)
163-163
: Ensure imports are updated after exportingbuildPostList
Now that
buildPostList
is exported, make sure all modules that import it are updated accordingly.Run the following script to find all import statements of
build-post-list
:#!/bin/bash # Description: Find all import statements of `build-post-list`. # Expectation: Imports should destructure `buildPostList` from the module. rg --type js "require\(.+build-post-list.+\)" -A 2
29-43
: Ensure all calls tobuildPostList
are updatedThe
buildPostList
function now acceptspostDirectories
,basePath
, andwriteFilePath
as parameters. Ensure that all places wherebuildPostList
is called have been updated to use the new signature.Run the following script to find all calls to
buildPostList
and verify their parameters:✅ Verification successful
All calls to
buildPostList
have been updated to use the new signature with three arguments.
tests/build-post-list.test.js
scripts/index.js
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Find all calls to `buildPostList` in the codebase. # Expectation: Calls should use the new signature with three arguments. rg --type js "buildPostList\(" -A 2Length of output: 714
Script:
#!/bin/bash # Description: Find all direct calls to `buildPostList` in the JavaScript codebase. # Improved search pattern to capture function calls with varying whitespace and argument structures. rg --type js "\bbuildPostList\s*\(" -A 2Length of output: 2505
scripts/build-post-list.js
Outdated
if (details.slug.startsWith('/docs')) | ||
result["docs"].push(details) | ||
else if(details.slug.startsWith('/blog')) | ||
else if (details.slug.startsWith('/blog')) | ||
result["blog"].push(details) | ||
else if(details.slug.startsWith('/about')) | ||
else if (details.slug.startsWith('/about')) | ||
result["about"].push(details) | ||
else {} | ||
else { } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove unnecessary empty else
block in addItem
function
The empty else { }
block at line 26 serves no purpose and can be removed to clean up the code.
Apply this diff to remove the empty block:
else if (details.slug.startsWith('/about'))
result["about"].push(details)
- else { }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (details.slug.startsWith('/docs')) | |
result["docs"].push(details) | |
else if(details.slug.startsWith('/blog')) | |
else if (details.slug.startsWith('/blog')) | |
result["blog"].push(details) | |
else if(details.slug.startsWith('/about')) | |
else if (details.slug.startsWith('/about')) | |
result["about"].push(details) | |
else {} | |
else { } | |
if (details.slug.startsWith('/docs')) | |
result["docs"].push(details) | |
else if (details.slug.startsWith('/blog')) | |
result["blog"].push(details) | |
else if (details.slug.startsWith('/about')) | |
result["about"].push(details) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vishvamsinh28 You can apply this suggestion.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
} catch (error) { | ||
throw new Error(`Error while building post list: ${error.message}`); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preserve original error stack trace when rethrowing errors
When rethrowing an error in the catch block, consider using throw error
to preserve the original stack trace, or use the cause
property to retain the error's context.
Apply this diff to preserve the original error:
} catch (error) {
- throw new Error(`Error while building post list: ${error.message}`);
+ throw error;
}
Alternatively, to add context while preserving the original error:
} catch (error) {
+ throw new Error('Error while building post list', { cause: error });
}
Note: The cause
option is available in Node.js v16.9.0 and newer.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
} catch (error) { | |
throw new Error(`Error while building post list: ${error.message}`); | |
} catch (error) { | |
throw error; | |
} | |
``` | |
Option 2: Add context while preserving the original error | |
```suggestion | |
} catch (error) { | |
throw new Error('Error while building post list', { cause: error }); | |
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Kindly apply this suggestion.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@akshatnema, thank you for your response. I'm unable to directly apply the suggested changes, but please consider incorporating them to preserve the original error stack trace.
const fileName_without_extension = file.slice(0, -4) | ||
// removes the file extension. For example, release-notes-2.1.0.md -> release-notes-2.1.0 | ||
const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-")+1) | ||
const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-") + 1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use path
module functions to handle file extensions safely
Instead of manually slicing the file name to remove the extension, use path.basename
and path.extname
for safer and more reliable handling of file names and extensions.
Apply this diff:
- const fileName_without_extension = file.slice(0, -4)
+ const fileNameWithoutExtension = basename(file, extname(file))
Don't forget to import the required functions at the top of the file:
const { resolve, basename } = require('path')
+ const { extname } = require('path')
Update subsequent code to use fileNameWithoutExtension
.
Committable suggestion was skipped due to low confidence.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vishvamsinh28 Can you please test if these changes are really working? It would be nice to refactor this with utility function of path module.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
if (details.slug.includes('/reference/specification/') && !details.title) { | ||
const fileBaseName = basename(data.slug) // ex. v2.0.0 | v2.1.0-next-spec.1 | ||
const fileName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0 | ||
details.weight = specWeight-- | ||
|
||
if (fileName.startsWith('v')) { | ||
details.title = capitalize(fileName.slice(1)) | ||
details.title = capitalize(fileName.slice(1)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid reusing variable names to prevent confusion
The variable fileName
is redefined within this block, which may cause confusion with the outer fileName
. Consider renaming the inner fileName
variable to avoid shadowing.
Apply this diff to rename the inner fileName
to versionName
:
const fileBaseName = basename(data.slug) // ex. v2.0.0 | v2.1.0-next-spec.1
- const fileName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0
+ const versionName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0
details.weight = specWeight--
- if (fileName.startsWith('v')) {
- details.title = capitalize(fileName.slice(1))
+ if (versionName.startsWith('v')) {
+ details.title = capitalize(versionName.slice(1))
} else {
- details.title = capitalize(fileName)
+ details.title = capitalize(versionName)
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (details.slug.includes('/reference/specification/') && !details.title) { | |
const fileBaseName = basename(data.slug) // ex. v2.0.0 | v2.1.0-next-spec.1 | |
const fileName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0 | |
details.weight = specWeight-- | |
if (fileName.startsWith('v')) { | |
details.title = capitalize(fileName.slice(1)) | |
details.title = capitalize(fileName.slice(1)) | |
if (details.slug.includes('/reference/specification/') && !details.title) { | |
const fileBaseName = basename(data.slug) // ex. v2.0.0 | v2.1.0-next-spec.1 | |
const versionName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0 | |
details.weight = specWeight-- | |
if (versionName.startsWith('v')) { | |
details.title = capitalize(versionName.slice(1)) | |
} else { | |
details.title = capitalize(versionName) | |
} |
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (3)
tests/build-post-list.test.js (3)
37-53
: Consider adding more specific assertionsWhile this test case covers the basic functionality of
buildPostList
, it could be enhanced by adding more specific assertions about the content of the output. For example, you could check for the exact number of entries in each category (docs, blog, about) and verify the structure of individual entries.Here's an example of how you could add more specific assertions:
expect(output.docs).toHaveLength(1); expect(output.blog).toHaveLength(1); expect(output.about).toHaveLength(1); const docEntry = output.docs[0]; expect(docEntry).toHaveProperty('title', 'Docs Home'); expect(docEntry).toHaveProperty('slug', '/docs'); expect(docEntry).toHaveProperty('excerpt');
84-101
: Enhance error handling test and add a case for slugifyToCThe error handling test is good, but it could be more specific:
For the error handling test, consider asserting the specific type of error thrown:
await expect(buildPostList([invalidDir], tempDir, writeFilePath)).rejects.toThrow(Error);Add a test case for slugifyToC with a regular heading without an ID:
it('handles regular headings without ids', () => { const input = '## My Regular Heading'; expect(slugifyToC(input)).toBe('my-regular-heading'); });These additions will improve the test coverage and make the error handling more robust.
148-187
: Enhance error handling testsWhile these additional error handling tests cover important scenarios, they could be improved for more precise error checking:
Instead of catching the error and checking its message, use
expect().rejects.toThrow()
for asynchronous functions:it('throws an error if the directory cannot be read', async () => { const invalidDir = [join(tempDir, 'non-existent-dir'), '/invalid']; await expect(buildPostList([invalidDir], tempDir, writeFilePath)) .rejects.toThrow(/Error while building post list/); });Apply the same pattern to the other two error tests.
Consider adding more specific error message checks if the
buildPostList
function throws different error messages for different scenarios.These changes will make the tests more robust and easier to maintain.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- tests/build-post-list.test.js (1 hunks)
🧰 Additional context used
🔇 Additional comments (4)
tests/build-post-list.test.js (4)
1-35
: LGTM: Well-structured test setupThe import statements and describe block setup are well-organized. The use of beforeEach and afterEach hooks ensures a clean test environment for each test case, which is a good practice for maintaining test isolation.
55-82
: LGTM: Good coverage of edge casesThese test cases effectively cover important scenarios:
- Handling directories with only section files.
- Processing multiple release notes correctly.
The tests are well-structured and include specific assertions to verify the correct behavior of the
buildPostList
function in these scenarios.
103-146
: LGTM: Comprehensive tests for specification file filteringThese test cases effectively cover the filtering of specification files:
- Files without a title
- Files with "next-spec" in the filename
- Files with "explorer" in the filename
The tests are well-structured and include appropriate assertions to verify that these files are not processed by the
buildPostList
function. This ensures that only the intended files are included in the final output.
1-189
: Overall: Well-structured and comprehensive test suiteThis test file provides a thorough and well-organized suite of tests for the
buildPostList
andslugifyToC
functions. Key strengths include:
- Comprehensive coverage of happy paths, edge cases, and error scenarios.
- Consistent structure throughout the file.
- Good use of beforeEach and afterEach hooks for test isolation.
- Effective testing of file filtering logic.
While there are some minor suggestions for improvements (as noted in previous comments), the overall quality of the test suite is high. It should provide robust validation of the functions' behavior and help catch potential regressions in future development.
Tests are passing on Ubuntu but failing on Windows. I will keep it as a draft until I find a solution for it. |
98f835b
to
ecf927e
Compare
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (2)
scripts/build-post-list.js (2)
29-43
: Improved flexibility and error handling inbuildPostList
The changes to the
buildPostList
function are well-implemented:
- The function now accepts parameters, enhancing its configurability and reusability.
- Error handling for empty
postDirectories
has been added, which is a good practice.- The use of a
writeFilePath
parameter allows for more flexible output options.These changes align well with the PR objectives of adding tests, as they make the function more testable.
However, the error handling in the catch block could be improved to preserve the original error stack trace.
Consider updating the error handling to preserve the original stack trace:
} catch (error) { - throw new Error(`Error while building post list: ${error.message}`); + throw new Error('Error while building post list', { cause: error }); }This change will provide more context for debugging while preserving the original error information.
125-128
: Improve variable naming consistency in release notes handlingWhile the logic for extracting version information from release notes file names has been updated, the variable naming could be improved for consistency and clarity.
Consider updating the variable names to follow the camelCase convention used elsewhere in the code:
- const fileName_without_extension = file.slice(0, -4) + const fileNameWithoutExtension = file.slice(0, -4)This change will improve code consistency and readability.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
- scripts/build-post-list.js (7 hunks)
- tests/build-post-list.test.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/build-post-list.test.js
🧰 Additional context used
🔇 Additional comments (6)
scripts/build-post-list.js (6)
2-2
: Improved cross-platform compatibilityThe addition of
join
andsep
from thepath
module enhances the code's ability to handle file paths consistently across different operating systems. This is a positive change that aligns with best practices for cross-platform Node.js applications.
47-47
: Improved consistency inwalkDirectories
functionThe addition of
basePath
to thewalkDirectories
function signature and its recursive call ensures consistent handling of the base path throughout the directory traversal process. This change enhances the function's flexibility and aligns well with the modifications made tobuildPostList
.Also applies to: 83-83
55-57
: Enhanced cross-platform compatibility in file path handlingThe updates to file path handling using
join
andsep
, as well as the platform-independent index file check, significantly improve the code's cross-platform compatibility. These changes ensure consistent behavior across different operating systems and align with Node.js best practices for file system operations.Also applies to: 98-98
57-57
: Improved slug generation for cross-platform consistencyThe update to slug generation now uses the
basePath
parameter and normalizes separators to forward slashes. This change ensures consistent slug generation across different platforms, further enhancing the code's cross-platform compatibility.
162-163
: Improved module API with updated exportsThe module exports have been updated to include both
slugifyToC
andbuildPostList
functions. This change enhances the module's API by making both functions available for external use, which aligns well with the PR objectives of adding tests for thebuild-post-list.js
script. This modification will facilitate easier testing and potential reuse of these functions in other parts of the project.
Line range hint
1-163
: Overall assessment of changes tobuild-post-list.js
The modifications to this file are well-implemented and align closely with the PR objectives of adding tests for the
build-post-list.js
script. Key improvements include:
- Enhanced cross-platform compatibility through better file path handling.
- Improved function flexibility with parameterized inputs.
- Better error handling, particularly in the
buildPostList
function.- Updated module exports for easier testing and potential reuse.
These changes contribute positively to the codebase by improving testability, maintainability, and cross-platform consistency. The script is now better equipped to handle various input scenarios, which should facilitate more comprehensive testing.
There are a few minor suggestions for improvement, such as preserving the original error stack trace and maintaining consistent variable naming conventions. Addressing these points will further enhance the overall quality of the code.
da6c058
to
fe9c3da
Compare
There was a problem hiding this 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 (1)
tests/build-post-list.test.js (1)
62-64
: Remove unnecessaryconsole.log
statements in testsThe
console.log
statements at lines 62, 64, and 72 are unnecessary and can clutter the test output. Consider removing them to keep the test output clean.Apply this diff to remove the
console.log
statements:- console.log("output before ", output); - console.log("output after ", output); - console.log("blog entry ", blogEntry);Also applies to: 72-72
it('throws an error if the directory cannot be read', async () => { | ||
const invalidDir = [join(tempDir, 'non-existent-dir'), '/invalid']; | ||
|
||
let error; | ||
try { | ||
await buildPostList([invalidDir], tempDir, writeFilePath); | ||
} catch (err) { | ||
error = err; | ||
} | ||
|
||
expect(error).toBeDefined(); | ||
expect(error.message).toMatch(/Error while building post list/); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Duplicate test cases for invalid directory error handling
The test case at lines 175-187 duplicates the earlier test at lines 108-111, both checking the handling of invalid directories. Consider consolidating these tests to avoid redundancy.
Apply this diff to remove the duplicate test:
- it('throws an error if the directory cannot be read', async () => {
- const invalidDir = [join(tempDir, 'non-existent-dir'), '/invalid'];
-
- let error;
- try {
- await buildPostList([invalidDir], tempDir, writeFilePath);
- } catch (err) {
- error = err;
- }
-
- expect(error).toBeDefined();
- expect(error.message).toMatch(/Error while building post list/);
- });
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('throws an error if the directory cannot be read', async () => { | |
const invalidDir = [join(tempDir, 'non-existent-dir'), '/invalid']; | |
let error; | |
try { | |
await buildPostList([invalidDir], tempDir, writeFilePath); | |
} catch (err) { | |
error = err; | |
} | |
expect(error).toBeDefined(); | |
expect(error.message).toMatch(/Error while building post list/); | |
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vishvamsinh28 You've added a similar test above in this file. Please check.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
tests/build-post-list.test.js
Outdated
const normalizeItem = (item) => { | ||
if (item.id) { | ||
item.id = normalizePath(item.id); | ||
} | ||
return item; | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Avoid mutating function arguments in normalizeItem
Modifying the item
parameter directly in the normalizeItem
function can lead to unintended side effects. Instead, return a new object with the updated id
property.
Apply this diff to refactor the normalizeItem
function:
const normalizeItem = (item) => {
- if (item.id) {
- item.id = normalizePath(item.id);
- }
- return item;
+ return {
+ ...item,
+ id: item.id ? normalizePath(item.id) : item.id,
+ };
};
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const normalizeItem = (item) => { | |
if (item.id) { | |
item.id = normalizePath(item.id); | |
} | |
return item; | |
}; | |
const normalizeItem = (item) => { | |
return { | |
...item, | |
id: item.id ? normalizePath(item.id) : item.id, | |
}; | |
}; |
0b9b50e
to
7ae14bd
Compare
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (4)
tests/index.test.js (1)
Line range hint
16-33
: Consider updating the test forbuildPostList
.The test suite currently only checks if
buildPostList
is called, but doesn't verify its parameters. SincebuildPostList
now accepts three parameters (postDirectories
,basePath
, andwriteFilePath
), consider updating the test to ensure it's called with the correct arguments.Here's a suggested update to the test:
test('should call all functions in the correct order', async () => { await start(); expect(buildPostList).toHaveBeenCalledWith( expect.any(Array), // postDirectories expect.any(String), // basePath expect.any(String) // writeFilePath ); // ... rest of the test remains the same });This change will provide more robust verification of the
buildPostList
function usage.scripts/index.js (2)
11-17
: LGTM: New variables improve configurability.The introduction of
postDirectories
,basePath
, andwriteFilePath
variables enhances the flexibility of the post list building process. This is a good improvement.Consider adding a brief comment explaining the structure of the
postDirectories
array for improved readability:// Each item in postDirectories is a pair of [directoryPath, urlPath] const postDirectories = [ ['pages/blog', '/blog'], ['pages/docs', '/docs'], ['pages/about', '/about'] ];
Line range hint
1-70
: Overall assessment: Changes improve flexibility and maintainability.The modifications to
scripts/index.js
align well with the PR objectives. They support the new functionality being tested in thebuild-post-list.js
script by updating the import statement and function call. These changes enhance the flexibility and configurability of the post list building process.Consider documenting the new parameter structure for
buildPostList
in a README or inline documentation to help future developers understand the configuration options quickly.scripts/build-post-list.js (1)
71-72
: LGTM: Improved handling of nested sectionsThe changes in how
parent
andsectionId
are set, along with the updated recursive call towalkDirectories
, improve the handling of nested sections. This makes the code more robust when dealing with different directory structures.For added clarity, consider adding a comment explaining the logic behind using
slugElements.length - 2
andslugElements.length - 1
forparent
andsectionId
respectively.Also applies to: 82-82
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
- scripts/build-post-list.js (7 hunks)
- scripts/index.js (1 hunks)
- tests/build-post-list.test.js (1 hunks)
- tests/index.test.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/build-post-list.test.js
🧰 Additional context used
🔇 Additional comments (10)
tests/index.test.js (2)
Line range hint
1-33
: Overall, the changes look good with room for improvement.The import statement has been correctly updated to reflect the changes in the
buildPostList
function. However, the test suite could be enhanced to verify the new function signature. Consider implementing the suggested changes to improve test coverage and ensure consistency with the updatedbuildPostList
function.
2-2
: LGTM! Import statement updated correctly.The change from default import to named import is correct and consistent with the changes in the
buildPostList
function.To ensure consistency, let's verify if the
start
function has been updated to use the newbuildPostList
parameters:✅ Verification successful
Verified! The
start
function correctly usesbuildPostList
with the updated parameters.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check if the start function uses the new buildPostList parameters # Test: Search for buildPostList usage in the start function rg -A 5 'function start' scripts/index.js | rg 'buildPostList'Length of output: 62
Script:
#!/bin/bash # Description: Verify that buildPostList is called with three parameters in scripts/index.js # Search for buildPostList function calls with exactly three arguments ast-grep --pattern 'buildPostList($_, $_, $_)' scripts/index.jsLength of output: 150
scripts/index.js (2)
4-4
: LGTM: Import statement updated correctly.The change to use destructuring for importing
buildPostList
is consistent with modern JavaScript practices and improves code readability.
19-19
: LGTM: Function call updated correctly.The
buildPostList
function call has been correctly updated to include the new parameters, which is consistent with the changes in the function's signature.To ensure that the
buildPostList
function in thebuild-post-list.js
file correctly handles these new parameters, please run the following verification script:This script will help verify that the function signature has been updated correctly and that there are no remaining calls to
buildPostList
without parameters.scripts/build-post-list.js (6)
2-2
: LGTM: Cleaned up importsGood job on cleaning up the imports by only importing the
basename
function from thepath
module. This is a best practice that helps keep the code clean and potentially improves performance.
20-26
: Improved readability, but consider removing empty else blockThe changes to the
addItem
function improve readability with better whitespace. However, the emptyelse { }
block at line 26 is still present and serves no purpose. Consider removing it as suggested in the previous review.
29-43
: Improved function signature and error handling, but consider preserving error stack traceThe changes to the
buildPostList
function are good improvements:
- The updated function signature allows for more flexibility.
- The new error handling for empty
postDirectories
is a good addition.- Writing to a specified
writeFilePath
enhances the function's configurability.However, as mentioned in a previous review, consider preserving the original error stack trace when rethrowing errors. You can do this by either using
throw error
or using thecause
property to retain the error's context.
47-47
: LGTM: Updated walkDirectories function signatureThe addition of the
basePath
parameter to thewalkDirectories
function signature is a good change. It aligns with the updates in thebuildPostList
function and allows for more flexible handling of directory paths.
99-105
: Consider renaming variables and improving consistencyThe changes in this section make minor adjustments to the logic for handling specification references. However, as mentioned in a previous review, the variable
fileName
is still being reused, which could lead to confusion. Consider renaming the innerfileName
to something likeversionName
for clarity.Also, for consistency, consider using template literals for string concatenation in line 105:
details.title = `${capitalize(fileName.slice(1))}`Also applies to: 110-110
125-128
: Improved exports, but consider refining file name handlingThe export of
slugifyToC
andbuildPostList
functions is a good practice for modularity. However, there are a couple of points to consider:
As mentioned in a previous review, instead of manually slicing the file name to remove the extension, consider using
path.basename
andpath.extname
for safer and more reliable handling of file names and extensions.The logic for extracting the version from the file name could be simplified and made more robust. Consider using a regular expression to extract the version number directly:
const versionMatch = file.match(/release-notes-(.+)\.md$/); if (versionMatch) { const version = versionMatch[1]; releaseNotes.push(version); }This approach would be more resilient to changes in file naming conventions.
Also applies to: 162-163
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Left some comments. Please address them.
scripts/build-post-list.js
Outdated
if (details.slug.startsWith('/docs')) | ||
result["docs"].push(details) | ||
else if(details.slug.startsWith('/blog')) | ||
else if (details.slug.startsWith('/blog')) | ||
result["blog"].push(details) | ||
else if(details.slug.startsWith('/about')) | ||
else if (details.slug.startsWith('/about')) | ||
result["about"].push(details) | ||
else {} | ||
else { } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vishvamsinh28 You can apply this suggestion.
scripts/build-post-list.js
Outdated
if (process.env.NODE_ENV === 'production') { | ||
// console.log(inspect(result, { depth: null, colors: true })) | ||
} | ||
writeFileSync(writeFilePath, JSON.stringify(result, null, ' ')) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You can remove this part if this block is doing nothing. It will increase your branch converage.
} catch (error) { | ||
throw new Error(`Error while building post list: ${error.message}`); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Kindly apply this suggestion.
const fileName_without_extension = file.slice(0, -4) | ||
// removes the file extension. For example, release-notes-2.1.0.md -> release-notes-2.1.0 | ||
const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-")+1) | ||
const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-") + 1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vishvamsinh28 Can you please test if these changes are really working? It would be nice to refactor this with utility function of path module.
it('handles heading ids like {# myHeadingId}', () => { | ||
const input = '## My Heading {#custom-id}'; | ||
expect(slugifyToC(input)).toBe('custom-id'); | ||
}); | ||
|
||
it('handles heading ids like {<a name="myHeadingId"/>}', () => { | ||
const input = '## My Heading {<a name="custom-anchor-id"/>}'; | ||
expect(slugifyToC(input)).toBe('custom-anchor-id'); | ||
}); | ||
|
||
it('handles empty strings', () => { | ||
expect(slugifyToC('')).toBe(''); | ||
}); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These tests are not part of buildPostList. You can define different test suites inside same file, with different names under describe.
it('throws an error if the directory cannot be read', async () => { | ||
const invalidDir = [join(tempDir, 'non-existent-dir'), '/invalid']; | ||
|
||
let error; | ||
try { | ||
await buildPostList([invalidDir], tempDir, writeFilePath); | ||
} catch (err) { | ||
error = err; | ||
} | ||
|
||
expect(error).toBeDefined(); | ||
expect(error.message).toMatch(/Error while building post list/); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vishvamsinh28 You've added a similar test above in this file. Please check.
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (3)
tests/build-post-list.test.js (3)
37-83
: Consider enhancing assertions for output structure.While the tests cover the core functionality well, consider adding more specific assertions about the structure of the output object. For example:
// Add these assertions in the first test expect(output.docs).toEqual(expect.arrayContaining([ expect.objectContaining({ title: expect.any(String), slug: expect.any(String), // Add other expected properties }) ]));
90-103
: Group slugifyToC tests in a separate describe block.These tests are testing a different function (slugifyToC) and should be grouped in their own describe block for better organization.
describe('slugifyToC', () => { it('handles heading ids like {# myHeadingId}', () => { const input = '## My Heading {#custom-id}'; expect(slugifyToC(input)).toBe('custom-id'); }); // ... other slugifyToC tests });
149-190
: Refactor repeated error handling pattern.The error handling pattern is duplicated across multiple tests. Consider creating a helper function to reduce code duplication.
const expectErrorWithMessage = async (action, expectedErrorPattern) => { let error; try { await action(); } catch (err) { error = err; } expect(error).toBeDefined(); expect(error.message).toMatch(expectedErrorPattern); }; // Usage in tests: it('throws an error if the directory cannot be read', async () => { const invalidDir = [join(tempDir, 'non-existent-dir'), '/invalid']; await expectErrorWithMessage( () => buildPostList([invalidDir], tempDir, writeFilePath), /Error while building post list/ ); });🧰 Tools
🪛 eslint
[error] 178-179: Delete
⏎
(prettier/prettier)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
tests/build-post-list.test.js
(1 hunks)
🧰 Additional context used
🪛 eslint
tests/build-post-list.test.js
[error] 178-179: Delete ⏎
(prettier/prettier)
🔇 Additional comments (1)
tests/build-post-list.test.js (1)
1-35
: LGTM! Well-structured test setup and teardown.
The test setup is comprehensive with proper initialization and cleanup of test files and directories.
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (3)
scripts/build-post-list.js (1)
162-163
: LGTM! Good change to named exports.The change to named exports improves modularity. Add a semicolon at the end to maintain consistency with the codebase style.
- module.exports = { slugifyToC, buildPostList } + module.exports = { slugifyToC, buildPostList };🧰 Tools
🪛 eslint
[error] 163-163: Insert
;
(prettier/prettier)
tests/build-post-list.test.js (2)
19-22
: Remove redundant directory creationThere's a duplicate directory creation for the blog directory:
- Line 19-20: Using normalized path
- Line 22: Direct path creation
Since
mkdirSync
withrecursive: true
handles path normalization internally, one of these creations can be removed.- const normalizedDir = normalize(join(tempDir, 'blog')); - mkdirSync(normalizedDir, { recursive: true }); - mkdirSync(join(tempDir, 'blog'), { recursive: true });
179-180
: Remove unnecessary blank lineRemove the extra blank line between the test declaration and the error variable initialization to maintain consistent formatting.
it('throws an error if no post directories are provided', async () => { - let error;
🧰 Tools
🪛 eslint
[error] 179-180: Delete
⏎
(prettier/prettier)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
scripts/build-post-list.js
(7 hunks)tests/build-post-list.test.js
(1 hunks)
🧰 Additional context used
🪛 eslint
scripts/build-post-list.js
[error] 163-163: Insert ;
(prettier/prettier)
tests/build-post-list.test.js
[error] 179-180: Delete ⏎
(prettier/prettier)
🔇 Additional comments (8)
scripts/build-post-list.js (6)
28-34
: LGTM! Good improvements to function signature and input validation.
The changes to accept configurable parameters and validate input are well implemented. The normalization of basePath is also a good practice.
42-43
: Previous error handling suggestion remains unaddressed.
As mentioned in the previous review, wrapping the error without preserving the stack trace can make debugging more difficult.
Apply this diff to preserve the original error context:
} catch (error) {
- throw new Error(`Error while building post list: ${error.message}`);
+ throw new Error('Error while building post list', { cause: error });
}
55-58
: LGTM! Good use of path.join for cross-platform compatibility.
The changes to use path.join
for file path handling improve cross-platform compatibility.
97-97
: LGTM! Improved index file detection.
The use of path.join
for index file detection improves cross-platform compatibility.
126-128
: Previous suggestion about using path module functions remains unaddressed.
As mentioned in the previous review, using path.basename
and path.extname
would be safer for handling file extensions.
Apply this diff:
- const fileName_without_extension = file.slice(0, -4)
+ const fileNameWithoutExtension = basename(file, extname(file))
71-72
: Verify array access safety.
The code assumes slugElements
will always have enough elements. Consider adding a length check before accessing array elements.
tests/build-post-list.test.js (2)
38-84
: LGTM! Well-structured core functionality tests
The tests effectively cover:
- Basic post list building and file writing
- Section file handling
- Multiple release notes processing
The tests follow good practices with clear arrange-act-assert patterns and meaningful assertions.
105-148
: LGTM! Comprehensive specification file handling tests
The tests effectively cover various specification file scenarios:
- Files without titles
- Files with "next-spec" in filename
- Files with "explorer" in filename
Each test is well-structured with clear setup and assertions.
it('handles heading ids like {# myHeadingId}', () => { | ||
const input = '## My Heading {#custom-id}'; | ||
expect(slugifyToC(input)).toBe('custom-id'); | ||
}); | ||
|
||
it('handles heading ids like {<a name="myHeadingId"/>}', () => { | ||
const input = '## My Heading {<a name="custom-anchor-id"/>}'; | ||
expect(slugifyToC(input)).toBe('custom-anchor-id'); | ||
}); | ||
|
||
it('handles empty strings', () => { | ||
expect(slugifyToC('')).toBe(''); | ||
}); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Organize slugifyToC tests in a separate describe block
These tests are testing a different function (slugifyToC
) and should be organized in their own describe block for better test organization and maintainability.
- it('handles heading ids like {# myHeadingId}', () => {
+ describe('slugifyToC', () => {
+ it('handles heading ids like {# myHeadingId}', () => {
const input = '## My Heading {#custom-id}';
expect(slugifyToC(input)).toBe('custom-id');
- });
+ });
- it('handles heading ids like {<a name="myHeadingId"/>}', () => {
+ it('handles heading ids like {<a name="myHeadingId"/>}', () => {
const input = '## My Heading {<a name="custom-anchor-id"/>}';
expect(slugifyToC(input)).toBe('custom-anchor-id');
- });
+ });
- it('handles empty strings', () => {
+ it('handles empty strings', () => {
expect(slugifyToC('')).toBe('');
+ });
});
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('handles heading ids like {# myHeadingId}', () => { | |
const input = '## My Heading {#custom-id}'; | |
expect(slugifyToC(input)).toBe('custom-id'); | |
}); | |
it('handles heading ids like {<a name="myHeadingId"/>}', () => { | |
const input = '## My Heading {<a name="custom-anchor-id"/>}'; | |
expect(slugifyToC(input)).toBe('custom-anchor-id'); | |
}); | |
it('handles empty strings', () => { | |
expect(slugifyToC('')).toBe(''); | |
}); | |
describe('slugifyToC', () => { | |
it('handles heading ids like {# myHeadingId}', () => { | |
const input = '## My Heading {#custom-id}'; | |
expect(slugifyToC(input)).toBe('custom-id'); | |
}); | |
it('handles heading ids like {<a name="myHeadingId"/>}', () => { | |
const input = '## My Heading {<a name="custom-anchor-id"/>}'; | |
expect(slugifyToC(input)).toBe('custom-anchor-id'); | |
}); | |
it('handles empty strings', () => { | |
expect(slugifyToC('')).toBe(''); | |
}); | |
}); |
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (3)
scripts/build-post-list.js (1)
162-163
: LGTM: Clean module exports.The change to named exports is good for tree-shaking and modularity. Minor nitpick: add a semicolon at the end of the exports statement.
-module.exports = { slugifyToC, buildPostList } +module.exports = { slugifyToC, buildPostList };🧰 Tools
🪛 eslint
[error] 163-163: Insert
;
(prettier/prettier)
tests/build-post-list.test.js (2)
46-46
: Remove debug console.log statementsDebug console.log statements should be removed before merging:
- Line 46:
console.log(output)
- Line 65:
console.log(output)
- Line 77:
console.log(output)
- console.log(output)
Also applies to: 65-65, 77-77
182-183
: Fix formatting: Remove extra newlineRemove the extra newline between lines 182 and 183 to maintain consistent formatting.
it('throws an error if no post directories are provided', async () => { - let error;
🧰 Tools
🪛 eslint
[error] 182-183: Delete
⏎
(prettier/prettier)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
scripts/build-post-list.js
(7 hunks)tests/build-post-list.test.js
(1 hunks)
🧰 Additional context used
🪛 eslint
scripts/build-post-list.js
[error] 163-163: Insert ;
(prettier/prettier)
tests/build-post-list.test.js
[error] 182-183: Delete ⏎
(prettier/prettier)
🔇 Additional comments (9)
scripts/build-post-list.js (5)
28-32
: LGTM: Good parameter validation and error handling.
The function signature changes and validation of empty directories are well implemented.
42-43
: Previous review comment about error handling is still valid.
The error handling in the catch block should preserve the original stack trace.
99-105
: Previous review comment about variable shadowing is still valid.
The variable fileName
is still being redefined within this block.
125-128
: Use path module for file extension handling.
The manual string manipulation for file extensions using slice
is error-prone. Previous suggestion to use path.basename
and path.extname
is still valid.
47-47
: Verify path handling security.
The path handling logic needs verification to ensure it's protected against path traversal attacks. The normalize
and replace
operations on user-provided paths should be carefully validated.
Also applies to: 51-51, 55-58
✅ Verification successful
Based on the extensive search results, I can now generate the final response regarding the path traversal security concern.
Path handling is secure against traversal attacks
The walkDirectories
function in scripts/build-post-list.js
is used in a controlled environment where:
- All paths are relative to the repository root
- Input paths are validated through
fd
command usage - No user-provided paths are directly used in file operations
- Path traversal via
../
is only used for internal imports and not for file operations - No direct file system traversal using user input is performed
The codebase shows consistent and safe path handling patterns:
- Uses
resolve()
for path normalization - Employs path utilities from Node.js
- Restricts operations to specific directories
- Validates paths before operations
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for potential path traversal vulnerabilities in directory handling
rg -A 2 "\.\./" .
rg -A 2 "\.\." .
Length of output: 241067
tests/build-post-list.test.js (4)
1-36
: Well-structured test setup!
The test setup follows best practices with:
- Proper isolation using temporary directories
- Comprehensive sample data setup
- Clean teardown after each test
89-92
: LGTM with existing feedback!
The error handling tests are comprehensive, covering various edge cases. A previous review has already addressed the duplicate test case issue.
Also applies to: 153-194
94-107
: LGTM with existing feedback!
The slugifyToC tests are comprehensive. A previous review has already suggested organizing these in a separate describe block.
108-151
: Well-structured special case handling tests!
The tests thoroughly cover edge cases for specification files:
- Files without titles
- Next-spec files
- Explorer files
Each test is focused and verifies a specific condition with proper setup and assertions.
There was a problem hiding this 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 (1)
scripts/build-post-list.js (1)
48-51
: Use const declarations for immutable variablesThese variables are never reassigned and should use
const
instead oflet
.- let directory = posix.normalize(dir[0]); - let sectionSlug = dir[1] || ''; - let files = readdirSync(directory); + const directory = posix.normalize(dir[0]); + const sectionSlug = dir[1] || ''; + const files = readdirSync(directory);🧰 Tools
🪛 eslint
[error] 48-139: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.
(no-restricted-syntax)
[error] 48-48: 'dir' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 49-49: 'directory' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 50-50: 'sectionSlug' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 51-51: 'files' is never reassigned. Use 'const' instead.
(prefer-const)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
scripts/build-post-list.js
(7 hunks)
🧰 Additional context used
🪛 eslint
scripts/build-post-list.js
[error] 2-2: Insert ;
(prettier/prettier)
[error] 20-21: Replace ⏎····result["docs"].push(details)
with ·result['docs'].push(details);
(prettier/prettier)
[error] 21-21: ["docs"] is better written in dot notation.
(dot-notation)
[error] 22-23: Replace ⏎····result["blog"].push(details)
with ·result['blog'].push(details);
(prettier/prettier)
[error] 23-23: ["blog"] is better written in dot notation.
(dot-notation)
[error] 24-25: Replace ⏎····result["about"].push(details)
with ·result['about'].push(details);
(prettier/prettier)
[error] 25-25: ["about"] is better written in dot notation.
(dot-notation)
[error] 33-33: Insert ;
(prettier/prettier)
[error] 34-34: 'walkDirectories' was used before it was defined.
(no-use-before-define)
[error] 34-34: Insert ;
(prettier/prettier)
[error] 35-35: Replace "docs"].filter((p)·=>·p.slug.startsWith('/docs/')))
with 'docs'].filter((p)·=>·p.slug.startsWith('/docs/')));
(prettier/prettier)
[error] 35-35: ["docs"] is better written in dot notation.
(dot-notation)
[error] 36-36: Replace "docsTree"]·=·treePosts
with 'docsTree']·=·treePosts;
(prettier/prettier)
[error] 36-36: ["docsTree"] is better written in dot notation.
(dot-notation)
[error] 37-37: Replace "docs"]·=·addDocButtons(result["docs"],·treePosts)
with 'docs']·=·addDocButtons(result['docs'],·treePosts);
(prettier/prettier)
[error] 37-37: ["docs"] is better written in dot notation.
(dot-notation)
[error] 37-37: ["docs"] is better written in dot notation.
(dot-notation)
[error] 41-41: Insert ;
(prettier/prettier)
[error] 47-47: 'result' is already declared in the upper scope on line 11 column 7.
(no-shadow)
[error] 47-47: Default parameters should be last.
(default-param-last)
[error] 48-48: 'dir' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 49-49: 'directory' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 50-50: 'sectionSlug' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 51-51: 'files' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 53-53: 'file' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 58-58: Insert ;
(prettier/prettier)
[error] 72-72: Insert ;
(prettier/prettier)
[error] 73-73: Insert ;
(prettier/prettier)
[error] 83-83: Insert ;
(prettier/prettier)
[error] 84-84: Unexpected string concatenation.
(prefer-template)
[error] 98-98: Insert ;
(prettier/prettier)
[error] 99-99: Insert ;
(prettier/prettier)
[error] 101-101: Replace ·
with ;
(prettier/prettier)
[error] 102-102: 'fileName' is already declared in the upper scope on line 55 column 13.
(no-shadow)
[error] 102-102: Insert ;
(prettier/prettier)
[error] 103-103: Unary operator '--' used.
(no-plusplus)
[error] 103-103: Insert ;
(prettier/prettier)
[error] 106-106: 'capitalize' was used before it was defined.
(no-use-before-define)
[error] 106-106: Insert ;
(prettier/prettier)
[error] 108-108: 'capitalize' was used before it was defined.
(no-use-before-define)
[error] 108-108: Insert ;
(prettier/prettier)
[error] 126-126: Replace "release-notes")·&&·dir[1]·===·"/blog"
with 'release-notes')·&&·dir[1]·===·'/blog'
(prettier/prettier)
[error] 127-127: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 127-127: Insert ;
(prettier/prettier)
[error] 129-129: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 129-129: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 129-129: Replace "-")·+·1)
with '-')·+·1);
(prettier/prettier)
[error] 164-164: Insert ;
(prettier/prettier)
🔇 Additional comments (4)
scripts/build-post-list.js (4)
42-43
: Preserve error stack trace
When rethrowing errors, it's better to preserve the original stack trace using the cause
property (Node.js ≥ 16.9.0).
- throw new Error(`Error while building post list: ${error.message}`);
+ throw new Error('Error while building post list', { cause: error });
101-103
: Fix variable shadowing in reference specification processing
The fileName
variable shadows the outer declaration, which could lead to confusion.
const fileBaseName = basename(data.slug) // ex. v2.0.0 | v2.1.0-next-spec.1
- const fileName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0
+ const versionName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0
- details.weight = specWeight--
+ details.weight = specWeight -= 1
🧰 Tools
🪛 eslint
[error] 101-101: Replace ·
with ;
(prettier/prettier)
[error] 102-102: 'fileName' is already declared in the upper scope on line 55 column 13.
(no-shadow)
[error] 102-102: Insert ;
(prettier/prettier)
[error] 103-103: Unary operator '--' used.
(no-plusplus)
[error] 103-103: Insert ;
(prettier/prettier)
126-129
: Use path module for file extension handling
Instead of manual string manipulation, use the path module's functions for safer file extension handling.
- const fileName_without_extension = file.slice(0, -4)
+ const fileNameWithoutExtension = basename(file, extname(file))
- const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-") + 1)
+ const version = fileNameWithoutExtension.slice(fileNameWithoutExtension.lastIndexOf("-") + 1)
🧰 Tools
🪛 eslint
[error] 126-126: Replace "release-notes")·&&·dir[1]·===·"/blog"
with 'release-notes')·&&·dir[1]·===·'/blog'
(prettier/prettier)
[error] 127-127: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 127-127: Insert ;
(prettier/prettier)
[error] 129-129: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 129-129: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 129-129: Replace "-")·+·1)
with '-')·+·1);
(prettier/prettier)
163-164
: LGTM: Clean module exports
The module exports are well-structured, exporting both utility functions as named exports.
🧰 Tools
🪛 eslint
[error] 164-164: Insert ;
(prettier/prettier)
scripts/build-post-list.js
Outdated
} | ||
|
||
function walkDirectories(directories, result, sectionWeight = 0, sectionTitle, sectionId, rootSectionId) { | ||
function walkDirectories(directories, result, basePath, sectionWeight = 0, sectionTitle, sectionId, rootSectionId) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Fix parameter shadowing and default parameter placement
The function has two issues:
- The
result
parameter shadows the globalresult
variable - The default parameter
sectionWeight
should be last in the parameter list
- function walkDirectories(directories, result, basePath, sectionWeight = 0, sectionTitle, sectionId, rootSectionId) {
+ function walkDirectories(directories, resultObj, basePath, sectionTitle, sectionId, rootSectionId, sectionWeight = 0) {
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
function walkDirectories(directories, result, basePath, sectionWeight = 0, sectionTitle, sectionId, rootSectionId) { | |
function walkDirectories(directories, resultObj, basePath, sectionTitle, sectionId, rootSectionId, sectionWeight = 0) { |
🧰 Tools
🪛 eslint
[error] 47-47: 'result' is already declared in the upper scope on line 11 column 7.
(no-shadow)
[error] 47-47: Default parameters should be last.
(default-param-last)
scripts/build-post-list.js
Outdated
if (process.env.NODE_ENV === 'production') { | ||
// console.log(inspect(result, { depth: null, colors: true })) | ||
} | ||
writeFileSync(writeFilePath, JSON.stringify(result, null, ' ')) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove unnecessary production check
The empty production environment check serves no purpose and can be safely removed.
- if (process.env.NODE_ENV === 'production') {
- // console.log(inspect(result, { depth: null, colors: true }))
- }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (process.env.NODE_ENV === 'production') { | |
// console.log(inspect(result, { depth: null, colors: true })) | |
} | |
writeFileSync(writeFilePath, JSON.stringify(result, null, ' ')) | |
writeFileSync(writeFilePath, JSON.stringify(result, null, ' ')) |
🧰 Tools
🪛 eslint
[error] 41-41: Insert ;
(prettier/prettier)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
🧹 Outside diff range and nitpick comments (4)
scripts/build-post-list.js (2)
Line range hint
1-17
: Consider encapsulating global stateThe global mutable variables
result
andreleaseNotes
could lead to issues with concurrent operations and make the code harder to test. Consider encapsulating this state within thebuildPostList
function or creating a class to manage the state.-const result = { - docs: [], - blog: [], - about: [], - docsTree: {} -} -const releaseNotes = [] async function buildPostList(postDirectories, basePath, writeFilePath) { + const result = { + docs: [], + blog: [], + about: [], + docsTree: {} + } + const releaseNotes = []🧰 Tools
🪛 eslint
[error] 1-1: Insert
;
(prettier/prettier)
[error] 2-2: Insert
;
(prettier/prettier)
[error] 3-3: Insert
;
(prettier/prettier)
[error] 4-4: Insert
;
(prettier/prettier)
[error] 5-5: Insert
;
(prettier/prettier)
19-26
: Use dot notation for object propertiesUsing string literals for accessing object properties is less readable and more error-prone. Consider using dot notation instead.
const addItem = (details) => { if (details.slug.startsWith('/docs')) - result["docs"].push(details) + result.docs.push(details) else if (details.slug.startsWith('/blog')) - result["blog"].push(details) + result.blog.push(details) else if (details.slug.startsWith('/about')) - result["about"].push(details) + result.about.push(details) };🧰 Tools
🪛 eslint
[error] 20-21: Replace
⏎····result["docs"].push(details)
with·result['docs'].push(details);
(prettier/prettier)
[error] 21-21: ["docs"] is better written in dot notation.
(dot-notation)
[error] 22-23: Replace
⏎····result["blog"].push(details)
with·result['blog'].push(details);
(prettier/prettier)
[error] 23-23: ["blog"] is better written in dot notation.
(dot-notation)
[error] 24-25: Replace
⏎····result["about"].push(details)
with·result['about'].push(details);
(prettier/prettier)
[error] 25-25: ["about"] is better written in dot notation.
(dot-notation)
tests/build-post-list.test.js (2)
1-36
: Test setup looks good with room for minor improvementsThe test setup is well-structured with proper initialization and cleanup. Consider these minor enhancements:
- Extract sample file contents to constants for better maintainability
- Use
path.join
consistently instead of mixing with template literals+const SAMPLE_CONTENT = { + releaseNotes: '---\ntitle: Release Notes 2.1.0\n---\nThis is a release note.', + docsHome: '---\ntitle: Docs Home\n---\nThis is the documentation homepage.', + about: '---\ntitle: About Us\n---\nThis is the about page.' +}; beforeEach(async () => { - tempDir = resolve(__dirname, `test-config`); + tempDir = join(__dirname, 'test-config'); // ... rest of the setup await fs.writeFile( join(tempDir, 'blog', 'release-notes-2.1.0.mdx'), - '---\ntitle: Release Notes 2.1.0\n---\nThis is a release note.' + SAMPLE_CONTENT.releaseNotes );🧰 Tools
🪛 eslint
[error] 5-5: 'describe' is not defined.
(no-undef)
[error] 10-10: 'beforeEach' is not defined.
(no-undef)
[error] 16-16: Delete
,
(prettier/prettier)
[error] 23-23: Replace
join(tempDir,·'blog',·'release-notes-2.1.0.mdx'),·'---\ntitle:·Release·Notes·2.1.0\n---\nThis·is·a·release·note.'
with⏎······join(tempDir,·'blog',·'release-notes-2.1.0.mdx'),⏎······'---\ntitle:·Release·Notes·2.1.0\n---\nThis·is·a·release·note.'⏎····
(prettier/prettier)
[error] 26-26: Replace
join(tempDir,·'docs',·'index.mdx'),·'---\ntitle:·Docs·Home\n---\nThis·is·the·documentation·homepage.'
with⏎······join(tempDir,·'docs',·'index.mdx'),⏎······'---\ntitle:·Docs·Home\n---\nThis·is·the·documentation·homepage.'⏎····
(prettier/prettier)
[error] 34-34: 'afterEach' is not defined.
(no-undef)
5-183
: Consider adding tests for these scenariosThe test suite is comprehensive but could benefit from additional test cases:
- Test handling of malformed file paths
- Test handling of files with invalid extensions
- Test concurrent file operations
- Test handling of symbolic links
Would you like me to help implement these additional test cases?
🧰 Tools
🪛 eslint
[error] 5-5: 'describe' is not defined.
(no-undef)
[error] 10-10: 'beforeEach' is not defined.
(no-undef)
[error] 16-16: Delete
,
(prettier/prettier)
[error] 23-23: Replace
join(tempDir,·'blog',·'release-notes-2.1.0.mdx'),·'---\ntitle:·Release·Notes·2.1.0\n---\nThis·is·a·release·note.'
with⏎······join(tempDir,·'blog',·'release-notes-2.1.0.mdx'),⏎······'---\ntitle:·Release·Notes·2.1.0\n---\nThis·is·a·release·note.'⏎····
(prettier/prettier)
[error] 26-26: Replace
join(tempDir,·'docs',·'index.mdx'),·'---\ntitle:·Docs·Home\n---\nThis·is·the·documentation·homepage.'
with⏎······join(tempDir,·'docs',·'index.mdx'),⏎······'---\ntitle:·Docs·Home\n---\nThis·is·the·documentation·homepage.'⏎····
(prettier/prettier)
[error] 34-34: 'afterEach' is not defined.
(no-undef)
[error] 38-38: 'it' is not defined.
(no-undef)
[error] 52-52: Replace
item
with(item)
(prettier/prettier)
[error] 57-57: 'it' is not defined.
(no-undef)
[error] 59-59: Replace
join(tempDir,·'docs',·'section1',·'_section.mdx'),·'---\ntitle:·Section·1\n---\nThis·is·section·1.'
with⏎······join(tempDir,·'docs',·'section1',·'_section.mdx'),⏎······'---\ntitle:·Section·1\n---\nThis·is·section·1.'⏎····
(prettier/prettier)
[error] 67-67: Replace
item
with(item)
(prettier/prettier)
[error] 70-70: 'it' is not defined.
(no-undef)
[error] 71-71: Replace
join(tempDir,·'blog',·'release-notes-2.1.1.mdx'),·'---\ntitle:·Release·Notes·2.1.1\n---\nThis·is·a·release·note.'
with⏎······join(tempDir,·'blog',·'release-notes-2.1.1.mdx'),⏎······'---\ntitle:·Release·Notes·2.1.1\n---\nThis·is·a·release·note.'⏎····
(prettier/prettier)
[error] 78-78: Replace
item
with(item)
(prettier/prettier)
[error] 79-79: Replace
item
with(item)
(prettier/prettier)
[error] 88-88: 'it' is not defined.
(no-undef)
[error] 93-93: 'it' is not defined.
(no-undef)
[error] 98-98: 'it' is not defined.
(no-undef)
[error] 103-103: 'it' is not defined.
(no-undef)
[error] 107-107: 'it' is not defined.
(no-undef)
[error] 114-114: Replace
item
with(item)
(prettier/prettier)
[error] 119-119: 'it' is not defined.
(no-undef)
[error] 121-121: Replace
join(specDir,·'v2.1.0-next-spec.1.mdx'),·'---\n---\nContent·of·pre-release·specification·v2.1.0-next-spec.1.'
with⏎······join(specDir,·'v2.1.0-next-spec.1.mdx'),⏎······'---\n---\nContent·of·pre-release·specification·v2.1.0-next-spec.1.'⏎····
(prettier/prettier)
[error] 126-126: Replace
item
with(item)
(prettier/prettier)
[error] 131-131: 'it' is not defined.
(no-undef)
[error] 138-138: Replace
item
with(item)
(prettier/prettier)
[error] 143-143: 'it' is not defined.
(no-undef)
[error] 157-157: 'it' is not defined.
(no-undef)
[error] 171-171: 'it' is not defined.
(no-undef)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
-
scripts/build-post-list.js
(7 hunks) -
tests/build-post-list.test.js
(1 hunks)
🧰 Additional context used
🪛 eslint
scripts/build-post-list.js
[error] 1-1: Insert ;
(prettier/prettier)
[error] 2-2: Insert ;
(prettier/prettier)
[error] 20-21: Replace ⏎····result["docs"].push(details)
with ·result['docs'].push(details);
(prettier/prettier)
[error] 21-21: ["docs"] is better written in dot notation.
(dot-notation)
[error] 22-23: Replace ⏎····result["blog"].push(details)
with ·result['blog'].push(details);
(prettier/prettier)
[error] 23-23: ["blog"] is better written in dot notation.
(dot-notation)
[error] 24-25: Replace ⏎····result["about"].push(details)
with ·result['about'].push(details);
(prettier/prettier)
[error] 25-25: ["about"] is better written in dot notation.
(dot-notation)
[error] 33-33: Insert ;
(prettier/prettier)
[error] 34-34: 'walkDirectories' was used before it was defined.
(no-use-before-define)
[error] 34-34: Insert ;
(prettier/prettier)
[error] 35-35: Replace "docs"].filter((p)·=>·p.slug.startsWith('/docs/')))
with 'docs'].filter((p)·=>·p.slug.startsWith('/docs/')));
(prettier/prettier)
[error] 35-35: ["docs"] is better written in dot notation.
(dot-notation)
[error] 36-36: Replace "docsTree"]·=·treePosts
with 'docsTree']·=·treePosts;
(prettier/prettier)
[error] 36-36: ["docsTree"] is better written in dot notation.
(dot-notation)
[error] 37-37: Replace "docs"]·=·addDocButtons(result["docs"],·treePosts)
with 'docs']·=·addDocButtons(result['docs'],·treePosts);
(prettier/prettier)
[error] 37-37: ["docs"] is better written in dot notation.
(dot-notation)
[error] 37-37: ["docs"] is better written in dot notation.
(dot-notation)
[error] 41-41: Insert ;
(prettier/prettier)
[error] 47-47: This line has a length of 122. Maximum allowed is 120.
(max-len)
[error] 47-47: Replace directories,·result,·basePath,·sectionWeight·=·0,·sectionTitle,·sectionId,·rootSectionId
with ⏎··directories,⏎··result,⏎··basePath,⏎··sectionWeight·=·0,⏎··sectionTitle,⏎··sectionId,⏎··rootSectionId⏎
(prettier/prettier)
[error] 47-47: 'result' is already declared in the upper scope on line 11 column 7.
(no-shadow)
[error] 47-47: Default parameters should be last.
(default-param-last)
[error] 48-48: 'dir' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 49-49: 'directory' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 50-50: 'sectionSlug' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 51-51: 'files' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 51-51: Unexpected await
inside a loop.
(no-await-in-loop)
[error] 51-51: Insert ;
(prettier/prettier)
[error] 53-53: 'file' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 58-58: Insert ;
(prettier/prettier)
[error] 60-60: Unexpected await
inside a loop.
(no-await-in-loop)
[error] 60-60: 'isDirectory' was used before it was defined.
(no-use-before-define)
[error] 61-61: Unexpected await
inside a loop.
(no-await-in-loop)
[error] 63-63: Unexpected await
inside a loop.
(no-await-in-loop)
[error] 63-63: Insert ;
(prettier/prettier)
[error] 72-72: Insert ;
(prettier/prettier)
[error] 73-73: Insert ;
(prettier/prettier)
[error] 83-83: This line has a length of 125. Maximum allowed is 120.
(max-len)
[error] 83-83: Unexpected await
inside a loop.
(no-await-in-loop)
[error] 83-83: Replace [[fileName,·slug]],·result,·basePath,·details.weight,·details.title,·details.sectionId,·rootId)
with ⏎··········[[fileName,·slug]],⏎··········result,⏎··········basePath,⏎··········details.weight,⏎··········details.title,⏎··········details.sectionId,⏎··········rootId⏎········);
(prettier/prettier)
[error] 84-84: Unexpected string concatenation.
(prefer-template)
[error] 85-85: Unexpected await
inside a loop.
(no-await-in-loop)
[error] 85-85: Insert ;
(prettier/prettier)
[error] 97-97: Insert ;
(prettier/prettier)
[error] 98-98: Insert ;
(prettier/prettier)
[error] 99-99: Insert ;
(prettier/prettier)
[error] 101-101: Replace ·
with ;
(prettier/prettier)
[error] 102-102: 'fileName' is already declared in the upper scope on line 55 column 13.
(no-shadow)
[error] 102-102: Insert ;
(prettier/prettier)
[error] 103-103: Unary operator '--' used.
(no-plusplus)
[error] 103-103: Insert ;
(prettier/prettier)
[error] 106-106: 'capitalize' was used before it was defined.
(no-use-before-define)
[error] 106-106: Insert ;
(prettier/prettier)
[error] 108-108: 'capitalize' was used before it was defined.
(no-use-before-define)
[error] 108-108: Insert ;
(prettier/prettier)
[error] 126-126: Replace "release-notes")·&&·dir[1]·===·"/blog"
with 'release-notes')·&&·dir[1]·===·'/blog'
(prettier/prettier)
[error] 127-127: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 127-127: Insert ;
(prettier/prettier)
[error] 129-129: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 129-129: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 129-129: Replace "-")·+·1)
with '-')·+·1);
(prettier/prettier)
[error] 157-157: Insert ;
(prettier/prettier)
[error] 161-161: Replace .split(/[\s\-]/g).map(word·=>·
${word[0].toUpperCase()}${word.substr(1)}).join('·')
with ⏎····.split(/[\s\-]/g)⏎····.map((word)·=>·
${word[0].toUpperCase()}${word.substr(1)})⏎····.join('·');
(prettier/prettier)
[error] 161-161: Unnecessary escape character: -.
(no-useless-escape)
[error] 164-164: Insert ;
(prettier/prettier)
tests/build-post-list.test.js
[error] 5-5: 'describe' is not defined.
(no-undef)
[error] 10-10: 'beforeEach' is not defined.
(no-undef)
[error] 16-16: Delete ,
(prettier/prettier)
[error] 23-23: Replace join(tempDir,·'blog',·'release-notes-2.1.0.mdx'),·'---\ntitle:·Release·Notes·2.1.0\n---\nThis·is·a·release·note.'
with ⏎······join(tempDir,·'blog',·'release-notes-2.1.0.mdx'),⏎······'---\ntitle:·Release·Notes·2.1.0\n---\nThis·is·a·release·note.'⏎····
(prettier/prettier)
[error] 26-26: Replace join(tempDir,·'docs',·'index.mdx'),·'---\ntitle:·Docs·Home\n---\nThis·is·the·documentation·homepage.'
with ⏎······join(tempDir,·'docs',·'index.mdx'),⏎······'---\ntitle:·Docs·Home\n---\nThis·is·the·documentation·homepage.'⏎····
(prettier/prettier)
[error] 34-34: 'afterEach' is not defined.
(no-undef)
[error] 38-38: 'it' is not defined.
(no-undef)
[error] 52-52: Replace item
with (item)
(prettier/prettier)
[error] 57-57: 'it' is not defined.
(no-undef)
[error] 59-59: Replace join(tempDir,·'docs',·'section1',·'_section.mdx'),·'---\ntitle:·Section·1\n---\nThis·is·section·1.'
with ⏎······join(tempDir,·'docs',·'section1',·'_section.mdx'),⏎······'---\ntitle:·Section·1\n---\nThis·is·section·1.'⏎····
(prettier/prettier)
[error] 67-67: Replace item
with (item)
(prettier/prettier)
[error] 70-70: 'it' is not defined.
(no-undef)
[error] 71-71: Replace join(tempDir,·'blog',·'release-notes-2.1.1.mdx'),·'---\ntitle:·Release·Notes·2.1.1\n---\nThis·is·a·release·note.'
with ⏎······join(tempDir,·'blog',·'release-notes-2.1.1.mdx'),⏎······'---\ntitle:·Release·Notes·2.1.1\n---\nThis·is·a·release·note.'⏎····
(prettier/prettier)
[error] 78-78: Replace item
with (item)
(prettier/prettier)
[error] 79-79: Replace item
with (item)
(prettier/prettier)
[error] 88-88: 'it' is not defined.
(no-undef)
[error] 93-93: 'it' is not defined.
(no-undef)
[error] 98-98: 'it' is not defined.
(no-undef)
[error] 103-103: 'it' is not defined.
(no-undef)
[error] 107-107: 'it' is not defined.
(no-undef)
[error] 114-114: Replace item
with (item)
(prettier/prettier)
[error] 119-119: 'it' is not defined.
(no-undef)
[error] 121-121: Replace join(specDir,·'v2.1.0-next-spec.1.mdx'),·'---\n---\nContent·of·pre-release·specification·v2.1.0-next-spec.1.'
with ⏎······join(specDir,·'v2.1.0-next-spec.1.mdx'),⏎······'---\n---\nContent·of·pre-release·specification·v2.1.0-next-spec.1.'⏎····
(prettier/prettier)
[error] 126-126: Replace item
with (item)
(prettier/prettier)
[error] 131-131: 'it' is not defined.
(no-undef)
[error] 138-138: Replace item
with (item)
(prettier/prettier)
[error] 143-143: 'it' is not defined.
(no-undef)
[error] 157-157: 'it' is not defined.
(no-undef)
[error] 171-171: 'it' is not defined.
(no-undef)
🔇 Additional comments (3)
scripts/build-post-list.js (1)
100-106
:
Fix variable shadowing in reference specification handling
The fileName
variable shadows the one defined in the outer scope, which could lead to confusion and bugs.
if (details.slug.includes('/reference/specification/') && !details.title) {
const fileBaseName = basename(data.slug) // ex. v2.0.0 | v2.1.0-next-spec.1
- const fileName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0
+ const versionName = fileBaseName.split('-')[0] // v2.0.0 | v2.1.0
details.weight = specWeight--
- if (fileName.startsWith('v')) {
- details.title = capitalize(fileName.slice(1))
+ if (versionName.startsWith('v')) {
+ details.title = capitalize(versionName.slice(1))
Likely invalid or redundant comment.
🧰 Tools
🪛 eslint
[error] 101-101: Replace ·
with ;
(prettier/prettier)
[error] 102-102: 'fileName' is already declared in the upper scope on line 55 column 13.
(no-shadow)
[error] 102-102: Insert ;
(prettier/prettier)
[error] 103-103: Unary operator '--' used.
(no-plusplus)
[error] 103-103: Insert ;
(prettier/prettier)
[error] 106-106: 'capitalize' was used before it was defined.
(no-use-before-define)
[error] 106-106: Insert ;
(prettier/prettier)
tests/build-post-list.test.js (2)
93-106
: Organize slugifyToC tests separately
🧰 Tools
🪛 eslint
[error] 93-93: 'it' is not defined.
(no-undef)
[error] 98-98: 'it' is not defined.
(no-undef)
[error] 103-103: 'it' is not defined.
(no-undef)
143-182
: Consolidate error handling tests
🧰 Tools
🪛 eslint
[error] 143-143: 'it' is not defined.
(no-undef)
[error] 157-157: 'it' is not defined.
(no-undef)
[error] 171-171: 'it' is not defined.
(no-undef)
let files = readdirSync(directory); | ||
let directory = posix.normalize(dir[0]); | ||
let sectionSlug = dir[1] || ''; | ||
let files = await readdir(directory) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Optimize async operations in loops
Multiple await
calls inside loops can significantly impact performance. Consider using Promise.all
to parallelize these operations.
- let files = await readdir(directory)
+ const files = await readdir(directory)
+ const filePromises = files.map(async (file) => {
// Move the file processing logic here
+ })
+ await Promise.all(filePromises)
Also applies to: 83-83, 85-85
🧰 Tools
🪛 eslint
[error] 51-51: 'files' is never reassigned. Use 'const' instead.
(prefer-const)
[error] 51-51: Unexpected await
inside a loop.
(no-await-in-loop)
[error] 51-51: Insert ;
(prettier/prettier)
if (process.env.NODE_ENV === 'production') { | ||
// console.log(inspect(result, { depth: null, colors: true })) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove unnecessary production check block
The production environment check block contains only a commented console.log and serves no purpose.
- if (process.env.NODE_ENV === 'production') {
- // console.log(inspect(result, { depth: null, colors: true }))
- }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (process.env.NODE_ENV === 'production') { | |
// console.log(inspect(result, { depth: null, colors: true })) | |
} |
} | ||
|
||
function walkDirectories(directories, result, sectionWeight = 0, sectionTitle, sectionId, rootSectionId) { | ||
async function walkDirectories(directories, result, basePath, sectionWeight = 0, sectionTitle, sectionId, rootSectionId) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix parameter shadowing and default parameter placement
The function has two issues:
- The
result
parameter shadows the globalresult
variable - The default parameter
sectionWeight
should be last in the parameter list
-async function walkDirectories(directories, result, basePath, sectionWeight = 0, sectionTitle, sectionId, rootSectionId) {
+async function walkDirectories(directories, resultObj, basePath, sectionTitle, sectionId, rootSectionId, sectionWeight = 0) {
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
async function walkDirectories(directories, result, basePath, sectionWeight = 0, sectionTitle, sectionId, rootSectionId) { | |
async function walkDirectories(directories, resultObj, basePath, sectionTitle, sectionId, rootSectionId, sectionWeight = 0) { |
🧰 Tools
🪛 eslint
[error] 47-47: This line has a length of 122. Maximum allowed is 120.
(max-len)
[error] 47-47: Replace directories,·result,·basePath,·sectionWeight·=·0,·sectionTitle,·sectionId,·rootSectionId
with ⏎··directories,⏎··result,⏎··basePath,⏎··sectionWeight·=·0,⏎··sectionTitle,⏎··sectionId,⏎··rootSectionId⏎
(prettier/prettier)
[error] 47-47: 'result' is already declared in the upper scope on line 11 column 7.
(no-shadow)
[error] 47-47: Default parameters should be last.
(default-param-last)
if (file.startsWith("release-notes") && dir[1] === "/blog") { | ||
const fileName_without_extension = file.slice(0, -4) | ||
// removes the file extension. For example, release-notes-2.1.0.md -> release-notes-2.1.0 | ||
const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-")+1) | ||
const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-") + 1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use path module functions and follow naming conventions
The file extension handling could be improved using the path
module, and variable names should follow camelCase convention.
- const fileName_without_extension = file.slice(0, -4)
- const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-") + 1)
+ const fileNameWithoutExt = basename(file, extname(file))
+ const version = fileNameWithoutExt.slice(fileNameWithoutExt.lastIndexOf('-') + 1)
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (file.startsWith("release-notes") && dir[1] === "/blog") { | |
const fileName_without_extension = file.slice(0, -4) | |
// removes the file extension. For example, release-notes-2.1.0.md -> release-notes-2.1.0 | |
const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-")+1) | |
const version = fileName_without_extension.slice(fileName_without_extension.lastIndexOf("-") + 1) | |
if (file.startsWith("release-notes") && dir[1] === "/blog") { | |
const fileNameWithoutExt = basename(file, extname(file)) | |
// removes the file extension. For example, release-notes-2.1.0.md -> release-notes-2.1.0 | |
const version = fileNameWithoutExt.slice(fileNameWithoutExt.lastIndexOf('-') + 1) |
🧰 Tools
🪛 eslint
[error] 126-126: Replace "release-notes")·&&·dir[1]·===·"/blog"
with 'release-notes')·&&·dir[1]·===·'/blog'
(prettier/prettier)
[error] 127-127: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 127-127: Insert ;
(prettier/prettier)
[error] 129-129: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 129-129: Identifier 'fileName_without_extension' is not in camel case.
(camelcase)
[error] 129-129: Replace "-")·+·1)
with '-')·+·1);
(prettier/prettier)
it('throws an error if the front matter cannot be parsed', async () => { | ||
await fs.writeFile(join(tempDir, 'docs', 'invalid.mdx'), '---\ninvalid front matter\n---\nContent'); | ||
|
||
let error; | ||
try { | ||
await buildPostList(postDirectories, tempDir, writeFilePath); | ||
} catch (err) { | ||
error = err; | ||
} | ||
|
||
expect(error).toBeDefined(); | ||
expect(error.message).toMatch(/Error while building post list/); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Simplify error handling tests using Jest's expect().rejects
The current try-catch pattern is verbose. Consider using Jest's built-in utilities for testing rejected promises.
- let error;
- try {
- await buildPostList(postDirectories, tempDir, writeFilePath);
- } catch (err) {
- error = err;
- }
-
- expect(error).toBeDefined();
- expect(error.message).toMatch(/Error while building post list/);
+ await expect(buildPostList(postDirectories, tempDir, writeFilePath))
+ .rejects
+ .toThrow(/Error while building post list/);
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('throws an error if the front matter cannot be parsed', async () => { | |
await fs.writeFile(join(tempDir, 'docs', 'invalid.mdx'), '---\ninvalid front matter\n---\nContent'); | |
let error; | |
try { | |
await buildPostList(postDirectories, tempDir, writeFilePath); | |
} catch (err) { | |
error = err; | |
} | |
expect(error).toBeDefined(); | |
expect(error.message).toMatch(/Error while building post list/); | |
}); | |
it('throws an error if the front matter cannot be parsed', async () => { | |
await fs.writeFile(join(tempDir, 'docs', 'invalid.mdx'), '---\ninvalid front matter\n---\nContent'); | |
await expect(buildPostList(postDirectories, tempDir, writeFilePath)) | |
.rejects | |
.toThrow(/Error while building post list/); | |
}); |
🧰 Tools
🪛 eslint
[error] 157-157: 'it' is not defined.
(no-undef)
it('builds a post list and writes the result to a file', async () => { | ||
await buildPostList(postDirectories, tempDir, writeFilePath); | ||
|
||
const outputExists = await fs.pathExists(writeFilePath); | ||
expect(outputExists).toBe(true); | ||
|
||
const output = JSON.parse(await fs.readFile(writeFilePath, 'utf-8')); | ||
console.log(output); | ||
|
||
expect(output).toHaveProperty('docs'); | ||
expect(output).toHaveProperty('blog'); | ||
expect(output).toHaveProperty('about'); | ||
expect(output).toHaveProperty('docsTree'); | ||
|
||
const blogEntry = output.blog.find(item => item.slug === '/blog/release-notes-2.1.0'); | ||
expect(blogEntry).toBeDefined(); | ||
expect(blogEntry.title).toBe('Release Notes 2.1.0'); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Remove debug logs and enhance assertions
The basic functionality test is good but could be improved:
- Remove
console.log
statements used for debugging - Add more specific assertions for the output structure
const output = JSON.parse(await fs.readFile(writeFilePath, 'utf-8'));
-console.log(output);
+expect(output).toMatchObject({
+ docs: expect.any(Array),
+ blog: expect.any(Array),
+ about: expect.any(Array),
+ docsTree: expect.any(Object)
+});
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('builds a post list and writes the result to a file', async () => { | |
await buildPostList(postDirectories, tempDir, writeFilePath); | |
const outputExists = await fs.pathExists(writeFilePath); | |
expect(outputExists).toBe(true); | |
const output = JSON.parse(await fs.readFile(writeFilePath, 'utf-8')); | |
console.log(output); | |
expect(output).toHaveProperty('docs'); | |
expect(output).toHaveProperty('blog'); | |
expect(output).toHaveProperty('about'); | |
expect(output).toHaveProperty('docsTree'); | |
const blogEntry = output.blog.find(item => item.slug === '/blog/release-notes-2.1.0'); | |
expect(blogEntry).toBeDefined(); | |
expect(blogEntry.title).toBe('Release Notes 2.1.0'); | |
}); | |
it('builds a post list and writes the result to a file', async () => { | |
await buildPostList(postDirectories, tempDir, writeFilePath); | |
const outputExists = await fs.pathExists(writeFilePath); | |
expect(outputExists).toBe(true); | |
const output = JSON.parse(await fs.readFile(writeFilePath, 'utf-8')); | |
expect(output).toMatchObject({ | |
docs: expect.any(Array), | |
blog: expect.any(Array), | |
about: expect.any(Array), | |
docsTree: expect.any(Object) | |
}); | |
expect(output).toHaveProperty('docs'); | |
expect(output).toHaveProperty('blog'); | |
expect(output).toHaveProperty('about'); | |
expect(output).toHaveProperty('docsTree'); | |
const blogEntry = output.blog.find(item => item.slug === '/blog/release-notes-2.1.0'); | |
expect(blogEntry).toBeDefined(); | |
expect(blogEntry.title).toBe('Release Notes 2.1.0'); | |
}); |
🧰 Tools
🪛 eslint
[error] 38-38: 'it' is not defined.
(no-undef)
[error] 52-52: Replace item
with (item)
(prettier/prettier)
This script adds tests for build-post-list.js script
Summary by CodeRabbit
New Features
buildPostList
andslugifyToC
functions.Bug Fixes
Documentation