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

Setup Script #2952

Open
wants to merge 16 commits into
base: develop-postgres
Choose a base branch
from

Conversation

prayanshchh
Copy link
Contributor

@prayanshchh prayanshchh commented Jan 26, 2025

What kind of change does this PR introduce?
created setup script for develop-postgres

Issue Number:
#2688

Snapshots/Videos:

Screencast.from.2025-01-29.08-47-05.webm
Screencast.from.2025-01-29.08-52-29.webm
Screencast.from.2025-01-29.08-54-58.webm

If relevant, did you update the documentation?

Summary

Does this PR introduce a breaking change?

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

Have you read the contributing guide?

Summary by CodeRabbit

  • New Features

    • Introduced an interactive setup process with a new command that streamlines the configuration of various application settings.
    • Added a new dependency for user input handling.
  • Improvements

    • Enhanced error handling during setup with robust backup and recovery mechanisms.
    • Updated existing dependencies for improved stability.
  • Tests

    • Expanded automated tests to ensure the reliability of the interactive configuration process and environment management, covering various setup functions and validations.

Copy link

coderabbitai bot commented Jan 26, 2025

Warning

Rate limit exceeded

@prayanshchh has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 58 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 0038171 and 33852b1.

📒 Files selected for processing (1)
  • src/setup/setup.ts (1 hunks)

Walkthrough

This update enhances the project’s setup and configuration process. The changes update package metadata by modifying dependencies and scripts. A new interactive setup script and error handling have been introduced for configuring environment variables via user prompts. Additionally, a new function to update and back up environment files has been added. Several comprehensive test suites and specifications have also been included to validate the new interactive setup functions and related utilities using the vitest framework.

Changes

File(s) Change Summary
package.json Updated dotenv version and added new dependency inquirer; introduced a new setup script (executes tsx setup.ts).
src/setup/setup.ts Added a comprehensive interactive setup script with multiple functions (e.g., promptInput, promptList, validateURL, validatePort, validateEmail, generateJwtSecret, checkEnvFile, initializeEnvFile, and various setup functions such as setCI, setNodeEnvironment, administratorEmail, apiSetup, cloudbeaverSetup, minioSetup, postgresSetup, setup) including error handling and backup management.
src/setup/updateEnvVariable.ts Introduced a new function to update environment variables in .env or .env_test; creates backups, updates file content and synchronizes with process.env, and restores the backup if an error occurs.
test/setup/administratorEmail.test.ts, test/setup/apiSetup.test.ts, test/setup/cloudbeaverSetup.test.ts, test/setup/minioSetup.test.ts, test/setup/postgresSetup.test.ts, test/setup/setNodeEnvironment.test.ts, test/setup/envSetup.spec.ts, test/setup/updateEnvVariable.test.ts, test/setup/setup.test.ts Added new test suites using vitest to validate functionality for interactive setup elements and utilities (administrator email prompting & validation, API configuration, CloudBeaver, Minio, PostgreSQL setups, node environment settings, environment file initialization, environment variable updates, and overall setup functionality).

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant I as Inquirer
    participant S as Setup Module
    participant E as Env File
    U->>I: Provide configuration input
    I->>S: Return user responses
    S->>E: Check and backup existing .env file
    S->>E: Update or add environment variables
    E-->>S: Confirm file update
    alt Error Occurs
        S->>S: Log error details (message, type, code, stack)
        S->>U: Output error message
        S->>S: Exit process with status 1
    else Successful Update
        S->>U: Finalize and complete setup
    end
Loading

Possibly related issues

Suggested reviewers

  • palisadoes

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.

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

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 425af24 and 922a84e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (10)
  • package.json (3 hunks)
  • setup.ts (1 hunks)
  • src/setup/updateEnvVariable.ts (1 hunks)
  • test/setup/administratorEmail.test.ts (1 hunks)
  • test/setup/apiSetup.test.ts (1 hunks)
  • test/setup/cloudbeaverSetup.test.ts (1 hunks)
  • test/setup/minioSetup.test.ts (1 hunks)
  • test/setup/postgresSetup.test.ts (1 hunks)
  • test/setup/setNodeEnviorment.test.ts (1 hunks)
  • vitest.config.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (7)
setup.ts (2)

18-30: Confirm deletion behavior before removing .env if no backup exists.

When originalEnvContent is null but .env exists, restoreEnvFile deletes .env. It might be safer to prompt the user for confirmation, especially if they intend to preserve a manually created .env. This helps prevent accidental data destruction.


64-85: 🧹 Nitpick (assertive)

Consider validating email input.

The administratorEmail function simply stores the input into API_ADMINISTRATOR_USER_EMAIL_ADDRESS. If a user enters invalid data, application behavior might break. Add basic validation (e.g., a regex check or additional prompt feedback) to ensure valid email formatting.

test/setup/administratorEmail.test.ts (1)

14-22: 🧹 Nitpick (assertive)

Test invalid inputs and error flows.

The test suite validates normal use (i.e., a valid email). Consider adding edge cases, such as empty strings or invalid emails, to ensure administratorEmail gracefully handles unexpected input.

test/setup/minioSetup.test.ts (1)

17-23: Verify the security implications of the MINIO_BROWSER setting.

The test uses "off" for MINIO_BROWSER. Ensure this aligns with security best practices for your deployment environment.

✅ Verification successful

MinIO browser configuration is properly implemented

The MINIO_BROWSER="off" setting in tests is appropriate and the overall implementation follows security best practices:

  • Configuration is documented and follows MinIO's official guidelines
  • Production environment prompts for the setting with clear documentation
  • Test configuration demonstrates secure usage without affecting production
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check MinIO documentation for recommended MINIO_BROWSER settings
curl -s https://min.io/docs/minio/linux/reference/minio-server/minio-server.html | grep -A 5 "MINIO_BROWSER"

Length of output: 108


Script:

#!/bin/bash
# Search for MINIO_BROWSER configurations and related documentation
echo "=== Searching for MINIO_BROWSER usage ==="
rg "MINIO_BROWSER" -B 2 -A 2

echo -e "\n=== Checking for MinIO configuration files ==="
fd -g "*minio*.{ts,js,json,md}"

echo -e "\n=== Looking for setup documentation ==="
fd -g "README.md" --exec grep -l -i "minio" {} \;

Length of output: 3036

test/setup/setNodeEnviorment.test.ts (2)

49-64: LGTM! Comprehensive error handling test.

The error handling test case is well-implemented with proper spy cleanup and error verification.


66-73: LGTM! Good coverage of unchanged environment case.

The test case properly verifies that NODE_ENV remains unchanged when not in test environment.

package.json (1)

95-96: LGTM! Setup script added correctly.

The setup script is properly configured to use tsx for TypeScript execution.

setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
vitest.config.ts Outdated Show resolved Hide resolved
src/setup/updateEnvVariable.ts Outdated Show resolved Hide resolved
test/setup/minioSetup.test.ts Outdated Show resolved Hide resolved
test/setup/apiSetup.test.ts Outdated Show resolved Hide resolved
test/setup/setNodeEnviorment.test.ts Outdated Show resolved Hide resolved
@prayanshchh
Copy link
Contributor Author

will fix failing tests and implement suggestions

@palisadoes
Copy link
Contributor

  1. The documentation says that a JWT needs to be generated. Is this included in your code?
  2. Why does the prompt for production or development come last? It should be first, because the environment variables will be set differently afterwards

@prayanshchh
Copy link
Contributor Author

  1. The documentation says that a JWT needs to be generated. Is this included in your code?
  2. Why does the prompt for production or development come last? It should be first, because the environment variables will be set differently afterwards

will implement both

@prayanshchh
Copy link
Contributor Author

prayanshchh commented Jan 28, 2025

  1. The documentation says that a JWT needs to be generated. Is this included in your code?
  2. Why does the prompt for production or development come last? It should be first, because the environment variables will be set differently afterwards

NODE_ENV is not the deciding factor as to whether test env should be configured or devcontainer, the variable CI is the deciding factor, if set false .env.devcontainer will be referred, if true, .env.ci will be referred to fill the .env.

image
image
image

I am planning to go with this approach, is this alright?

@palisadoes
Copy link
Contributor

@xoldd PTAL at this PR. It has implications for API setup using a script

@palisadoes
Copy link
Contributor

  1. The documentation says that a JWT needs to be generated. Is this included in your code?
  2. Why does the prompt for production or development come last? It should be first, because the environment variables will be set differently afterwards

NODE_ENV is not the deciding factor as to whether test env should be configured or devcontainer, the variable CI is the deciding factor, if set false .env.devcontainer will be referred, if true, .env.ci will be referred to fill the .env.

image image image

I am planning to go with this approach, is this alright?

  1. It looks that way. Please go ahead.
  2. What about the DB importation?

@prayanshchh
Copy link
Contributor Author

  1. The documentation says that a JWT needs to be generated. Is this included in your code?
  2. Why does the prompt for production or development come last? It should be first, because the environment variables will be set differently afterwards

NODE_ENV is not the deciding factor as to whether test env should be configured or devcontainer, the variable CI is the deciding factor, if set false .env.devcontainer will be referred, if true, .env.ci will be referred to fill the .env.
image image image
I am planning to go with this approach, is this alright?

  1. It looks that way. Please go ahead.
  2. What about the DB importation?

@gurramkarthiknetha is working on it, we talked on slack, he has started work on this

@palisadoes
Copy link
Contributor

@coderabbitai full review

Copy link

coderabbitai bot commented Jan 28, 2025

✅ Actions performed

Full review triggered.

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

♻️ Duplicate comments (1)
package.json (1)

18-18: ⚠️ Potential issue

Fix invalid package versions.

The specified versions are invalid and could cause installation failures:

Apply this fix:

-    "dotenv": "^16.4.7",
+    "dotenv": "^16.4.1",
-    "inquirer": "^12.3.2",
+    "inquirer": "^9.2.15",

Also applies to: 27-27

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 425af24 and 922a84e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (10)
  • package.json (3 hunks)
  • setup.ts (1 hunks)
  • src/setup/updateEnvVariable.ts (1 hunks)
  • test/setup/administratorEmail.test.ts (1 hunks)
  • test/setup/apiSetup.test.ts (1 hunks)
  • test/setup/cloudbeaverSetup.test.ts (1 hunks)
  • test/setup/minioSetup.test.ts (1 hunks)
  • test/setup/postgresSetup.test.ts (1 hunks)
  • test/setup/setNodeEnviorment.test.ts (1 hunks)
  • vitest.config.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Pull request workflow
vitest.config.ts

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.

package.json

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.

setup.ts

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.

🔇 Additional comments (9)
setup.ts (4)

10-16: Clarify backup method behavior.

While backupEnvFile correctly stores the original content of the .env file, you might consider logging or returning an explicit indicator to confirm whether a backup is performed or skipped (e.g., if the file doesn’t exist). This ensures downstream logic can be more transparent and conditional.

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.


32-44: Rename or document overwriting behavior in checkEnvFile.

Although it’s called checkEnvFile, the function overwrites the .env file with contents from envFiles/.env.devcontainer. Consider either renaming it (e.g., initializeEnvFile) or adding inline comments noting that it destructively replaces the existing .env.

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.


381-382: Review .env overwrite sequence.

checkEnvFile() is invoked immediately before backupEnvFile(), meaning the script first overwrites .env from the devcontainer file, then backs it up. If your intent is to preserve the user’s existing .env, consider reversing the call order or prompting for confirmation before overwriting.

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.


128-163: Ensure secret values are safely stored.

You’re storing credentials (e.g., API_JWT_SECRET, Minio secret key) directly in the .env file. While this is common in local development, consider using a secrets manager (e.g., Vault) or encryption at rest for production to reduce credential exposure risk.

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.

vitest.config.ts (1)

5-9: Be cautious with ignoring configuration errors.

Using ignoreConfigErrors: true can hide potential misconfigurations in TypeScript paths. Address any underlying config issues if possible, rather than skipping them. Also, note that the pipeline has flagged unauthorized changes to this file. If this file is deemed sensitive, you may need to add the ignore-sensitive-files-pr label or revert these changes to pass the checks.

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.

test/setup/minioSetup.test.ts (1)

15-37: Add validation tests for MinIO configuration.

The test suite should include validation for:

  • IP address format validation
  • Port conflict detection between API and Console ports
  • Root credential strength requirements

Example test case:

it("should detect port conflicts", async () => {
  const mockedAnswers = {
    ...mockedAnswers,
    MINIO_API_MAPPED_PORT: "8000",
    MINIO_CONSOLE_MAPPED_PORT: "8000", // Same port as API
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(mockedAnswers);
  
  await expect(minioSetup()).rejects.toThrow("Port conflict detected");
});
test/setup/setNodeEnviorment.test.ts (2)

1-74: Fix typo in filename: "setNodeEnviorment" should be "setNodeEnvironment".

The test file has a typo in its name that should be corrected to maintain consistency.

Run these commands to fix the filename:

#!/bin/bash
# Rename the file
git mv test/setup/setNodeEnviorment.test.ts test/setup/setNodeEnvironment.test.ts

# Update imports in other files
rg -l "setNodeEnviorment" | xargs sed -i 's/setNodeEnviorment/setNodeEnvironment/g'

1-74: Test implementation looks good!

The test suite is well-structured with comprehensive coverage of:

  • Happy path
  • Default values
  • Error handling
  • Environment-specific behavior
package.json (1)

95-96: Address pipeline failure for sensitive file changes.

The pipeline indicates unauthorized changes in sensitive files. The PR requires the 'ignore-sensitive-files-pr' label to proceed.

Run this script to identify sensitive file patterns:

✅ Verification successful

Development configuration scripts are legitimate and follow security best practices

The new scripts are standard development utilities:

  • setup: An interactive configuration tool with proper environment variable management
  • upgrade_drizzle_metadata: A standard database schema migration utility

Both follow security best practices including environment backup/restore functionality and interactive configuration of sensitive data.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for sensitive file patterns
rg -l "password|secret|credential|key" .

Length of output: 11322


Script:

#!/bin/bash
# Check setup.ts and related setup files
echo "=== setup.ts ==="
cat setup.ts 2>/dev/null || echo "File not found"
echo -e "\n=== src/setup/updateEnvVariable.ts ==="
cat src/setup/updateEnvVariable.ts 2>/dev/null || echo "File not found"
echo -e "\n=== Looking for drizzle setup files ==="
fd "drizzle.*\.(ts|js|json)" --type f --exec head -n 20 {}

Length of output: 13262

🧰 Tools
🪛 GitHub Actions: Pull request workflow

[error] Unauthorized changes detected in sensitive file. Requires 'ignore-sensitive-files-pr' label to proceed.

test/setup/administratorEmail.test.ts Outdated Show resolved Hide resolved
test/setup/postgresSetup.test.ts Outdated Show resolved Hide resolved
src/setup/updateEnvVariable.ts Outdated Show resolved Hide resolved
src/setup/updateEnvVariable.ts Outdated Show resolved Hide resolved
test/setup/cloudbeaverSetup.test.ts Outdated Show resolved Hide resolved
test/setup/apiSetup.test.ts Outdated Show resolved Hide resolved
@prayanshchh
Copy link
Contributor Author

sir this isn't ready as of moment, I have implemented you requirements, just fixing code_quality issues, then I can look at suggestions all together

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

codecov bot commented Jan 28, 2025

Codecov Report

Attention: Patch coverage is 80.20833% with 95 lines in your changes missing coverage. Please review.

Project coverage is 40.28%. Comparing base (8dca2ac) to head (33852b1).
Report is 2 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
src/setup/setup.ts 80.73% 84 Missing ⚠️
setup.ts 0.00% 10 Missing ⚠️
src/setup/updateEnvVariable.ts 97.05% 1 Missing ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #2952      +/-   ##
====================================================
+ Coverage             39.71%   40.28%   +0.57%     
====================================================
  Files                   455      458       +3     
  Lines                 33553    34033     +480     
  Branches                407      444      +37     
====================================================
+ Hits                  13324    13709     +385     
- Misses                20229    20324      +95     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

♻️ Duplicate comments (3)
test/setup/cloudbeaverSetup.test.ts (1)

15-45: 🛠️ Refactor suggestion

Add test cases for validation and error scenarios.

The current test only covers the happy path. For security-critical configuration like CloudBeaver, we need additional test cases.

Add these test cases:

it("should validate admin password strength", async () => {
  const weakPasswordAnswers = {
    CLOUDBEAVER_ADMIN_PASSWORD: "weak"
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(weakPasswordAnswers);
  
  await expect(cloudbeaverSetup()).rejects.toThrow(
    "Password must be at least 8 characters"
  );
});

it("should validate server URL format", async () => {
  const invalidUrlAnswers = {
    CLOUDBEAVER_SERVER_URL: "invalid-url"
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(invalidUrlAnswers);
  
  await expect(cloudbeaverSetup()).rejects.toThrow(
    "Invalid server URL format"
  );
});

it("should validate port range", async () => {
  const invalidPortAnswers = {
    CLOUDBEAVER_MAPPED_PORT: "999999"
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(invalidPortAnswers);
  
  await expect(cloudbeaverSetup()).rejects.toThrow(
    "Port must be between 1 and 65535"
  );
});
test/setup/apiSetup.test.ts (1)

15-77: 🛠️ Refactor suggestion

Add security validation tests for critical configurations.

While the test covers all environment variables, it lacks validation for security-critical fields like JWT secrets and database credentials.

Add these security validation tests:

it("should validate JWT secret strength", async () => {
  const weakJwtAnswers = {
    API_JWT_SECRET: "weak"
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(weakJwtAnswers);
  await expect(apiSetup()).rejects.toThrow("JWT secret too weak");
});

it("should validate database credentials", async () => {
  const weakDbAnswers = {
    API_POSTGRES_PASSWORD: "weak"
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(weakDbAnswers);
  await expect(apiSetup()).rejects.toThrow("Database password too weak");
});

it("should validate URL formats", async () => {
  const invalidUrlAnswers = {
    API_BASE_URL: "invalid-url"
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(invalidUrlAnswers);
  await expect(apiSetup()).rejects.toThrow("Invalid URL format");
});
package.json (1)

18-18: ⚠️ Potential issue

Fix invalid package versions.

The specified versions appear to be invalid:

Apply this diff to fix the versions:

-    "dotenv": "^16.4.7",
+    "dotenv": "^16.4.1",
-    "inquirer": "^12.3.2",
+    "inquirer": "^9.2.15",

Also applies to: 27-27

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 922a84e and 06de1a1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (10)
  • package.json (4 hunks)
  • setup.ts (1 hunks)
  • src/setup.ts (1 hunks)
  • src/setup/updateEnvVariable.ts (1 hunks)
  • test/setup/administratorEmail.test.ts (1 hunks)
  • test/setup/apiSetup.test.ts (1 hunks)
  • test/setup/cloudbeaverSetup.test.ts (1 hunks)
  • test/setup/minioSetup.test.ts (1 hunks)
  • test/setup/postgresSetup.test.ts (1 hunks)
  • test/setup/setNodeEnvironment.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (5)
src/setup/updateEnvVariable.ts (1)

23-25: Well done addressing potential ReDoS in regex.

Escaping dynamic variables in the pattern helps prevent malicious strings from causing performance issues. This is a secure approach.

src/setup.ts (1)

50-57: Ensure source env files exist.

envFiles/.env.ci and envFiles/.env.devcontainer must exist prior to reading. Otherwise, this will throw an exception. Consider adding checks or fallback logic to handle missing files or prompting the user to confirm their presence.

setup.ts (1)

4-8: Great fallback approach upon errors.

Calling restoreEnvFile() before exiting ensures the user’s original .env file remains intact if setup fails. This protects against partially-applied configurations. Nice job!

test/setup/minioSetup.test.ts (1)

15-39: Add validation tests for MinIO configuration.

The test suite should include:

  • IP address format validation
  • Port conflict detection between API and Console ports
  • Root credential strength requirements

Example test case:

it("should detect port conflicts", async () => {
  const mockedAnswers = {
    ...validAnswers,
    MINIO_API_MAPPED_PORT: "8000",
    MINIO_CONSOLE_MAPPED_PORT: "8000", // Same port as API
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(mockedAnswers);
  
  await expect(minioSetup()).rejects.toThrow("Port conflict detected");
});
test/setup/postgresSetup.test.ts (1)

15-38: Add test coverage for edge cases and error scenarios.

The current test only covers the happy path. Consider adding test cases for:

  • Invalid port numbers (e.g., negative, non-numeric, out of range)
  • Invalid IP addresses
  • Empty or whitespace-only values
  • Database name validation
  • Error handling when environment variable updates fail

Example test case:

it("should validate port number", async () => {
  const mockedAnswers = {
    ...mockedAnswers,
    POSTGRES_MAPPED_PORT: "-1", // Invalid port
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(mockedAnswers);
  
  await expect(postgresSetup()).rejects.toThrow("Invalid port number");
});

src/setup/updateEnvVariable.ts Outdated Show resolved Hide resolved
src/setup.ts Outdated Show resolved Hide resolved
src/setup.ts Outdated Show resolved Hide resolved
src/setup.ts Outdated Show resolved Hide resolved
src/setup.ts Outdated Show resolved Hide resolved
src/setup.ts Outdated Show resolved Hide resolved
test/setup/administratorEmail.test.ts Outdated Show resolved Hide resolved
test/setup/administratorEmail.test.ts Outdated Show resolved Hide resolved
test/setup/setNodeEnvironment.test.ts Outdated Show resolved Hide resolved
package.json Outdated Show resolved Hide resolved
@prayanshchh
Copy link
Contributor Author

prayanshchh commented Jan 28, 2025

will implement all the new suggestions, the old ones are not relevant as a lot of code was changed.

except this, does this fulfill your requirements now @palisadoes ?
waiting for the sample db work to finish, if this looks good, I can help with that

@prayanshchh
Copy link
Contributor Author

I forgot to add documentation for this, will do it tomorrow

@palisadoes palisadoes added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Jan 28, 2025
@palisadoes
Copy link
Contributor

  1. You need to update the video. You said the prod/dev question would come first.
  2. What happens when non defaults are selected?
  3. When is the .env file updated? It needs to be only at the very end.
  4. What happens if a .env file is already discovered?

@prayanshchh
Copy link
Contributor Author

  1. I have updated and uploaded three videos
  2. the video shows how the script handles non-defaults
  3. presently we update env file as the user enters the values, I have implemented backup and restoring env, so if ctrl+c is hit then env goes back to its previous state, is this good?
  4. I will add this functionality

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

@prayanshchh
Copy link
Contributor Author

  1. Can you move src/setup.ts to src/setup and write tests for it?
  2. We need to have complete coverage. There has been a history of poor setup experiences in the repo

yes sir, the tests are already present I will try and bring patch to 100%

Copy link

github-actions bot commented Feb 2, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

src/setup/setup.ts Fixed Show fixed Hide fixed
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: 5

🔭 Outside diff range comments (1)
test/setup/envSetup.spec.ts (1)

1-68: Enhance test coverage with error scenarios and edge cases.

The test suite should include additional test cases:

  1. Error handling when file operations fail
  2. Edge cases for file content parsing
  3. Invalid environment file formats

Add these test cases:

it("should handle file read errors", async () => {
  vi.spyOn(inquirer, "prompt").mockResolvedValue({ CI: "false" });
  await setCI();
  vi.spyOn(fs, "readFileSync").mockImplementation(() => {
    throw new Error("Read failed");
  });
  
  await expect(initializeEnvFile()).rejects.toThrow("Read failed");
});

it("should handle invalid env file format", async () => {
  vi.spyOn(inquirer, "prompt").mockResolvedValue({ CI: "false" });
  await setCI();
  vi.spyOn(fs, "readFileSync").mockReturnValue("invalid=format=value");
  
  await expect(initializeEnvFile()).rejects.toThrow();
});
♻️ Duplicate comments (2)
test/setup/apiSetup.test.ts (1)

20-82: 🛠️ Refactor suggestion

Add security validation and edge case tests.

The test suite should include validation for security-critical configurations:

  1. JWT secret strength
  2. Database credentials
  3. SSL settings

Add these security validation tests:

it("should validate JWT secret strength", async () => {
  const weakJwtAnswers = {
    ...mockResponses[7],
    API_JWT_SECRET: "weak"
  };
  promptMock.mockResolvedValueOnce(weakJwtAnswers);
  await expect(apiSetup()).rejects.toThrow("JWT secret too weak");
});

it("should validate database credentials", async () => {
  const weakDbAnswers = {
    ...mockResponses[18],
    API_POSTGRES_PASSWORD: "weak"
  };
  promptMock.mockResolvedValueOnce(weakDbAnswers);
  await expect(apiSetup()).rejects.toThrow("Database password too weak");
});
package.json (1)

18-18: ⚠️ Potential issue

Fix invalid package versions.

The specified versions don't exist:

Apply this diff to fix the versions:

-    "dotenv": "^16.4.7",
+    "dotenv": "^16.4.1",
-    "inquirer": "^12.3.2",
+    "inquirer": "^9.2.15",

Also applies to: 27-27

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67f62aa and 4dd9878.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (11)
  • package.json (4 hunks)
  • setup.ts (1 hunks)
  • src/setup/setup.ts (1 hunks)
  • test/setup/administratorEmail.test.ts (1 hunks)
  • test/setup/apiSetup.test.ts (1 hunks)
  • test/setup/cloudbeaverSetup.test.ts (1 hunks)
  • test/setup/envSetup.spec.ts (1 hunks)
  • test/setup/minioSetup.test.ts (1 hunks)
  • test/setup/postgresSetup.test.ts (1 hunks)
  • test/setup/setNodeEnvironment.test.ts (1 hunks)
  • test/setup/updateEnvVariable.test.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
test/setup/setNodeEnvironment.test.ts (1)
Learnt from: prayanshchh
PR: PalisadoesFoundation/talawa-api#2952
File: test/setup/setNodeEnvironment.test.ts:14-46
Timestamp: 2025-01-29T15:09:03.936Z
Learning: When using inquirer's list type for input, validation is not needed as users can only select from predefined choices. The validate attribute is not applicable for list type in inquirer.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (7)
src/setup/setup.ts (1)

429-435: Review the logic referencing .env.backup.

The SIGINT handler restores from .env.backup if it exists, but there is no code in this file that actually creates .env.backup. If this behavior is intended, ensure that a backup is created in a preceding step or document how .env.backup should be generated.

test/setup/minioSetup.test.ts (1)

15-38: Add test cases for validation and error handling.

The current test only covers the happy path. Consider adding test cases for:

  1. Input validation (IP addresses, ports, credentials)
  2. Error handling scenarios
  3. Edge cases
// Add these test cases
it("should validate credentials", async () => {
  const mockResponse = {
    MINIO_ROOT_PASSWORD: "weak" // Too weak
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(mockResponse);
  await expect(minioSetup()).rejects.toThrow(/Password too weak/);
});

it("should handle error scenarios", async () => {
  vi.spyOn(inquirer, "prompt").mockRejectedValueOnce(new Error("Prompt failed"));
  await expect(minioSetup()).rejects.toThrow("Prompt failed");
});
test/setup/postgresSetup.test.ts (1)

15-38: Add comprehensive test coverage for PostgreSQL setup.

The current test only covers the happy path. Consider adding:

  1. Order verification for configuration prompts
  2. Validation for all required PostgreSQL variables
  3. Error handling scenarios
// Add these test cases
it("should prompt for configuration in the correct order", async () => {
  const promptMock = vi.spyOn(inquirer, "prompt");
  await postgresSetup();
  
  expect(promptMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
    name: "POSTGRES_DB"
  }));
  expect(promptMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
    name: "POSTGRES_PASSWORD"
  }));
});

it("should validate all required variables", async () => {
  const answers = await postgresSetup();
  ["POSTGRES_DB", "POSTGRES_PASSWORD", "POSTGRES_USER"].forEach(varName => {
    expect(answers[varName]).toBeDefined();
  });
});
test/setup/cloudbeaverSetup.test.ts (1)

15-45: Add security-focused test cases.

The current test only covers the happy path. For a security-critical tool like CloudBeaver, add test cases for:

  1. Password strength validation
  2. URL format and security validation
  3. Port range validation
// Add these test cases
it("should validate admin password strength", async () => {
  const mockResponse = {
    CLOUDBEAVER_ADMIN_PASSWORD: "weak"
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(mockResponse);
  await expect(cloudbeaverSetup()).rejects.toThrow(/Password too weak/);
});

it("should enforce HTTPS for server URL", async () => {
  const mockResponse = {
    CLOUDBEAVER_SERVER_URL: "http://internal-server"
  };
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce(mockResponse);
  await expect(cloudbeaverSetup()).rejects.toThrow(/HTTPS required/);
});
test/setup/administratorEmail.test.ts (2)

27-32: Add email normalization test cases.

Consider adding test cases for email normalization to ensure consistent handling of:

  1. Mixed case emails
  2. Leading/trailing whitespace
  3. International domain names
it("should normalize email addresses", async () => {
  const mockEmail = "  [email protected]  ";
  vi.spyOn(inquirer, "prompt").mockResolvedValueOnce({
    API_ADMINISTRATOR_USER_EMAIL_ADDRESS: mockEmail,
  });
  const answers = await administratorEmail();
  expect(answers.API_ADMINISTRATOR_USER_EMAIL_ADDRESS).toBe("[email protected]");
});

34-42: Add test cases for error handling scenarios.

Consider adding test cases for:

  1. User cancellation of the prompt
  2. Network/IO errors during prompt
  3. Multiple invalid attempts before success
it("should handle user cancellation gracefully", async () => {
  vi.spyOn(inquirer, "prompt").mockRejectedValueOnce(new Error("User cancelled"));
  await expect(administratorEmail()).rejects.toThrow("User cancelled");
});
test/setup/updateEnvVariable.test.ts (1)

1-81: LGTM! Comprehensive test coverage.

The test suite thoroughly covers:

  • Updating existing variables
  • Adding new variables
  • Backup and restore functionality
  • Error handling
  • File creation scenarios

src/setup/setup.ts Outdated Show resolved Hide resolved
src/setup/setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
test/setup/setNodeEnvironment.test.ts Show resolved Hide resolved
test/setup/cloudbeaverSetup.test.ts Outdated Show resolved Hide resolved
@palisadoes
Copy link
Contributor

Please:

  1. fix the failing tests
  2. make coderabbit.ai approve your changes

Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

Please update the database JSON files

  1. They should be in a sample_data folder not scripts/
  2. Update src/utilities/loadSampleData.ts accordingly

@prayanshchh
Copy link
Contributor Author

alright sir I will make the changes, give me some time I have exams going on

@prayanshchh
Copy link
Contributor Author

sir I have one doubt on the working of setup script

previously setup script would start the development server hence importing sample data would make sense as database was up and running

but now that we setup the project using devcontainers, when npm run setup will be run, the database will not be up and hence if we give option to import sample data it won't be able to import, as postgres will start with devcontainer and not with setup script.

thoughts? @palisadoes

@prayanshchh
Copy link
Contributor Author

another thing we don't have a npm run import sample_data as we used to have in develop, is this okay?

@palisadoes
Copy link
Contributor

another thing we don't have a npm run import sample_data as we used to have in develop, is this okay?

Yes

@palisadoes
Copy link
Contributor

sir I have one doubt on the working of setup script

previously setup script would start the development server hence importing sample data would make sense as database was up and running

but now that we setup the project using devcontainers, when npm run setup will be run, the database will not be up and hence if we give option to import sample data it won't be able to import, as postgres will start with devcontainer and not with setup script.

thoughts? @palisadoes

In that case we'll need 2 scripts. One for setup and the other for DB importation.

@prayanshchh
Copy link
Contributor Author

sir I have one doubt on the working of setup script
previously setup script would start the development server hence importing sample data would make sense as database was up and running
but now that we setup the project using devcontainers, when npm run setup will be run, the database will not be up and hence if we give option to import sample data it won't be able to import, as postgres will start with devcontainer and not with setup script.
thoughts? @palisadoes

In that case we'll need 2 scripts. One for setup and the other for DB importation.

alright then I will create another script for db importation, the initial idea is to set the db importation and format db value in env as YES or NO, and when devcontainers setup is running we can run the db importation script, is this good?

I will continue in this PR

@palisadoes
Copy link
Contributor

OK

  1. It will also need to work with production
  2. There will need to be precautions that re-importation doesn't happen with each restart

@palisadoes
Copy link
Contributor

  1. Please fix the conflicting files
  2. The PR GitHub actions have been fixed.

@palisadoes
Copy link
Contributor

Please fix the conflicting files

@prayanshchh
Copy link
Contributor Author

increasing coverage for setup, will try to get this done by today

Copy link

github-actions bot commented Feb 6, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (5)
src/setup/setup.ts (2)

91-93: ⚠️ Potential issue

Incomplete string escaping: Backslash characters are not escaped in environment variable values.

The code replaces double quotes in environment variable values but does not escape backslash characters. This omission could lead to malformed .env files if any value contains backslashes.

Apply this diff to fix the issue:

 const safeContent = Object.entries(parsedEnv)
-    .map(([key, value]) => `${key}="${value.replace(/"/g, '\\"')}"`)
+    .map(([key, value]) => `${key}="${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`)
    .join("\n");

497-498: 🧹 Nitpick (assertive)

Provide a summary of configured settings for user confirmation.

After completing the setup, consider displaying a summary of the configuration settings (excluding sensitive values like passwords and secrets) to allow the user to confirm that the inputs are correct.

test/setup/cloudbeaverSetup.test.ts (1)

15-45: 🧹 Nitpick (assertive)

Enhance test coverage for edge cases and validation.

Currently, the test only covers the default scenario. Consider adding tests for invalid inputs to ensure that the cloudbeaverSetup function handles them correctly, such as:

  • Weak or invalid admin passwords.
  • Incorrect server URLs.
  • Invalid port numbers (e.g., out of range).
package.json (2)

18-18: ⚠️ Potential issue

Fix invalid package versions.

The specified versions appear to be incorrect:

Apply this diff to fix the versions:

-    "dotenv": "^16.4.7",
+    "dotenv": "^16.4.1",
-    "inquirer": "^12.4.1",
+    "inquirer": "^9.2.15",

Also applies to: 27-27


98-99: 🧹 Nitpick (assertive)

Consider grouping related scripts together.

The setup script should be grouped with other setup-related scripts like upgrade_drizzle_metadata for better organization.

Apply this diff to reorder the scripts:

     "start_production_server": "pnpm build_production && node ./dist/index.js",
     "start_production_server_with_debugger": "pnpm build_production && node --inspect=${API_DEBUGGER_HOST:-127.0.0.1}:${API_DEBUGGER_PORT:-9229} ./dist/index.js",
-    "setup": "tsx setup.ts",
-    "upgrade_drizzle_metadata": "drizzle-kit up"
+    "upgrade_drizzle_metadata": "drizzle-kit up",
+    "setup": "tsx setup.ts"
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4dd9878 and 303b872.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • package.json (2 hunks)
  • setup.ts (1 hunks)
  • src/setup/setup.ts (1 hunks)
  • test/setup/cloudbeaverSetup.test.ts (1 hunks)
  • test/setup/setup.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (3)
setup.ts (1)

1-11: LGTM!

The setup script correctly imports and invokes the setup function, handling errors appropriately.

test/setup/setup.test.ts (2)

8-13: LGTM! Good practice for environment handling.

The test setup correctly backs up and restores environment variables, ensuring test isolation.


15-65: Verify test coverage for edge cases.

While the test covers the happy path for CI=false, consider adding tests for:

  • Invalid email formats
  • Empty responses
  • Non-default configurations

Would you like me to generate additional test cases for these scenarios?

src/setup/setup.ts Outdated Show resolved Hide resolved
test/setup/setup.test.ts Show resolved Hide resolved
Copy link

github-actions bot commented Feb 6, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

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

♻️ Duplicate comments (2)
src/setup/setup.ts (2)

3-3: ⚠️ Potential issue

Fix incorrect import and usage of abort from node:process.

The abort function is not exported from the node:process module. Importing it directly will cause an error. Instead, use process.exit(1); to terminate the process gracefully.

Apply this diff to correct the import and replace abort(); with process.exit(1);:

-import { abort } from "node:process";
+// Removed incorrect import of abort

// ... rest of the code

     console.error(err);
-    abort();
+    process.exit(1);

Also applies to lines: 107-107, 122-122, 137-137


418-503: 🧹 Nitpick (assertive)

Enhance test coverage for the setup flow, including error handling.

The setup function orchestrates prompts and environment file updates, but some branches, especially error handling paths (e.g., when the user interrupts the process), are not covered by tests. Consider adding tests to cover these scenarios to improve reliability.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 429-430: src/setup/setup.ts#L429-L430
Added lines #L429 - L430 were not covered by tests


[warning] 436-441: src/setup/setup.ts#L436-L441
Added lines #L436 - L441 were not covered by tests


[warning] 457-458: src/setup/setup.ts#L457-L458
Added lines #L457 - L458 were not covered by tests


[warning] 469-470: src/setup/setup.ts#L469-L470
Added lines #L469 - L470 were not covered by tests


[warning] 482-483: src/setup/setup.ts#L482-L483
Added lines #L482 - L483 were not covered by tests


[warning] 495-496: src/setup/setup.ts#L495-L496
Added lines #L495 - L496 were not covered by tests

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 303b872 and 0038171.

📒 Files selected for processing (1)
  • src/setup/setup.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/setup/setup.ts

[warning] 39-41: src/setup/setup.ts#L39-L41
Added lines #L39 - L41 were not covered by tests


[warning] 106-108: src/setup/setup.ts#L106-L108
Added lines #L106 - L108 were not covered by tests


[warning] 121-123: src/setup/setup.ts#L121-L123
Added lines #L121 - L123 were not covered by tests


[warning] 136-138: src/setup/setup.ts#L136-L138
Added lines #L136 - L138 were not covered by tests


[warning] 191-196: src/setup/setup.ts#L191-L196
Added lines #L191 - L196 were not covered by tests


[warning] 339-343: src/setup/setup.ts#L339-L343
Added lines #L339 - L343 were not covered by tests


[warning] 345-350: src/setup/setup.ts#L345-L350
Added lines #L345 - L350 were not covered by tests


[warning] 352-356: src/setup/setup.ts#L352-L356
Added lines #L352 - L356 were not covered by tests


[warning] 358-364: src/setup/setup.ts#L358-L364
Added lines #L358 - L364 were not covered by tests


[warning] 389-393: src/setup/setup.ts#L389-L393
Added lines #L389 - L393 were not covered by tests


[warning] 395-401: src/setup/setup.ts#L395-L401
Added lines #L395 - L401 were not covered by tests


[warning] 429-430: src/setup/setup.ts#L429-L430
Added lines #L429 - L430 were not covered by tests


[warning] 436-441: src/setup/setup.ts#L436-L441
Added lines #L436 - L441 were not covered by tests


[warning] 457-458: src/setup/setup.ts#L457-L458
Added lines #L457 - L458 were not covered by tests


[warning] 469-470: src/setup/setup.ts#L469-L470
Added lines #L469 - L470 were not covered by tests


[warning] 482-483: src/setup/setup.ts#L482-L483
Added lines #L482 - L483 were not covered by tests


[warning] 495-496: src/setup/setup.ts#L495-L496
Added lines #L495 - L496 were not covered by tests

src/setup/setup.ts Show resolved Hide resolved
src/setup/setup.ts Outdated Show resolved Hide resolved
src/setup/setup.ts Outdated Show resolved Hide resolved
src/setup/setup.ts Show resolved Hide resolved
Copy link

github-actions bot commented Feb 6, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants