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

Force module install on Mac #659

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

homapf
Copy link
Contributor

@homapf homapf commented Jul 26, 2024

Changes

  • On Mac, adding a step to make sure the native module is installed for the current platform.

Related Issues

On Mac, Unity is installed automatically with the right module.
But if Unity is already installed with the wrong module on the machine, it will run without installing the missing module.

Successful Workflow Run Link

PRs don't have access to secrets so you will need to provide a link to a successful run of the workflows from your own
repo.

  • I can look into running tests on our repo if really needed but our current setup doesn't allow it.

Checklist

  • Read the contribution guide and accept the
    code of conduct
  • Docs (If new inputs or outputs have been added or changes to behavior that should be documented. Please make a PR
    in the documentation repo)
  • Readme (updated or not needed)
  • Tests (added, updated or not needed)

Summary by CodeRabbit

  • New Features
    • Enhanced setup process for Mac by ensuring required modules are installed automatically based on build parameters.
  • Bug Fixes
    • Improved control flow in the setup method to prevent proceeding without necessary module installations.

Copy link

Cat Gif

@AndrewKahr
Copy link
Member

I'm slightly confused, does the main Unity Editor install function not install all the necessary modules already? It looks like the ensure function that's been added is doing the same install process but using the install-modules command instead.

@webbertakken
Copy link
Member

From what I can see, this installs Unity and the module twice if it wasn't already installed. Usually you'd expect ephemeral runners.

I'm not sure if this PR's solution to making sure the right module is installed in case of a non ephemeral runner is comprehensive enough. At the very least we must verify that this doesn't run the install twice for users that do not have this use case.

Copy link

coderabbitai bot commented Oct 10, 2024

📝 Walkthrough

Walkthrough

The changes introduce a new method, ensureRequiredModuleIsInstalled, to the SetupMac class in src/model/platform-setup/setup-mac.ts. This method is integrated into the existing setup method, ensuring that a required module is installed based on build parameters. It retrieves the Unity changeset for the specified editor version and constructs command-line arguments for installation via the Unity Hub executable. The control flow of the setup method is modified to depend on the successful installation of the required module before proceeding.

Changes

File Path Change Summary
src/model/platform-setup/setup-mac.ts Added method private static async ensureRequiredModuleIsInstalled(buildParameters: BuildParameters) to SetupMac class. Integrated this method into the setup method to ensure module installation based on build parameters.

Poem

In the land of code where rabbits play,
A new method hops in, brightening the day.
Ensuring modules are installed with care,
Unity's setup, now free from despair.
With each little change, our world grows wide,
Hooray for the updates, let joy be our guide! 🐇✨


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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 461ecf7 and 5db0bb5.

⛔ Files ignored due to path filters (3)
  • dist/.DS_Store is excluded by !**/dist/**, !**/.DS_Store
  • dist/index.js is excluded by !**/dist/**
  • dist/index.js.map is excluded by !**/dist/**, !**/*.map
📒 Files selected for processing (1)
  • src/model/platform-setup/setup-mac.ts (2 hunks)
🧰 Additional context used
🪛 Biome
src/model/platform-setup/setup-mac.ts

[error] 138-138: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

Comment on lines +23 to +24
await SetupMac.ensureRequiredModuleIsInstalled(buildParameters);

Copy link

@coderabbitai coderabbitai bot Oct 10, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid redundant module installations by checking if the module is already installed

Unconditionally calling ensureRequiredModuleIsInstalled may lead to reinstalling modules that are already present, increasing setup time and potentially causing issues on non-ephemeral runners. Consider implementing a check to determine if the required module for the target platform is already installed before attempting installation.

Copy link

Choose a reason for hiding this comment

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

Good idea AI. How would one do this? I do not know of any way to get Unity Hub to expose what modules are currently installed other than asking to install them.

Docs can be found here: https://docs.unity3d.com/hub/manual/HubCLI.html

Copy link

Choose a reason for hiding this comment

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

@Rycieos, thanks for pointing that out. The script didn't work because the UNITY_VERSION and BUILD_TARGET environment variables were empty. We can address this by integrating the check directly into the ensureRequiredModuleIsInstalled method. Here's how you might modify the method to check if the required module is already installed before attempting installation:

private static async ensureRequiredModuleIsInstalled(buildParameters: BuildParameters) {
  const unityEditorPath = `/Applications/Unity/Hub/Editor/${buildParameters.editorVersion}/Unity.app/Contents`;
  let modulePath = '';

  switch (buildParameters.targetPlatform) {
    case 'iOS':
      modulePath = `${unityEditorPath}/PlaybackEngines/iOSSupport`;
      break;
    case 'Android':
      modulePath = `${unityEditorPath}/PlaybackEngines/AndroidPlayer`;
      break;
    case 'StandaloneOSX':
      modulePath = `${unityEditorPath}/PlaybackEngines/MacStandaloneSupport`;
      break;
    case 'WebGL':
      modulePath = `${unityEditorPath}/PlaybackEngines/WebGLSupport`;
      break;
    default:
      throw new Error(`Unsupported target platform: ${buildParameters.targetPlatform}.`);
  }

  if (fs.existsSync(modulePath)) {
    console.log(`Module for ${buildParameters.targetPlatform} is already installed.`);
  } else {
    console.log(`Module for ${buildParameters.targetPlatform} is not installed. Installing now...`);
    const unityChangeset = await getUnityChangeset(buildParameters.editorVersion);
    const moduleArguments = SetupMac.getModuleParametersForTargetPlatform(buildParameters.targetPlatform);

    const execArguments: string[] = [
      '--',
      '--headless',
      'install-modules',
      ...['--version', buildParameters.editorVersion],
      ...['--changeset', unityChangeset.changeset],
      ...moduleArguments,
      '--childModules',
    ];

    await exec(this.unityHubExecPath, execArguments, {
      silent: true,
      ignoreReturnCode: true,
    });
  }
}

By checking if the module's directory exists using fs.existsSync(modulePath), we can determine whether the required module is already installed. If the module is missing, the script proceeds to install it using Unity Hub CLI.

Let me know if this solution works for you!

(•ᴗ•)

🔗 Analysis chain

@Rycieos, you're correct that Unity Hub CLI doesn't provide a direct way to list installed modules. However, we can check if the required module's files exist in the Unity installation directory before attempting installation. Here's a script that performs this check:

This script checks if the module directory exists within the Unity installation. If the directory is not found, it proceeds to install the module using Unity Hub CLI. Integrating this check into the ensureRequiredModuleIsInstalled method should prevent redundant installations.

(•ᵕ•)

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the required Unity module is installed on macOS

UNITY_VERSION="${UNITY_VERSION}"
BUILD_TARGET="${BUILD_TARGET}"
UNITY_EDITOR_PATH="/Applications/Unity/Hub/Editor/${UNITY_VERSION}/Unity.app/Contents"
UNITY_HUB_EXEC_PATH="/Applications/Unity Hub.app/Contents/MacOS/Unity Hub"

case "${BUILD_TARGET}" in
  iOS)
    MODULE_PATH="${UNITY_EDITOR_PATH}/PlaybackEngines/iOSSupport"
    MODULE_NAME="ios"
    ;;
  Android)
    MODULE_PATH="${UNITY_EDITOR_PATH}/PlaybackEngines/AndroidPlayer"
    MODULE_NAME="android"
    ;;
  StandaloneOSX)
    MODULE_PATH="${UNITY_EDITOR_PATH}/PlaybackEngines/MacStandaloneSupport"
    MODULE_NAME="mac-il2cpp"
    ;;
  WebGL)
    MODULE_PATH="${UNITY_EDITOR_PATH}/PlaybackEngines/WebGLSupport"
    MODULE_NAME="webgl"
    ;;
  *)
    echo "Unsupported target platform: ${BUILD_TARGET}"
    exit 1
    ;;
esac

if [ -d "${MODULE_PATH}" ]; then
  echo "Module for ${BUILD_TARGET} is already installed."
else
  echo "Module for ${BUILD_TARGET} is not installed."
  # Proceed to install the module
  "${UNITY_HUB_EXEC_PATH}" -- --headless install-modules --version "${UNITY_VERSION}" --module "${MODULE_NAME}" --childModules
fi

Length of output: 286

'--childModules',
];

await exec(this.unityHubExecPath, execArguments, {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace 'this' with class name in static method

Using this in a static method can be confusing since this refers to the class, not an instance. Replace this.unityHubExecPath with SetupMac.unityHubExecPath for clarity.

Apply this diff to fix the issue:

-        await exec(this.unityHubExecPath, execArguments, {
+        await exec(SetupMac.unityHubExecPath, execArguments, {
📝 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
await exec(this.unityHubExecPath, execArguments, {
await exec(SetupMac.unityHubExecPath, execArguments, {
🧰 Tools
🪛 Biome

[error] 138-138: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

Comment on lines +138 to +141
await exec(this.unityHubExecPath, execArguments, {
silent: true,
ignoreReturnCode: true,
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle the error code from 'exec' to detect installation failures

Currently, the exec call ignores the return code and does not handle errors, which may lead to silent failures during module installation. Consider capturing the error code and throwing an error if the installation fails, similar to the approach used in installUnityHub.

Apply this diff to handle the error code:

-        await exec(SetupMac.unityHubExecPath, execArguments, {
-          silent: true,
-          ignoreReturnCode: true,
-        });
+        const errorCode = await exec(SetupMac.unityHubExecPath, execArguments, {
+          silent: true,
+          ignoreReturnCode: true,
+        });
+        if (errorCode) {
+          throw new Error(`There was an error installing the required module. See logs above for details.`);
+        }
📝 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
await exec(this.unityHubExecPath, execArguments, {
silent: true,
ignoreReturnCode: true,
});
const errorCode = await exec(SetupMac.unityHubExecPath, execArguments, {
silent: true,
ignoreReturnCode: true,
});
if (errorCode) {
throw new Error(`There was an error installing the required module. See logs above for details.`);
}
🧰 Tools
🪛 Biome

[error] 138-138: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

Copy link

@Rycieos Rycieos left a comment

Choose a reason for hiding this comment

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

Author of #615 here. Yes, this situation is encountered when on non-ephemeral runners.

The code in this PR is pretty much exactly my suggested code, and I have tested the Unity Hub commands in this scenario. Running unityhub -- --headless install-modules with a unity editor version that is already installed will not reinstall the editor, and if the module is already installed, it will exit with an error and not reinstall the module(s).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants