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

chore(packages): fix target dependencies and optimize build process #8608

Merged
merged 3 commits into from
Dec 22, 2024

Conversation

rahul-rocket
Copy link
Collaborator

@rahul-rocket rahul-rocket commented Dec 22, 2024

PR

Please note: we will close your PR without comment if you do not check the boxes above and provide ALL requested information.


Summary by CodeRabbit

  • New Features

    • Enhanced environment file generation with improved error handling and logging.
    • Introduced new build targets for environment generation and replacement in the UI configuration package.
  • Bug Fixes

    • Improved robustness of the environment setup process by ensuring target directories exist before file operations.
  • Chores

    • Streamlined build scripts for the UI configuration package to optimize the build process.
    • Simplified export structure in the project module for better organization.
    • Updated build commands in the UI core package for better dependency management.

Copy link
Contributor

coderabbitai bot commented Dec 22, 2024

Walkthrough

This pull request enhances the environment configuration and build process for the Gauzy project. Key modifications include updates to the .scripts/configure.ts for improved error handling and directory management, simplifications in the package.json build commands, and the introduction of new targets in packages/ui-config/project.json. Additionally, logging enhancements in packages/ui-config/scripts/replace-env-files.ts provide better visibility during environment file replacements. Overall, the changes aim to streamline the environment generation, build, and file replacement processes.

Changes

File Change Summary
.scripts/configure.ts Added existsSync and mkdirSync imports, improved directory and file handling, enhanced error logging
package.json Simplified build commands for ui-config package, removed redundant configuration steps
packages/ui-config/package.json Simplified production build script by removing cross-env and environment script execution
packages/ui-config/project.json Added new targets generate-env and replace-env, introduced dependencies for build process
packages/ui-config/scripts/replace-env-files.ts Added logging for environment file replacement, updated path resolution
packages/ui-core/shared/src/lib/project/index.ts Consolidated exports by removing specific project mutation exports and adding a single export for project-module
packages/ui-core/project.json Updated build target dependencies and commands for streamlined configuration management

Possibly related PRs

Suggested reviewers

  • evereq

Poem

🐰 Configs dancing, scripts so bright,
Environments leaping with pure delight!
Build commands trimmed, paths now clear,
A rabbit's magic touches here,
Smooth deployment, no more fright! 🚀


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9d110c6 and adc6e96.

📒 Files selected for processing (3)
  • package.json (1 hunks)
  • packages/ui-config/project.json (2 hunks)
  • packages/ui-core/project.json (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
🔇 Additional comments (6)
packages/ui-core/project.json (3)

13-19: LGTM: Build dependencies are properly configured

The build target correctly depends on:

  1. Other package builds (^build)
  2. Local config target

This ensures proper build order and configuration generation.


38-38: LGTM: Production configuration uses nx build properly

Using nx build instead of direct script execution is the correct approach as it ensures proper dependency tracking and configuration management.


41-41: LGTM: Development configuration mirrors production setup

The development configuration correctly mirrors the production setup, maintaining consistency in the build process.

packages/ui-config/project.json (3)

12-17: LGTM: Build properly depends on environment setup

The build target correctly depends on the replace-env target, ensuring environment files are properly configured before the build starts.


32-43: LGTM: Environment generation target is well structured

The generate-env target properly handles both production and development environments with appropriate commands.


46-51: LGTM: Replace-env dependencies are properly ordered

The target correctly depends on generate-env, ensuring proper sequencing of environment setup operations.


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@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: 3

🔭 Outside diff range comments (1)
.scripts/configure.ts (1)

Line range hint 383-401: Remove duplicated path resolution

The path resolution is unnecessarily duplicated in the success callback. The paths are already resolved earlier.

Simplify the callbacks by reusing the already resolved paths:

writeFile(envFilePath, envFileContent, (error) => {
  if (error) {
    console.error(`Error writing environment file: ${error}`);
  } else {
-   const envFilePath = path.resolve(`./packages/ui-config/src/lib/environments/${envFileDest}`);
    console.log(`Generated Angular environment file: ${envFilePath}`);
  }
});

writeFile(envFileOtherPath, envFileDestOtherContent, (error) => {
  if (error) {
    console.error(`Error writing environment file: ${error}`);
  } else {
-   const envFileOtherPath = path.resolve(`./packages/ui-config/src/lib/environments/${envFileDestOther}`);
    console.log(`Generated Second Empty Angular environment file: ${envFileOtherPath}`);
  }
});
🧹 Nitpick comments (2)
packages/ui-config/project.json (1)

32-46: Consider adding error handling for environment generation.

The generate-env target should include error handling to ensure the environment files are generated successfully.

Consider adding error checking:

 "generate-env": {
   "executor": "nx:run-commands",
   "options": {
-    "cwd": "."
+    "cwd": ".",
+    "parallel": false,
+    "exitOnError": true
   },
   "configurations": {
     "production": {
-      "commands": ["yarn run config:prod"]
+      "commands": [
+        "echo 'Generating production environment...'",
+        "yarn run config:prod || (echo 'Failed to generate production environment' && exit 1)"
+      ]
     },
packages/ui-config/scripts/replace-env-files.ts (1)

8-8: Consider using a logging library for better log management.

The current console.log statements could be enhanced with a proper logging library for better log levels and formatting.

Consider using winston or debug for more structured logging:

import * as winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console()
  ]
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5de0dad and 3f13f08.

📒 Files selected for processing (5)
  • .scripts/configure.ts (3 hunks)
  • package.json (1 hunks)
  • packages/ui-config/package.json (1 hunks)
  • packages/ui-config/project.json (2 hunks)
  • packages/ui-config/scripts/replace-env-files.ts (1 hunks)
🔇 Additional comments (5)
packages/ui-config/project.json (1)

12-17: LGTM: Build dependency chain is well structured.

The build target correctly depends on the replace-env target, ensuring environment files are properly set up before building.

packages/ui-config/package.json (1)

22-22: LGTM: Build script properly utilizes nx configuration.

The simplified build command correctly leverages the nx build system and configuration defined in project.json.

.scripts/configure.ts (2)

5-5: LGTM: Necessary imports added for directory handling

The addition of existsSync and mkdirSync imports is appropriate for the new directory handling functionality.


379-382: LGTM: Clean path resolution implementation

The use of path.resolve for constructing file paths is a good practice that ensures consistent path handling across different platforms.

package.json (1)

123-125: LGTM: Build command optimization

The build commands for ui-config have been streamlined by removing redundant config:dev calls. This is a good optimization that should improve build times.

Let's verify that the removed config:dev step isn't required elsewhere:

✅ Verification successful

LGTM: Build command optimization is safe

The removal of config:dev from ui-config build commands is safe. The search results show that:

  1. ui-config package builds do not depend on config:dev
  2. Other packages that depend on ui-config (like ui-core) reference the build commands directly
  3. The only config:dev dependency is in the start:gauzy:forever command which is unrelated to the build process
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if any other scripts depend on the config:dev step for ui-config
rg "yarn run config:dev.*build:package:ui-config" --type yaml --type json

Length of output: 75


Script:

#!/bin/bash
# Let's check for any references to config:dev in relation to ui-config more broadly
rg "config:dev.*ui-config|ui-config.*config:dev" --type yaml --type json -A 2

# Also check for any direct dependencies on config:dev in package.json
rg "config:dev" package.json -A 2

# Check if there are any workflow files that might reference these build steps
fd -e yml -e yaml . .github/workflows -x cat {}

Length of output: 69247


Script:

#!/bin/bash
# Let's check for any references to config:dev in build commands or dependencies
rg "config:dev.*build|build.*config:dev" package.json -A 2

# Also check for any direct dependencies between ui-config and config:dev
rg "ui-config.*config:dev|config:dev.*ui-config" package.json -A 2

# Check for any references to ui-config in the build scripts
rg "build:package:ui-config" package.json -A 2

Length of output: 4260

packages/ui-config/project.json Outdated Show resolved Hide resolved

const env = process.env['NODE_ENV'] || 'development';
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and environment argument parsing.

The script needs improvements in error handling and should handle the --environment argument passed from project.json.

Consider these improvements:

+ import { argv } from 'process';
+ 
+ // Parse environment argument
+ const args = argv.slice(2);
+ const envArg = args.find(arg => arg.startsWith('--environment='))?.split('=')[1];
+ 
- const env = process.env['NODE_ENV'] || 'development';
+ const env = envArg || process.env['NODE_ENV'] || 'development';
  console.log(`Current NODE_ENV: ${process.env['NODE_ENV']}`);

  if (env === 'production') {
    console.log('Replacing environment files for __dirname: ' + __dirname);
-   const sourceFile = path.join(path.resolve(__dirname, '../src/lib/environments'), 'environment.prod.ts');
-   const targetFile = path.join(path.resolve(__dirname, '../src/lib/environments'), 'environment.ts');
+   const envDir = path.resolve(__dirname, '../src/lib/environments');
+   
+   // Verify directory exists
+   if (!fs.existsSync(envDir)) {
+     console.error(`Environment directory not found: ${envDir}`);
+     process.exit(1);
+   }
+   
+   const sourceFile = path.join(envDir, 'environment.prod.ts');
+   const targetFile = path.join(envDir, 'environment.ts');
+   
+   // Verify source file exists
+   if (!fs.existsSync(sourceFile)) {
+     console.error(`Source file not found: ${sourceFile}`);
+     process.exit(1);
+   }

Also applies to: 14-16

Comment on lines +370 to +377
// Define the folder paths
const environmentsFolder = './packages/ui-config/src/lib/environments';

// Ensure the environments folder exists
if (!existsSync(environmentsFolder)) {
mkdirSync(environmentsFolder, { recursive: true });
console.log(`Created environments folder: ${environmentsFolder}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for directory creation

While the directory creation logic is good, it should include error handling for scenarios where directory creation fails.

Consider wrapping the directory creation in a try-catch block:

- if (!existsSync(environmentsFolder)) {
-   mkdirSync(environmentsFolder, { recursive: true });
-   console.log(`Created environments folder: ${environmentsFolder}`);
- }
+ if (!existsSync(environmentsFolder)) {
+   try {
+     mkdirSync(environmentsFolder, { recursive: true });
+     console.log(`Created environments folder: ${environmentsFolder}`);
+   } catch (error) {
+     console.error(`Error creating environments folder: ${error}`);
+     process.exit(1);
+   }
+ }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Define the folder paths
const environmentsFolder = './packages/ui-config/src/lib/environments';
// Ensure the environments folder exists
if (!existsSync(environmentsFolder)) {
mkdirSync(environmentsFolder, { recursive: true });
console.log(`Created environments folder: ${environmentsFolder}`);
}
// Define the folder paths
const environmentsFolder = './packages/ui-config/src/lib/environments';
// Ensure the environments folder exists
if (!existsSync(environmentsFolder)) {
try {
mkdirSync(environmentsFolder, { recursive: true });
console.log(`Created environments folder: ${environmentsFolder}`);
} catch (error) {
console.error(`Error creating environments folder: ${error}`);
process.exit(1);
}
}

Copy link

nx-cloud bot commented Dec 22, 2024

View your CI Pipeline Execution ↗ for commit adc6e96.

Command Status Duration Result
nx build desktop --base-href ./ ✅ Succeeded 1m 47s View ↗
nx build desktop-api --output-path=dist/apps/de... ✅ Succeeded 28s View ↗
nx run api:desktop-api ✅ Succeeded 1m 18s View ↗
nx run gauzy:desktop-ui --base-href ./ ✅ Succeeded 4m 52s View ↗
nx build desktop-ui-lib --configuration=develop... ✅ Succeeded 30s View ↗
nx build plugin-integration-wakatime ✅ Succeeded 4s View ↗
nx build desktop-lib ✅ Succeeded 6s View ↗
nx build desktop-window ✅ Succeeded 2s View ↗
Additional runs (32) ✅ Succeeded ... View ↗

☁️ Nx Cloud last updated this comment at 2024-12-22 10:31:33 UTC

@rahul-rocket rahul-rocket changed the title chore(ui-config): fix target dependencies and optimize build process chore(packages): fix target dependencies and optimize build process Dec 22, 2024
@rahul-rocket rahul-rocket merged commit b165252 into develop Dec 22, 2024
12 of 16 checks passed
@rahul-rocket rahul-rocket deleted the fix/ui-config-targets branch December 22, 2024 09:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant