Skip to content

Bug fix/LibGit2Sharp Lib downgrade#4103

Merged
Maheshkale447 merged 6 commits into
Releases/Official-Releasefrom
BugFix/GitLibDowngrade
Feb 13, 2025
Merged

Bug fix/LibGit2Sharp Lib downgrade#4103
Maheshkale447 merged 6 commits into
Releases/Official-Releasefrom
BugFix/GitLibDowngrade

Conversation

@GokulBothe99

@GokulBothe99 GokulBothe99 commented Feb 12, 2025

Copy link
Copy Markdown
Contributor

Thank you for your contribution.
Before submitting this PR, please make sure:

  • PR description and commit message should describe the changes done in this PR
  • Verify the PR is pointing to correct branch i.e. Release or Beta branch if the code fix is for specific release , else point it to master
  • Latest Code from master or specific release branch is merged to your branch
  • No unwanted\commented\junk code is included
  • No new warning upon build solution
  • Code Summary\Comments are added to my code which explains what my code is doing
  • Existing unit test cases are passed
  • New Unit tests are added for your development
  • Sanity Tests are successfully executed for New and Existing Functionality
  • Verify that changes are compatible with all relevant browsers and platforms.
  • After creating pull request there should not be any conflicts
  • Resolve all Codacy comments
  • Builds and checks are passed before PR is sent for review
  • Resolve code review comments
  • Update the Help Library document to match any feature changes

Summary by CodeRabbit

  • Chores
    • Updated dependency management by removing and downgrading package references to enhance compatibility and overall system stability.
  • Refactor
    • Streamlined source control operations, improving error handling and progress reporting for a smoother user experience.

@coderabbitai

coderabbitai Bot commented Feb 12, 2025

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request updates dependency management and refactors key methods in the project. The LibGit2Sharp package is removed, and the version for LibGit2Sharp.NativeBinaries is downgraded in the project file. In the source control module, several methods are refactored to modify existing options objects in place rather than returning new instances. These changes affect how fetch, pull, and clone operations are handled without altering the overall project structure.

Changes

File(s) Change Summary
Ginger/.../GingerCoreNET.csproj - Removed LibGit2Sharp package reference.
- Downgraded LibGit2Sharp.NativeBinaries from version 2.0.323 to 2.0.278.
- Removed various DLL/resource references.
Ginger/.../SourceControl/GITSourceControl.cs - Refactored methods to modify passed FetchOptions instead of returning new objects.
- Updated signatures for GetFetchOptions, GetFetchOptionsWithProgress, and related methods.
- Aligned option handling for pull and clone operations.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GIT as GITSourceControl
    participant FOpts as FetchOptions

    Client->>GIT: Call GetProject(...)/GetProjectWithProgress(...)
    alt With progress
      GIT->>FOpts: Update via GetFetchOptionsWithProgress(fetchOptions, progress, cancellation)
    else Without progress
      GIT->>FOpts: Update via GetFetchOptions(fetchOptions)
    end
    GIT->>Client: Return result
Loading

Possibly related PRs

  • Git dll issue fixed #3749: Addresses similar changes in package version management for LibGit2Sharp.NativeBinaries in the GingerCoreNET.csproj file.

Suggested reviewers

  • Maheshkale447

Poem

I'm a rabbit, swift and keen,
Hopping through the code so clean.
Dependencies pruned with a graceful twist,
Fetch options updated, you get the gist!
Code paths now dance to a refactored beat 🐰
Happy commits, may our patches always be sweet!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 58aeac3 and 4130af1.

📒 Files selected for processing (1)
  • Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs (7 hunks)

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 or @coderabbitai title 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.

@GokulBothe99
GokulBothe99 changed the base branch from master to Releases/Official-Release February 12, 2025 17:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 16

🔭 Outside diff range comments (12)
Ginger/GingerCoreNET/InputVariableRule/ProcessInputVariableRule.cs (1)

307-319: ⚠️ Potential issue

Fix bug in CheckIfValuesCanbecompared method.

There's a bug in the method where the same value (actual) is being parsed twice instead of parsing both actual and Expected parameters.

Apply this fix:

 private static bool CheckIfValuesCanbecompared(string actual, string Expected)
 {
     try
     {
         double.Parse(actual);
-        double.Parse(actual);
+        double.Parse(Expected);
         return true;
     }
     catch
     {
         return false;
     }
 }
Ginger/GingerCoreNET/Run/Platforms/PlatformsInfo/MobilePlatform.cs (2)

104-108: 🛠️ Refactor suggestion

Remove commented-out code.

This commented-out implementation of GetPlatformElementTypesData should be removed as it's no longer needed and the active implementation is working correctly.


133-137: 🛠️ Refactor suggestion

Remove commented-out code for List element operations.

The commented-out code for List element operations should be removed to maintain code cleanliness.

Ginger/Ginger/ALM/ALMConnectionPage.xaml.cs (1)

847-851: 🧹 Nitpick (assertive)

Remove unnecessary empty line.

The event handler implementation is correct, but there's an unnecessary empty line that can be removed.

 private void TokenCheckBox_Checked(object sender, RoutedEventArgs e)
 {
-
     PasswordLabel.Content = "Token";
 }
Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightDriver.cs (1)

1929-1958: 🧹 Nitpick (assertive)

Consider adding documentation for supported operations.

The list of supported browser element operations is comprehensive but lacks documentation explaining the purpose and requirements of each operation. Consider adding XML documentation to help developers understand when to use each operation.

+        /// <summary>
+        /// List of browser element operations supported by the Playwright driver.
+        /// Each operation represents a specific browser automation action.
+        /// </summary>
         private static readonly IEnumerable<ActBrowserElement.eControlAction> ActBrowserElementSupportedOperations =
         [
             ActBrowserElement.eControlAction.GotoURL,
Ginger/GingerCoreNET/Run/Platforms/PlatformsInfo/JavaPlatform.cs (2)

477-519: 🛠️ Refactor suggestion

Remove duplicate actions from Unknown element type list.

There are duplicate entries in the list of actions for Unknown element type:

  • SetValue appears on both lines 482 and 484
  • AsyncClick appears on both lines 477 and 501

Apply this diff to remove the duplicates:

 case eElementType.Unknown:
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.AsyncClick);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.Click);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.ClickXY);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.MouseClick);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.MousePressRelease);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.SetValue);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.GetValue);
-    javaPlatformElementActionslist.Add(ActUIElement.eElementAction.SetValue);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.SendKeys);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.SendKeyPressRelease);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.GetControlProperty);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.DoubleClick);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.GetSelectedNodeChildItems);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.ScrollDown);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.ScrollUp);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.ScrollLeft);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.ScrollRight);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.Select);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.AsyncSelect);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.SelectByIndex);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.GetItemCount);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.GetAllValues);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.GetValueByIndex);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.Toggle);
-    javaPlatformElementActionslist.Add(ActUIElement.eElementAction.AsyncClick);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.GetName);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.Switch);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.IsExist);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.CloseWindow);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.InitializeJEditorPane);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.JEditorPaneElementAction);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.SetDate);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.AcceptDialog);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.DismissDialog);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.GetDialogText);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.IsEnabled);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.IsVisible);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.IsMandatory);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.IsChecked);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.WinClick);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.winDoubleClick);
     javaPlatformElementActionslist.Add(ActUIElement.eElementAction.SetFocus);
     break;

264-266: 🧹 Nitpick (assertive)

Track the TODO for moving element type mapping to Java side.

The comment suggests an important architectural improvement to move the element type mapping logic to the Java side. This would improve separation of concerns and make the code more maintainable.

Would you like me to create an issue to track this technical debt? The issue would cover:

  1. Moving element type mapping logic to Java side
  2. Simplifying the payload to return element types directly
  3. Updating the C# code to handle the new payload format
Ginger/GingerCoreNET/Drivers/CoreDrivers/Mobile/Appium/GenericAppiumDriver.cs (3)

983-1027: 🧹 Nitpick (assertive)

Null-check potential
If the required capability (e.g., appPackage or bundleId) is not found, the error path simply sets act.Error. Consider a more explicit fallback or structured error messaging to guide debugging.


1032-1421: 🛠️ Refactor suggestion

Large switch statement
This method implements many device actions in a single place, making it long and harder to maintain. Consider extracting each action into a separate method or using a command pattern to improve readability and testability.


3808-4279: 🧹 Nitpick (assertive)

Grouping extensive device status methods
This large block of new methods (e.g., performance data, logs, screen recordings) greatly expands class responsibilities. Consider splitting into helper classes or partial classes for clarity and maintainability.

Ginger/GingerCoreCommon/GingerCoreCommon.csproj (2)

50-54: 🧹 Nitpick (assertive)

Review empty folder structure.

The project contains empty folders:

  • Repository/ExecLib/
  • Repository/ReportsLib/
  • RunLib/Common/

Consider removing these if they're no longer needed, or add a .gitkeep file if they're intended to be empty.


36-48: 💡 Verification agent

⚠️ Potential issue

🧩 Analysis chain

Remove duplicate LiteDB reference and verify package versions.

Issues found:

  1. LiteDB is referenced twice (PackageReference and direct Reference)
  2. Some package versions might need updates for compatibility with .NET 8.0

Remove the duplicate LiteDB reference:

-  <ItemGroup>
-    <Reference Include="LiteDB">
-      <HintPath>..\..\..\..\..\.nuget\packages\litedb\4.1.4\lib\net40\LiteDB.dll</HintPath>
-    </Reference>
-  </ItemGroup>

Please verify package compatibility:

Also applies to: 61-63


🏁 Script executed:

#!/bin/bash
# Check for latest stable versions of key packages
echo "Checking NuGet package versions..."
curl -s https://api.nuget.org/v3-flatcontainer/microsoft.codeanalysis/index.json | jq -r '.versions[]' | sort -V | tail -n 1
curl -s https://api.nuget.org/v3-flatcontainer/system.drawing.common/index.json | jq -r '.versions[]' | sort -V | tail -n 1

Length of output: 352


Action Required: Remove Duplicate LiteDB Reference and Recheck Dependency Versions

  • The codebase includes a duplicate LiteDB reference (both a modern PackageReference and an older direct Reference with a HintPath), which can lead to runtime conflicts. Please remove the redundant Reference:
    -  <ItemGroup>
    -    <Reference Include="LiteDB">
    -      <HintPath>..\..\..\..\..\.nuget\packages\litedb\4.1.4\lib\net40\LiteDB.dll</HintPath>
    -    </Reference>
    -  </ItemGroup>
  • The NuGet API check shows that later stable versions exist (e.g., Microsoft.CodeAnalysis at 4.12.0-3.final and System.Drawing.Common at 9.0.2). Confirm that your current versions (Microsoft.CodeAnalysis 3.7.0 and System.Drawing.Common 8.0.7) are intentionally locked for compatibility, or consider upgrading if possible.
🛑 Comments failed to post (16)
Ginger/Ginger/ALM/ALMConnectionPage.xaml.cs (1)

152-155: 🧹 Nitpick (assertive)

Consider making the token label update more concise and complete.

The current implementation only updates the label when UseToken is true. Consider using a ternary operator and handling both cases.

-            if (CurrentAlmConfigurations.UseToken)
-            {
-                PasswordLabel.Content = "Token";
-            }
+            PasswordLabel.Content = CurrentAlmConfigurations.UseToken ? "Token" : "Password";
📝 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.

            PasswordLabel.Content = CurrentAlmConfigurations.UseToken ? "Token" : "Password";
Ginger/GingerCoreNET/GingerCoreNET.csproj (1)

287-287: 💡 Verification agent

⚠️ Potential issue

🧩 Analysis chain

Potential version mismatch between LibGit2Sharp components.

The project has a direct DLL reference to LibGit2Sharp while using a downgraded version of LibGit2Sharp.NativeBinaries. This could lead to compatibility issues since these components are tightly coupled.

Let's verify the compatibility between these components:

Consider either:

  1. Removing the direct DLL reference and restoring the LibGit2Sharp NuGet package with a version compatible with NativeBinaries 2.0.278
  2. Or, if the DLL reference is necessary, ensure it's the correct version that works with NativeBinaries 2.0.278

Also applies to: 410-412


🏁 Script executed:

#!/bin/bash
# Description: Search for Git operations in the codebase that might be affected by this downgrade

# Search for Git operations using LibGit2Sharp
rg -l "LibGit2Sharp" | xargs rg "Repository\.|Clone\.|Checkout\.|Commit\.|Push\.|Pull\."

# Search for any error handling around Git operations
rg -l "LibGit2Sharp" | xargs rg "try.*catch.*LibGit2Sharp"

Length of output: 4818


Review Note – Investigate Inconsistent LibGit2Sharp Component Versions

The project now downgrades the LibGit2Sharp.NativeBinaries package to version 2.0.278 (line 287), but code (e.g. in GingerCoreNET/SourceControl/GITSourceControl.cs) still calls LibGit2Sharp APIs, suggesting that a direct DLL reference to LibGit2Sharp (not managed via NuGet) remains (as noted around lines 410–412 in GingerCoreNET.csproj). Since these components are tightly coupled, this mismatch might lead to runtime compatibility issues.

Action Items:

  • Confirm the DLL reference: Verify if the direct DLL reference to LibGit2Sharp in the csproj is still present; if so, check that its version is aligned with NativeBinaries 2.0.278.
  • Fix the inconsistency: Either remove the direct DLL reference and restore a NuGet-based reference for LibGit2Sharp using a version that benefits from automatic matching with NativeBinaries, or update the DLL reference to ensure it matches the downgraded NativeBinaries version.
Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/IBrowserTab.cs (1)

113-117: 🧹 Nitpick (assertive)

LGTM! The new browser control methods enhance functionality.

The new methods follow consistent async patterns and provide clear return types that indicate operation success.

Consider adding XML documentation comments to describe:

  • Parameters (e.g., urlPattern in SetBlockedURLAsync)
  • Return values (what constitutes success/failure)
  • Exceptions that might be thrown
Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/ActionHandlers/ActBrowserElementHandler.cs (3)

809-809: 🧹 Nitpick (assertive)

Fix typo in cast operator.

The ! operator is unnecessary as the cast will throw if _browser is null.

-await ((PlaywrightBrowserTab)_browser!.CurrentWindow.CurrentTab).StartCaptureNetworkLog(_act);
+await ((PlaywrightBrowserTab)_browser.CurrentWindow.CurrentTab).StartCaptureNetworkLog(_act);
📝 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.

                await ((PlaywrightBrowserTab)_browser.CurrentWindow.CurrentTab).StartCaptureNetworkLog(_act);

317-334: 🛠️ Refactor suggestion

Add script validation before injection.

Consider validating the JavaScript code before injection to prevent potential security issues.

 private async Task HandleInjectJS()
 {
     string script = _act.GetInputParamCalculatedValue("Value");
     if (string.IsNullOrEmpty(script))
     {
         _act.Error = "Error: Script value is empty";
         return;
     }
+    
+    // Basic validation to prevent obvious script injection
+    if (script.Contains("<script>") || script.Contains("</script>"))
+    {
+        _act.Error = "Error: Script contains potentially unsafe HTML tags";
+        return;
+    }
+    
     try
     {
         await _browser.CurrentWindow.CurrentTab.InjectJavascriptAsync(script);
     }
     catch (Exception ex)
     {
         _act.Error = "Error: Failed to Inject the provided Javascript";
         Reporter.ToLog(eLogLevel.ERROR, "Error: Failed to Inject the provided Javascript", ex);
     }
 }
📝 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.

private async Task HandleInjectJS()
{
    string script = _act.GetInputParamCalculatedValue("Value");
    if (string.IsNullOrEmpty(script))
    {
        _act.Error = "Error: Script value is empty";
        return;
    }
    
    // Basic validation to prevent obvious script injection
    if (script.Contains("<script>") || script.Contains("</script>"))
    {
        _act.Error = "Error: Script contains potentially unsafe HTML tags";
        return;
    }
    
    try
    {
        await _browser.CurrentWindow.CurrentTab.InjectJavascriptAsync(script);
    }
    catch (Exception ex)
    {
        _act.Error = "Error: Failed to Inject the provided Javascript";
        Reporter.ToLog(eLogLevel.ERROR, "Error: Failed to Inject the provided Javascript", ex);
    }
}

206-220: 🧹 Nitpick (assertive)

Consider adding retry logic for URL unblocking.

The URL unblocking operation might benefit from retry attempts in case of temporary failures.

 private async Task HandleUnblockUrls()
 {
+    const int maxRetries = 3;
+    const int retryDelayMs = 1000;
+    
     try
     {
-        if (!await _browser.CurrentWindow.CurrentTab.UnblockURLAsync())
+        for (int attempt = 1; attempt <= maxRetries; attempt++)
         {
-            _act.Error = "Failed to unblock the URLs";
+            if (await _browser.CurrentWindow.CurrentTab.UnblockURLAsync())
+            {
+                return;
+            }
+            
+            if (attempt < maxRetries)
+            {
+                await Task.Delay(retryDelayMs);
+            }
         }
+        _act.Error = $"Failed to unblock the URLs after {maxRetries} attempts";
     }
     catch (Exception ex)
     {
         _act.Error = $"Error unblocking URLs: {ex.Message}";
         Reporter.ToLog(eLogLevel.ERROR, "Error: Failed to unblock the URLs", ex);
     }
 }
📝 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.

        private async Task HandleUnblockUrls()
        {
            const int maxRetries = 3;
            const int retryDelayMs = 1000;
            
            try
            {
                for (int attempt = 1; attempt <= maxRetries; attempt++)
                {
                    if (await _browser.CurrentWindow.CurrentTab.UnblockURLAsync())
                    {
                        return;
                    }
                    
                    if (attempt < maxRetries)
                    {
                        await Task.Delay(retryDelayMs);
                    }
                }
                _act.Error = $"Failed to unblock the URLs after {maxRetries} attempts";
            }
            catch (Exception ex)
            {
                _act.Error = $"Error unblocking URLs: {ex.Message}";
                Reporter.ToLog(eLogLevel.ERROR, "Error: Failed to unblock the URLs", ex);
            }
        }
Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightBrowserTab.cs (2)

1239-1263: 🧹 Nitpick (assertive)

Consider enhancing window maximization for better cross-platform support.

The current implementation has potential limitations:

  1. Screen dimensions might not be accurate on multi-monitor setups.
  2. Setting viewport size might not maximize the actual window.

Consider this alternative implementation:

 public async Task MaximizeWindowAsync()
 {
     await MaximizeWindowInternalAsync();
 }

 private async Task MaximizeWindowInternalAsync()
 {
     try
     {
-        var screenWidth = await _playwrightPage.EvaluateAsync<int>("window.screen.width");
-        var screenHeight = await _playwrightPage.EvaluateAsync<int>("window.screen.height");
-        await _playwrightPage.SetViewportSizeAsync(screenWidth, screenHeight);
+        // Get the available screen space
+        var dimensions = await _playwrightPage.EvaluateAsync<dynamic>(@"
+            () => ({
+                width: window.screen.availWidth,
+                height: window.screen.availHeight
+            })");
+        
+        // Validate dimensions
+        if (dimensions.width <= 0 || dimensions.height <= 0)
+        {
+            throw new InvalidOperationException("Invalid screen dimensions detected");
+        }
+        
+        // Set viewport and maximize window
+        await _playwrightPage.SetViewportSizeAsync((int)dimensions.width, (int)dimensions.height);
+        await _playwrightPage.EvaluateAsync("window.moveTo(0,0)");
     }
     catch (Exception ex)
     {
         Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex);
         throw;
     }
 }
📝 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.

        /// <summary>
        /// Maximizes the browser window to the screen's width and height.
        /// </summary>
        public async Task MaximizeWindowAsync()
        {
            await MaximizeWindowInternalAsync();
        }
        /// <summary>
        /// Internal implementation of window maximization.
        /// </summary>
        private async Task MaximizeWindowInternalAsync()
        {
            try
            {
                // Get the available screen space
                var dimensions = await _playwrightPage.EvaluateAsync<dynamic>(@"
                    () => ({
                        width: window.screen.availWidth,
                        height: window.screen.availHeight
                    })");
                
                // Validate dimensions
                if (dimensions.width <= 0 || dimensions.height <= 0)
                {
                    throw new InvalidOperationException("Invalid screen dimensions detected");
                }
                
                // Set viewport and maximize window
                await _playwrightPage.SetViewportSizeAsync((int)dimensions.width, (int)dimensions.height);
                await _playwrightPage.EvaluateAsync("window.moveTo(0,0)");
            }
            catch (Exception ex)
            {
                Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex);
                throw;
            }
        }

1264-1339: 🧹 Nitpick (assertive)

Enhance URL blocking with comprehensive validation and rate limiting.

The URL blocking implementation could be improved for better reliability and performance.

Consider these enhancements:

 private async Task<bool> SetBlockedURLAsyncInternal(string urls)
 {
     try
     {
         var listURL = GetBlockedUrlsArray(urls);
+        var validUrlPatterns = new List<string>();
+        
         foreach (var rawURL in listURL)
         {
             var url = rawURL?.Trim();
             if (!string.IsNullOrEmpty(url))
             {
-                if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
+                // Validate URL pattern
+                if (!IsValidUrlPattern(url))
                 {
-                    url = "https://" + url;
+                    Reporter.ToLog(eLogLevel.WARN, $"Invalid URL pattern: {url}");
+                    continue;
                 }
-                await _playwrightPage.RouteAsync(url, async route => await route.AbortAsync());
+                validUrlPatterns.Add(url);
             }
         }
+        
+        // Apply rate limiting for large number of patterns
+        const int batchSize = 10;
+        for (int i = 0; i < validUrlPatterns.Count; i += batchSize)
+        {
+            var batch = validUrlPatterns.Skip(i).Take(batchSize);
+            var tasks = batch.Select(pattern => 
+                _playwrightPage.RouteAsync(pattern, async route => await route.AbortAsync())
+            );
+            await Task.WhenAll(tasks);
+            
+            // Add small delay between batches to prevent overwhelming
+            if (i + batchSize < validUrlPatterns.Count)
+            {
+                await Task.Delay(100);
+            }
+        }
+        
         await _playwrightPage.ReloadAsync();
         return true;
     }
     catch (Exception ex)
     {
         Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex);
         throw;
     }
 }

+private bool IsValidUrlPattern(string pattern)
+{
+    try
+    {
+        // Basic validation for common URL patterns
+        return pattern.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
+               pattern.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ||
+               pattern.StartsWith("*") ||
+               Uri.IsWellFormedUriString(pattern, UriKind.Absolute);
+    }
+    catch
+    {
+        return false;
+    }
+}
📝 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.

        /// <summary>
        /// Sets the URLs to be blocked during the browser session.
        /// </summary>
        /// <param name="urls">Comma-separated list of URLs to be blocked.</param>
        /// <returns>True if the URLs were successfully blocked, otherwise false.</returns>
        public async Task<bool> SetBlockedURLAsync(string urls)
        {
            return await SetBlockedURLAsyncInternal(urls);
        }
        private async Task<bool> SetBlockedURLAsyncInternal(string urls)
        {
            try
            {
                var listURL = GetBlockedUrlsArray(urls);
                var validUrlPatterns = new List<string>();
                
                foreach (var rawURL in listURL)
                {
                    var url = rawURL?.Trim();
                    if (!string.IsNullOrEmpty(url))
                    {
                        // Validate URL pattern
                        if (!IsValidUrlPattern(url))
                        {
                            Reporter.ToLog(eLogLevel.WARN, $"Invalid URL pattern: {url}");
                            continue;
                        }
                        validUrlPatterns.Add(url);
                    }
                }
                
                // Apply rate limiting for large number of patterns
                const int batchSize = 10;
                for (int i = 0; i < validUrlPatterns.Count; i += batchSize)
                {
                    var batch = validUrlPatterns.Skip(i).Take(batchSize);
                    var tasks = batch.Select(pattern => 
                        _playwrightPage.RouteAsync(pattern, async route => await route.AbortAsync())
                    );
                    await Task.WhenAll(tasks);
                    
                    // Add small delay between batches to prevent overwhelming
                    if (i + batchSize < validUrlPatterns.Count)
                    {
                        await Task.Delay(100);
                    }
                }
                
                await _playwrightPage.ReloadAsync();
                return true;
            }
            catch (Exception ex)
            {
                Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex);
                throw;
            }
        }

        /// <summary>
        /// Splits comma-separated URLs into an array.
        /// </summary>
        private string[] GetBlockedUrlsArray(string urlsToBlock)
        {
            string[] arrBlockedUrls = Array.Empty<string>();
            if (!string.IsNullOrEmpty(urlsToBlock))
            {
                arrBlockedUrls = urlsToBlock.Trim(',').Split(',', StringSplitOptions.RemoveEmptyEntries);
            }
            return arrBlockedUrls;
        }

        /// <summary>
        /// Unblocks all previously blocked URLs during the browser session.
        /// </summary>
        /// <returns>True if the URLs were successfully unblocked, otherwise false.</returns>
        public async Task<bool> UnblockURLAsync()
        {
            return await UnblockURLInternalAsync();
        }

        /// <summary>
        /// Internal implementation of URL unblocking.
        /// </summary>
        private async Task<bool> UnblockURLInternalAsync()
        {
            try
            {
                await _playwrightPage.UnrouteAllAsync();
                await _playwrightPage.ReloadAsync();
                return true;
            }
            catch (Exception ex)
            {
                Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex);
                throw;
            }
        }

        private bool IsValidUrlPattern(string pattern)
        {
            try
            {
                // Basic validation for common URL patterns
                return pattern.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
                       pattern.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ||
                       pattern.StartsWith("*") ||
                       Uri.IsWellFormedUriString(pattern, UriKind.Absolute);
            }
            catch
            {
                return false;
            }
        }
Ginger/GingerCore/Drivers/JavaDriverLib/GingerJavaAgent/agent/com/amdocs/ginger/JavaDriver.java (1)

1821-1855: 🧹 Nitpick (assertive)

Consider logging the silently caught exception and refactoring coordinate parsing.

This block cleanly adds "ClickXY" functionality, including validation of coordinates and boundary checks. However:

  • The generic catch block at lines 1849-1850 ignores errors without logging, which hampers debugging.
  • Repeated parsing logic for X and Y could be centralized in a helper method.

Below is a possible diff addressing these observations:

@@ -1848,7 +1848,13 @@
   }
 } catch(Exception ex) {
-  // Silently ignore
+  GingerAgent.WriteLog("Exception retrieving component dimensions: " + ex.getMessage());
+  // Decide whether to rethrow or return an error if critical
+  // return PayLoad.Error(...);
 }

@@ -1830,20 +1830,25 @@
 int x = 0;
 int y = 0;
-try {
-  x = Integer.parseInt(XCoordinate);
-} catch (Exception ex) {
-  return PayLoad.Error(PayLoad.ErrorCode.Unknown.GetErrorCode(), "Invalid XCoordinate format: " + XCoordinate);
-}
-try {
-  y = Integer.parseInt(YCoordinate);
-} catch (Exception ex) {
-  return PayLoad.Error(PayLoad.ErrorCode.Unknown.GetErrorCode(), "Invalid YCoordinate format: " + YCoordinate);
-}
+PayLoad parsed = parseCoordinates(XCoordinate, YCoordinate);
+if (parsed.IsErrorPayLoad()) {
+  return parsed;
+}
+x = parsed.GetValueInt();
+y = parsed.GetValueInt();

// Possibly continue the boundary checks here...

Committable suggestion skipped: line range outside the PR's diff.

Ginger/Ginger/Actions/ActionEditPages/ActMobileDeviceEditPage.xaml.cs (3)

76-77: 🧹 Nitpick (assertive)

Typo in control name "Sumilation"
Consider renaming xPhotoSumilationTxtBox to xPhotoSimulationTxtBox for correct spelling and clarity.

- xPhotoSumilationTxtBox
+ xPhotoSimulationTxtBox
📝 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.

            xPhotoSimulationTxtBox.Init(Context.GetAsContext(mAct.Context), mAct.GetOrCreateInputParam(nameof(ActMobileDevice.SimulatedPhotoPath)), true, true, UCValueExpression.eBrowserType.File, "*");

382-392: 🧹 Nitpick (assertive)

AddTouchOperation method
Rename tuchOperation to touchOperation to ensure consistency in naming.

- MobileTouchOperation tuchOperation = new MobileTouchOperation
+ MobileTouchOperation touchOperation = new MobileTouchOperation

Committable suggestion skipped: line range outside the PR's diff.


364-380: 🧹 Nitpick (assertive)

Define multi-touch grid columns
Columns and their headers look good. As a minor improvement, consider simplifying the Duration header to "Duration (ms)" for clarity.

- new GridColView() { Field = nameof(MobileTouchOperation.OperationDuration), Header = "Duration Milliseconds (Move & Pause)", ...
+ new GridColView() { Field = nameof(MobileTouchOperation.OperationDuration), Header = "Duration (ms)", ...
📝 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.

        private void SetMultiTouchGridView()
        {
            GridViewDef view = new GridViewDef(GridViewDef.DefaultViewName)
            {
                GridColsView =
            [
                new GridColView() { Field = nameof(MobileTouchOperation.OperationType), Header = "Operation Type", WidthWeight = 25, StyleType = GridColView.eGridColStyleType.ComboBox, CellValuesList=GingerCore.General.GetEnumValuesForCombo(typeof(eFingerOperationType)) },
                new GridColView() { Field = nameof(MobileTouchOperation.MoveXcoordinate), Header = "X Coordinate (Move Only)", WidthWeight = 25, StyleType = GridColView.eGridColStyleType.Text },
                new GridColView() { Field = nameof(MobileTouchOperation.MoveYcoordinate), Header = "Y Coordinate (Move Only)", WidthWeight = 25, StyleType = GridColView.eGridColStyleType.Text },
                new GridColView() { Field = nameof(MobileTouchOperation.OperationDuration), Header = "Duration (ms)", WidthWeight = 25, StyleType = GridColView.eGridColStyleType.Text },
            ]
            };
            xMultiTouchGrid.btnRefresh.Visibility = Visibility.Collapsed;
            xMultiTouchGrid.btnEdit.Visibility = Visibility.Collapsed;
            xMultiTouchGrid.SetAllColumnsDefaultView(view);
            xMultiTouchGrid.InitViewItems();
        }
Ginger/GingerCoreNET/Drivers/CoreDrivers/Mobile/Appium/GenericAppiumDriver.cs (2)

719-735: 🧹 Nitpick (assertive)

Consider improved error handling
When retrieving X/Y from the element fails, consider adding more descriptive logging or fallback logic for debugging. This helps diagnose failures in complex UI scenarios.


748-763: 🧹 Nitpick (assertive)

Prefer consistent naming or unify logic
PullXandYofElement duplicates logic and naming from the block at lines 719–735. Consider combining or centralizing to reduce repetition and potential drift.

Ginger/GingerCoreNET/ActionsLib/UI/Mobile/MobileTouchOperation.cs (1)

1-130: 🧹 Nitpick (assertive)

Well-structured class
The approach to reset coordinates and duration based on the operation type is clear. As a small improvement, ensure you handle potential negative or non-sensible coordinate/duration values.

Ginger/Ginger/Actions/ActionEditPages/ActMobileDeviceEditPage.xaml (1)

93-109: 🧹 Nitpick (assertive)

Consider adding accessibility attributes to the new controls.

While the UI controls are well-structured, consider adding accessibility attributes (AutomationProperties.Name, AutomationProperties.HelpText) to improve screen reader support.

-            <Label x:Name="xFilePathLbl" Style="{StaticResource $LabelStyle}" Content="Device File Path:" Margin="-4,0,0,0"/>
+            <Label x:Name="xFilePathLbl" Style="{StaticResource $LabelStyle}" Content="Device File Path:" Margin="-4,0,0,0"
+                   AutomationProperties.Name="Device File Path Label"
+                   AutomationProperties.HelpText="Enter the path to the file on the device"/>
📝 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.

        <StackPanel x:Name="xFileTransferPnl" HorizontalAlignment="Left" Orientation="Vertical"  DockPanel.Dock="Top" Margin="5,10,0,0" Visibility="Collapsed">
            <Label x:Name="xFilePathLbl" Style="{StaticResource $LabelStyle}" Content="Device File Path:" Margin="-4,0,0,0"
                   AutomationProperties.Name="Device File Path Label"
                   AutomationProperties.HelpText="Enter the path to the file on the device"/>
            <Actions:UCValueExpression x:Name="xFilePathTextBox" HorizontalAlignment="Left" Margin="0,0,0,0" Width="330"/>
            <Label x:Name="xFolderPathLbl" Style="{StaticResource $LabelStyle}" Content="Local Target Folder:" Margin="-3,0,0,0"/>
            <Actions:UCValueExpression x:Name="xFolderPathTxtBox" Width="340" />
        </StackPanel>
        
        <StackPanel x:Name="xSpecificPerformanceDataPnl" HorizontalAlignment="Left" Orientation="Vertical"  DockPanel.Dock="Top" Margin="0,2,0,0" Visibility="Collapsed">
            <Label Style="{StaticResource $LabelStyle}" Content="Data Type:" Margin="0,0,0,0"/>
            <UserControlsLib1:UCComboBox x:Name="xDataTypeComboBox" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="4,-6,0,0" Width="250"/>
        </StackPanel>
        <StackPanel x:Name="xDeviceRotationPnl" HorizontalAlignment="Left" Orientation="Horizontal"  DockPanel.Dock="Top" Margin="5,10,0,0" Visibility="Collapsed">
            <Label Style="{StaticResource $LabelStyle}" Content="Choose State: "/>
            <UserControlsLib1:UCComboBox x:Name="xDeviceRotateComboBox" VerticalAlignment="Top" Margin="0,-2,0,0" Width="241"/>
        </StackPanel>
        
        <Ginger:ucGrid x:Name="xMultiTouchGrid" Title="Touch Operations to Perform" ShowTitle="Collapsed" Visibility="Collapsed" Margin="0,10,0,0"/>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs (1)

1364-1375: 🧹 Nitpick (assertive)

Consider improved cancellation/error handling for clone with progress.
The code properly reports checkout progress, but if cancellation is requested early or the clone operation fails due to network issues, additional handling or messaging might be needed to reflect the partial progress or the cancellation state.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f7ad14 and 932204b.

📒 Files selected for processing (1)
  • Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs (7 hunks)
🔇 Additional comments (3)
Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs (3)

455-461: Ensure intended certificate handling policy for clone operation.
When invoking GetFetchOptions(co.FetchOptions); immediately before cloning, bear in mind that the current implementation in GetFetchOptions sets CertificateCheck to always return true, effectively skipping certificate verification. If this is not the intended security posture, consider enforcing stronger certificate checks or making this behavior configurable.


470-470: No functional change.
This line appears to be a simple blank-line addition without code changes.


1237-1245: Good consolidation of fetch options in pull options.
The approach of initializing PullOptions and then populating the fetch options with GetFetchOptions(pullOption.FetchOptions) keeps the code consistent with the refactored methods.

Comment thread Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs Outdated
Comment thread Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs
Comment thread Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🔭 Outside diff range comments (2)
Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs (2)

470-489: 🧹 Nitpick (assertive)

Correct the spelling of 'ExistInLocaly' for clarity.

Within this method, the property name sol.ExistInLocaly is misspelled. Consider renaming it to sol.ExistInLocally (or another accurate naming) to maintain consistency and readability.


1376-1386: ⚠️ Potential issue

Initialize FetchOptions for CloneOptions to avoid null references.

cloneOptions.FetchOptions may be null by default, causing a failure when calling GetFetchOptionsWithProgress(cloneOptions.FetchOptions, ...). To prevent errors, initialize it first.

Suggested fix:

var cloneOptions = new CloneOptions()
{
    BranchName = string.IsNullOrEmpty(SourceControlBranch) ? "master" : SourceControlBranch,
    OnCheckoutProgress = ...
};
+cloneOptions.FetchOptions = new FetchOptions();
GetFetchOptionsWithProgress(cloneOptions.FetchOptions, progressNotifier, cancellationToken);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 932204b and 58aeac3.

📒 Files selected for processing (1)
  • Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs (7 hunks)
🧰 Additional context used
🧠 Learnings (1)
Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs (2)
Learnt from: GokulBothe99
PR: Ginger-Automation/Ginger#4103
File: Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs:1252-1256
Timestamp: 2025-02-13T08:43:01.945Z
Learning: In GITSourceControl.cs, certificate validation should not be unconditionally disabled by returning true in FetchOptions.CertificateCheck. Instead, consider making it configurable and logging warnings when disabled.
Learnt from: GokulBothe99
PR: Ginger-Automation/Ginger#4103
File: Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs:1448-1455
Timestamp: 2025-02-13T08:42:35.821Z
Learning: In GITSourceControl class, the GetFetchOptionsWithProgress method modifies properties of an existing FetchOptions instance passed as a parameter, rather than creating and returning a new instance. The FetchOptions instance needs to be initialized before being passed to this method.
🔇 Additional comments (1)
Ginger/GingerCoreNET/SourceControl/GITSourceControl.cs (1)

1419-1450: Overall approach is consistent, but ensure callers pass a non-null FetchOptions.

This helper method correctly modifies an existing FetchOptions instance. Just remember that any caller must ensure fetchOptions is instantiated before passing it here to avoid exceptions.

Comment on lines +1260 to 1268
private void GetFetchOptions(FetchOptions fetchOptions)
{
return new FetchOptions
{
CredentialsProvider = GetSourceCredentialsHandler(),
Depth = 1,
CertificateCheck = (_, valid, host) => true,
};
if (fetchOptions == null) throw new ArgumentNullException(nameof(fetchOptions));
fetchOptions.CredentialsProvider = GetSourceCredentialsHandler();
fetchOptions.CertificateCheck = (certificate, valid, host) =>
{
return valid;
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Good practice in verifying certificate validity.

Using return valid; for CertificateCheck properly respects the certificate’s validity. If you need to accommodate self-signed certificates for certain environments, consider adding a configuration flag to selectively override this behavior and log a security warning.

Comment on lines 1459 to +1493
{
MergeResult mergeResult = null;
ReportFeatureUsage(operation: "Pull");

Task.Run(() =>
try
{
using (var repo = new LibGit2Sharp.Repository(RepositoryRootFolder))
MergeResult mergeResult = null;
ReportFeatureUsage(operation: "Pull");

Task.Run(() =>
{
var pullOptions = new PullOptions
using (var repo = new LibGit2Sharp.Repository(RepositoryRootFolder))
{
FetchOptions = GetFetchOptionsWithProgress(progressNotifier, cancellationToken)
};
var pullOptions = new PullOptions()
{
FetchOptions = new FetchOptions()

var signature = new Signature(
IsRepositoryPublic() ? "dummy" : SourceControlUser,
IsRepositoryPublic() ? "dummy" : SourceControlUser,
DateTimeOffset.Now
);
};

mergeResult = Commands.Pull(repo, signature, pullOptions);
}
}).Wait();
return mergeResult;

GetFetchOptionsWithProgress(pullOptions.FetchOptions, progressNotifier, cancellationToken);

var signature = new Signature(
IsRepositoryPublic() ? "dummy" : SourceControlUser,
IsRepositoryPublic() ? "dummy" : SourceControlUser,
DateTimeOffset.Now
);

mergeResult = Commands.Pull(repo, signature, pullOptions);
}
}).Wait();
return mergeResult;
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Error occurred while pulling the latest changes.", ex);
return null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider using an async approach instead of Task.Run(...).Wait().

While this code works, immediately waiting on a task negates most concurrency benefits and ignores the cancellation token during the wait. An async/await pattern could provide cleaner cancellation handling and non-blocking behavior.

Comment on lines +1237 to 1254
try
{
MergeOptions = new MergeOptions
var pullOption = new PullOptions
{
FailOnConflict = true,
},

FetchOptions = GetFetchOptions()
};
MergeOptions = new MergeOptions
{
FailOnConflict = true,
},
};
GetFetchOptions(pullOption?.FetchOptions);
return pullOption;
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Error occurred while getting pull options.", ex);
return null;
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Assign a new FetchOptions instance to avoid runtime errors.

In GetPullOptions(), pullOption?.FetchOptions is null by default. Calling GetFetchOptions(pullOption?.FetchOptions) will fail. Ensure pullOption.FetchOptions is initialized.

You can fix it by adding:

 var pullOption = new PullOptions
 {
     MergeOptions = new MergeOptions
     {
         FailOnConflict = true,
     },
-};
+    FetchOptions = new FetchOptions(),
 };
 GetFetchOptions(pullOption?.FetchOptions);
📝 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
try
{
MergeOptions = new MergeOptions
var pullOption = new PullOptions
{
FailOnConflict = true,
},
FetchOptions = GetFetchOptions()
};
MergeOptions = new MergeOptions
{
FailOnConflict = true,
},
};
GetFetchOptions(pullOption?.FetchOptions);
return pullOption;
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Error occurred while getting pull options.", ex);
return null;
}
}
try
{
var pullOption = new PullOptions
{
MergeOptions = new MergeOptions
{
FailOnConflict = true,
},
FetchOptions = new FetchOptions(),
};
GetFetchOptions(pullOption?.FetchOptions);
return pullOption;
}
catch (Exception ex)
{
Reporter.ToLog(eLogLevel.ERROR, "Error occurred while getting pull options.", ex);
return null;
}
}

Comment on lines +455 to 462
{
var co = new CloneOptions()
{
BranchName = string.IsNullOrEmpty(SourceControlBranch) ? "master" : SourceControlBranch,
};
GetFetchOptions(co.FetchOptions);
RepositoryRootFolder = LibGit2Sharp.Repository.Clone(URI, Path, co);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Initialize FetchOptions to prevent null exceptions.

Currently, co.FetchOptions is never initialized. Calling GetFetchOptions(co.FetchOptions) will throw an ArgumentNullException if co.FetchOptions is null. Consider creating a new FetchOptions() before invoking GetFetchOptions.

Below is a possible fix:

 var co = new CloneOptions()
 {
     BranchName = string.IsNullOrEmpty(SourceControlBranch) ? "master" : SourceControlBranch,
 };
+co.FetchOptions = new FetchOptions();
 GetFetchOptions(co.FetchOptions);
 RepositoryRootFolder = LibGit2Sharp.Repository.Clone(URI, Path, co);
📝 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
{
var co = new CloneOptions()
{
BranchName = string.IsNullOrEmpty(SourceControlBranch) ? "master" : SourceControlBranch,
};
GetFetchOptions(co.FetchOptions);
RepositoryRootFolder = LibGit2Sharp.Repository.Clone(URI, Path, co);
}
{
var co = new CloneOptions()
{
BranchName = string.IsNullOrEmpty(SourceControlBranch) ? "master" : SourceControlBranch,
};
co.FetchOptions = new FetchOptions();
GetFetchOptions(co.FetchOptions);
RepositoryRootFolder = LibGit2Sharp.Repository.Clone(URI, Path, co);
}

@Maheshkale447
Maheshkale447 merged commit 903ad32 into Releases/Official-Release Feb 13, 2025
@Maheshkale447
Maheshkale447 deleted the BugFix/GitLibDowngrade branch February 13, 2025 09:46
This was referenced Feb 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants