Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

build(cmake): Extract CMake project name and version from package.json. #45

Merged
merged 6 commits into from
Dec 29, 2024

Conversation

junhaoliao
Copy link
Member

@junhaoliao junhaoliao commented Dec 27, 2024

Description

  1. Extract CMake project name and version from package.json.

Validation performed

Positive test

  1. Ran task in the project root.
  2. Under the project root, cd build/clp-ffi-js.
  3. Ran cmake -LAH | grep -B 1 CLP_FFI_JS and saw below in the output:
    ...
    // The name of the project parsed from `package.json`.
    CLP_FFI_JS_PROJECT_NAME:STRING=clp-ffi-js
    --
    // The version of the project parsed from `package.json`.
    CLP_FFI_JS_VERSION:STRING=0.3.1
    
  4. Compare that with the one in package.json and found no discrepancy.

Negative test

  1. Removed line "version": "0.3.1", from package.json.
  2. Repeat above positive test steps 1-3 and saw
    ...
    // The name of the project parsed from `package.json`.
    CLP_FFI_JS_PROJECT_NAME:STRING=clp-ffi-js
    --
    // Use a placeholder version.
    CLP_FFI_JS_VERSION:STRING=0.0.0
    

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Project name and version are now dynamically extracted from package.json, enhancing configurability.
  • Bug Fixes
    • Improved handling of project name and version defaults if not specified in package.json.
  • Chores
    • Updated build configurations to ensure correct toolchain usage for Emscripten builds.

Copy link

coderabbitai bot commented Dec 27, 2024

Warning

Rate limit exceeded

@junhaoliao has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between eae6c3e and 319d74c.

📒 Files selected for processing (1)
  • CMakeLists.txt (1 hunks)

Walkthrough

The pull request modifies the CMakeLists.txt file to dynamically extract the project name and version from the package.json file. By using file(READ ...) and MATCHES commands, the build system can now parse the project's name and version from the JSON configuration. This approach allows for more flexible project configuration, reducing hardcoded values and improving maintainability. The CMAKE_TOOLCHAIN_FILE is also conditionally set to ensure proper Emscripten build configuration.

Changes

File Change Summary
CMakeLists.txt - Dynamically extract project name from package.json
- Dynamically extract project version from package.json
- Conditionally set CMAKE_TOOLCHAIN_FILE for Emscripten builds

Possibly related PRs

Suggested reviewers

  • kirkrodrigues

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
CMakeLists.txt (1)

14-23: Improve JSON parsing robustness

The current regex patterns for extracting name and version are too simplistic and might fail with valid JSON formats. Consider:

  1. Multiple spaces or tabs between tokens
  2. Newlines between quotes
  3. Escaped quotes within values
-if(${PACKAGE_JSON_CONTENT} MATCHES "\"name\":[ ]*\"([^\"]+)\"")
+if(${PACKAGE_JSON_CONTENT} MATCHES "\"name\"[[:space:]]*:[[:space:]]*\"([^\"\\]*(\\.[^\"\\]*)*)\""

Alternatively, consider using a proper JSON parser like jq or Python's json module through execute_process.

Also applies to: 24-33

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between beff6ae and 4748c01.

📒 Files selected for processing (1)
  • CMakeLists.txt (1 hunks)
🔇 Additional comments (1)
CMakeLists.txt (1)

36-40: 🛠️ Refactor suggestion

Quote project name and validate version format

  1. The project name should be quoted to handle names containing spaces
  2. Consider validating the version format to ensure it follows semantic versioning
 project(
-    ${CLP_FFI_JS_PROJECT_NAME}
+    "${CLP_FFI_JS_PROJECT_NAME}"
     LANGUAGES
         C
         CXX
     VERSION "${CLP_FFI_JS_VERSION}"
 )

Run this script to verify the version format:

CMakeLists.txt Outdated
@@ -9,12 +9,35 @@ Emscripten.cmake"
)
endif()

# Extract the project name & version from package.json
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/package.json" PACKAGE_JSON_CONTENT)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for package.json read operation

The file(READ ...) command doesn't verify if the file exists or is readable. Consider adding error handling:

-file(READ "${CMAKE_CURRENT_SOURCE_DIR}/package.json" PACKAGE_JSON_CONTENT)
+if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/package.json")
+    file(READ "${CMAKE_CURRENT_SOURCE_DIR}/package.json" PACKAGE_JSON_CONTENT)
+else()
+    message(FATAL_ERROR "package.json not found in ${CMAKE_CURRENT_SOURCE_DIR}")
+endif()
📝 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.

Suggested change
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/package.json" PACKAGE_JSON_CONTENT)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/package.json")
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/package.json" PACKAGE_JSON_CONTENT)
else()
message(FATAL_ERROR "package.json not found in ${CMAKE_CURRENT_SOURCE_DIR}")
endif()

@junhaoliao
Copy link
Member Author

We could also have used string(JSON ...) but that is

Added in version 3.19.

We're currently enforcing cmake_minimum_required(VERSION 3.16) and upgrading that would require developer who use Ubuntu Focal (20.04) to install cmake from non-Ubuntu-apt sources, which is non-ideal.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
CMakeLists.txt (3)

18-27: Consider using a more robust JSON parsing pattern

While the current regex works for basic JSON, it might fail with complex JSON structures containing nested objects or arrays. Consider a more robust pattern that:

  • Handles whitespace more precisely
  • Accounts for possible commas and line endings
  • Considers the position of the "name" field
-if(${PACKAGE_JSON_CONTENT} MATCHES "\"name\":[ ]*\"([^\"]+)\"")
+if(${PACKAGE_JSON_CONTENT} MATCHES "\"name\"[ \t]*:[ \t]*\"([^\"]+)\"[ \t]*[,}]")

28-37: Add semantic version validation

The current implementation accepts any string as a version. Consider adding validation for semantic versioning format (MAJOR.MINOR.PATCH).

-if(${PACKAGE_JSON_CONTENT} MATCHES "\"version\":[ \t]*\"([^\"]+)\"")
+if(${PACKAGE_JSON_CONTENT} MATCHES "\"version\":[ \t]*\"(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?)\"[ \t]*[,}]")

Also, consider adding a message when falling back to the default version:

 else()
+    message(WARNING "Failed to extract version from package.json. Using default version 0.0.0")
     set(CLP_FFI_JS_VERSION "0.0.0" CACHE STRING "Use a placeholder version." FORCE)
 endif()

39-44: Quote the project name parameter

While the current project name doesn't contain spaces, it's good practice to quote it for consistency and future-proofing.

 project(
-    ${CLP_FFI_JS_PROJECT_NAME}
+    "${CLP_FFI_JS_PROJECT_NAME}"
     LANGUAGES
         C
         CXX
     VERSION "${CLP_FFI_JS_VERSION}"
 )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4748c01 and eae6c3e.

📒 Files selected for processing (1)
  • CMakeLists.txt (1 hunks)
🔇 Additional comments (2)
CMakeLists.txt (2)

12-17: LGTM: Proper error handling implemented

The implementation correctly checks for the existence of package.json before attempting to read it, with a clear error message.


12-44: Verify package.json contents

Let's verify the existence and content of package.json to ensure the build won't fail.

✅ Verification successful

Package.json exists with required fields - build configuration is valid

The package.json file exists and contains both the "name" and "version" fields that are required by the CMake configuration:

  • name: "clp-ffi-js"
  • version: "0.3.1"

These values will be properly extracted by the CMake regex patterns and set as the project name and version respectively.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify package.json exists and contains required fields

# Check if package.json exists and show its contents
if [ -f "package.json" ]; then
    echo "package.json found. Contents:"
    cat package.json
else
    echo "package.json not found!"
    exit 1
fi

# Extract and validate name and version
echo -e "\nValidating fields:"
jq -r '.name + " " + .version' package.json || echo "Failed to extract name/version"

Length of output: 1144

CMakeLists.txt Outdated Show resolved Hide resolved
CMakeLists.txt Outdated Show resolved Hide resolved
CMakeLists.txt Outdated Show resolved Hide resolved
CMakeLists.txt Outdated Show resolved Hide resolved
CMakeLists.txt Outdated Show resolved Hide resolved
CMakeLists.txt Outdated Show resolved Hide resolved
CMakeLists.txt Outdated Show resolved Hide resolved
Copy link
Member

@kirkrodrigues kirkrodrigues left a comment

Choose a reason for hiding this comment

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

For the PR title, how about:

build(cmake): Extract CMake project name and version from package.json.

It's subjective, but I think build is a more appropriate type since this change feels like more than just a chore.

@junhaoliao junhaoliao changed the title chore(build): Extract CMake project name and version from package.json. build(cmake): Extract CMake project name and version from package.json. Dec 29, 2024
@junhaoliao junhaoliao merged commit 476f3c7 into y-scope:main Dec 29, 2024
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants