-
-
Notifications
You must be signed in to change notification settings - Fork 1k
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
base: develop-postgres
Are you sure you want to change the base?
Setup Script #2952
Conversation
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 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. 📒 Files selected for processing (1)
WalkthroughThis 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
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
Possibly related issues
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
Documentation and Community
|
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
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: 15
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
⛔ 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
isnull
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 intoAPI_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.
will fix failing tests and implement suggestions |
|
will implement both |
I am planning to go with this approach, is this alright? |
@xoldd PTAL at this PR. It has implications for API setup using a script |
|
@gurramkarthiknetha is working on it, we talked on slack, he has started work on this |
@coderabbitai full review |
✅ Actions performedFull review triggered. |
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
♻️ Duplicate comments (1)
package.json (1)
18-18
:⚠️ Potential issueFix invalid package versions.
The specified versions are invalid and could cause installation failures:
[email protected]
: Latest version is 16.4.1[email protected]
: Latest version is 9.2.15Apply 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
⛔ 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 incheckEnvFile
.Although it’s called
checkEnvFile
, the function overwrites the.env
file with contents fromenvFiles/.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 beforebackupEnvFile()
, 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 theignore-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 managementupgrade_drizzle_metadata
: A standard database schema migration utilityBoth 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.
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 |
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
Codecov ReportAttention: Patch coverage is
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. |
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: 10
♻️ Duplicate comments (3)
test/setup/cloudbeaverSetup.test.ts (1)
15-45
: 🛠️ Refactor suggestionAdd 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 suggestionAdd 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 issueFix invalid package versions.
The specified versions appear to be invalid:
[email protected]
: Latest version is 16.4.1[email protected]
: Latest version is 9.2.15Apply 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
⛔ 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
andenvFiles/.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"); });
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 ? |
I forgot to add documentation for this, will do it tomorrow |
|
|
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
yes sir, the tests are already present I will try and bring patch to 100% |
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
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: 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:
- Error handling when file operations fail
- Edge cases for file content parsing
- 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 suggestionAdd security validation and edge case tests.
The test suite should include validation for security-critical configurations:
- JWT secret strength
- Database credentials
- 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 issueFix invalid package versions.
The specified versions don't exist:
[email protected]
doesn't exist (latest is 16.4.1)[email protected]
doesn't exist (latest is 9.2.15)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
⛔ 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:
- Input validation (IP addresses, ports, credentials)
- Error handling scenarios
- 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:
- Order verification for configuration prompts
- Validation for all required PostgreSQL variables
- 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:
- Password strength validation
- URL format and security validation
- 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:
- Mixed case emails
- Leading/trailing whitespace
- 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:
- User cancellation of the prompt
- Network/IO errors during prompt
- 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
Please:
|
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.
Please update the database JSON files
- They should be in a
sample_data
folder notscripts/
- Update
src/utilities/loadSampleData.ts
accordingly
alright sir I will make the changes, give me some time I have exams going on |
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 thoughts? @palisadoes |
another thing we don't have a |
Yes |
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 |
OK
|
|
Please fix the conflicting files |
increasing coverage for setup, will try to get this done by today |
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
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
♻️ Duplicate comments (5)
src/setup/setup.ts (2)
91-93
:⚠️ Potential issueIncomplete 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 issueFix invalid package versions.
The specified versions appear to be incorrect:
[email protected]
doesn't exist (latest is 16.4.1)[email protected]
doesn't exist (latest is 9.2.15)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 likeupgrade_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
⛔ 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?
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
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
♻️ Duplicate comments (2)
src/setup/setup.ts (2)
3-3
:⚠️ Potential issueFix incorrect import and usage of
abort
fromnode:process
.The
abort
function is not exported from thenode:process
module. Importing it directly will cause an error. Instead, useprocess.exit(1);
to terminate the process gracefully.Apply this diff to correct the import and replace
abort();
withprocess.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
📒 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
Our Pull Request Approval ProcessThanks for contributing! Testing Your CodeRemember, your PRs won't be reviewed until these criteria are met:
Our policies make our code better. ReviewersDo not assign reviewers. Our Queue Monitors will review your PR and assign them.
Reviewing Your CodeYour reviewer(s) will have the following roles:
CONTRIBUTING.mdRead our CONTRIBUTING.md file. Most importantly:
Other
|
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
Test Coverage
Other information
Have you read the contributing guide?
Summary by CodeRabbit
New Features
Improvements
Tests