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

重置目录,优化热执行,Main拦截实验. #310

Merged
merged 1 commit into from
Jun 12, 2024
Merged

Conversation

NMSAzulX
Copy link
Collaborator

@NMSAzulX NMSAzulX commented Jun 12, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a proxy method generation for intercepting the Main method in C# files, enabling advanced interception logic.
  • Bug Fixes

    • Improved file availability checks by centralizing the logic in the VSCSharpFolder class.
  • Refactor

    • Updated project reference paths and package versions for better compatibility and performance.
    • Enhanced code readability and maintainability by consolidating comment tags and file checking methods.

Copy link

coderabbitai bot commented Jun 12, 2024

Walkthrough

The recent updates introduce a new HotExecutorGenerator class for intercepting the Main method in C# files, add project and package references, and modify file availability checks by centralizing logic in the VSCSharpFolder class. These changes enhance the Natasha framework's hot execution capabilities and streamline file monitoring processes.

Changes

File Path Change Summary
src/.../HotExecutorGenerator.cs Added HotExecutorGenerator class implementing ISourceGenerator to generate a proxy method for intercepting the Main method.
src/.../Natasha.CSharp.Extension.HotExecutor.SG.csproj Introduced a new project file specifying netstandard2.0 target framework, language version preview, and package references for Microsoft.CodeAnalysis.CSharp and Microsoft.CodeAnalysis.Analyzers.
src/.../Natasha.CSharp.Extension.HotExecutor.csproj Updated project reference path for Natasha.CSharp.Compiler project.
src/.../ProjectDynamicProxy.cs Added _commentTag field and SetCommentTag method; modified conditions in Run and HandleTree methods to use VSCSharpFolder.CheckFileAvailiable(file) and _commentTag, respectively.
src/.../VSCSharpFolder.cs Added ExpectFiles HashSet, loaded and parsed XML document to populate ExpectFiles, and introduced CheckFileAvailiable method for file availability checks.
src/.../VSCSharpMainFileWatcher.cs Replaced calls to CheckFileAvailiable method with those from the VSCSharpFolder class, affecting the logic flow within the StartMonitor method.
src/.../Natasha.CSharp.Compiler.csproj Updated Microsoft.CodeAnalysis.CSharp.Workspaces package version from 4.9.2 to 4.10.0.

Sequence Diagram(s)

sequenceDiagram
    participant Compiler as Natasha.CSharp.Compiler
    participant HotExecutor as HotExecutorGenerator
    participant Folder as VSCSharpFolder
    participant Proxy as ProjectDynamicProxy
    participant Watcher as VSCSharpMainFileWatcher

    HotExecutor->>Compiler: Intercept Main method
    Compiler-->>HotExecutor: Syntax tree with Main method
    HotExecutor-->>Proxy: Generate proxy method
    Proxy->>Folder: Check file availability
    Folder-->>Proxy: File is available
    Watcher->>Folder: Check file availability
    Folder-->>Watcher: File is available
Loading

Poem

In the realm of code so bright,
A rabbit hops with pure delight,
Hot execution now refined,
Main methods swiftly redefined.
File checks in a central place,
Enhancing flow, a smoother pace,
With every change, we celebrate,
Innovations that we create! 🌟🐇


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@NMSAzulX
Copy link
Collaborator Author

@coderabbitai review

Copy link

coderabbitai bot commented Jun 12, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@NMSAzulX NMSAzulX added the pr_src 此次提交包含 [源码工程] 相关的改动. label Jun 12, 2024
Copy link

UT Test - Ubuntu

1 tests   1 ✅  0s ⏱️
1 suites  0 💤
1 files    0 ❌

Results for commit a192e5c.

@NMSAzulX
Copy link
Collaborator Author

未检测到合适的 ISSUE 推荐给您。感谢您的反馈!

该条自动推荐信息来自于 nms-bot.

Copy link

UT Test - Windows

1 tests   1 ✅  0s ⏱️
1 suites  0 💤
1 files    0 ❌

Results for commit a192e5c.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Outside diff range and nitpick comments (3)
src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/VSCSharpFolder.cs (1)

Line range hint 17-51: Initialization of ExpectFiles should use proper syntax to create a new HashSet.

- ExpectFiles = [];
+ ExpectFiles = new HashSet<string>();
src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/VSCSharpMainFileWatcher.cs (1)

Line range hint 55-102: The implementation of file event handlers in VSCSharpMainFileWatcher is robust, making good use of the CheckFileAvailiable method from VSCSharpFolder. Consider adding more detailed debug logs to help with troubleshooting.

+ // Debug log to trace file path and availability status
+ Console.WriteLine($"Checking availability for: {e.FullPath}, Available: {VSCSharpFolder.CheckFileAvailiable(e.FullPath)}");
src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/ProjectDynamicProxy.cs (1)

32-39: Consider adding XML documentation for the SetCommentTag method to explain its purpose and usage.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ad8ff7e and a192e5c.

Files selected for processing (7)
  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor.SG/HotExecutorGenerator.cs (1 hunks)
  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor.SG/Natasha.CSharp.Extension.HotExecutor.SG.csproj (1 hunks)
  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/Natasha.CSharp.Extension.HotExecutor.csproj (1 hunks)
  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/ProjectDynamicProxy.cs (3 hunks)
  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/VSCSharpFolder.cs (4 hunks)
  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/VSCSharpMainFileWatcher.cs (5 hunks)
  • src/Natasha.CSharp/Natasha.CSharp.Compiler/Natasha.CSharp.Compiler.csproj (1 hunks)
Files skipped from review due to trivial changes (2)
  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor.SG/Natasha.CSharp.Extension.HotExecutor.SG.csproj
  • src/Natasha.CSharp/Natasha.CSharp.Compiler/Natasha.CSharp.Compiler.csproj
Additional comments not posted (5)
src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/VSCSharpFolder.cs (1)

68-75: The CheckFileAvailiable method is well-implemented, ensuring that files in certain paths or expected files are not processed. Good job on this logic.

src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/VSCSharpMainFileWatcher.cs (1)

138-138: The error handling method Error is well-implemented, providing detailed exception information. This is crucial for diagnosing issues in a production environment.

src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/ProjectDynamicProxy.cs (3)

32-39: The introduction of _commentTag and its setter method SetCommentTag is a good addition for dynamic comment management.


205-205: The update to check file availability before processing is a prudent addition, enhancing the robustness of the Run method.


252-252: The addition of comment-based filtering in the HandleTree method is a clever way to manage experimental or conditional features.

@@ -244,7 +249,7 @@ private static SyntaxTree HandleTree(string content)
var trivias = statement.GetLeadingTrivia();
foreach (var trivia in trivias)
{
if (trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) && trivia.ToString().Trim().StartsWith("//Once"))
if (trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) && trivia.ToString().Trim().StartsWith(_commentTag))
Copy link

Choose a reason for hiding this comment

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

Consider adding unit tests to ensure that the comment-based filtering works as expected and does not introduce bugs.

Would you like me to help by writing some unit tests for this functionality?

@@ -196,13 +202,12 @@

foreach (var file in srcCodeFiles)
{
if (_mainWatcher.CheckFileAvailiable(file))
if (VSCSharpFolder.CheckFileAvailiable(file))
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The CheckFileAvailiable method implementation has been located in VSCSharpFolder.cs. The method checks if the file path starts with certain predefined paths or is contained in a list of expected files, returning false if any of these conditions are met, and true otherwise. This implementation does not include any error handling for potential issues such as invalid file paths or access permissions.

To ensure robustness, it would be prudent to add error handling within this method to catch and handle exceptions that may arise during file checks.

Suggested Changes:

  • Add try-catch blocks within the CheckFileAvailiable method to handle potential exceptions.

Locations to Update:

  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/VSCSharpFolder.cs

Example Update:

public static bool CheckFileAvailiable(string file)
{
    try
    {
        if (file.StartsWith(VSCSharpFolder.ObjPath) || file.StartsWith(VSCSharpFolder.BinPath) || VSCSharpFolder.ExpectFiles.Contains(file))
        {
            return false;
        }
        return true;
    }
    catch (Exception ex)
    {
        // Log the exception or handle it as needed
        Console.WriteLine($"Error checking file availability: {ex.Message}");
        return false;
    }
}

Action Required:

  • Implement the suggested error handling in the CheckFileAvailiable method.
Analysis chain

Ensure that the file availability check is robust and consider adding error handling for file reading operations.


To ensure the file availability check is robust, we need to review the implementation of the CheckFileAvailiable method and verify if proper error handling is in place in the calling methods.


The CheckFileAvailiable method implementation was not found in the search results, which means it might be defined differently or located in a different file. Additionally, the search for error handling using try blocks revealed multiple instances of error handling across various files, but none specifically related to the CheckFileAvailiable method.

To proceed, we need to locate the exact implementation of the CheckFileAvailiable method and verify its robustness and error handling. Let's refine our search to ensure we capture the correct method definition.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the robustness of file availability checks.

# Test: Search for the method usage. Expect: Proper error handling in the method.
rg --type csharp $'CheckFileAvailiable'

Length of output: 1260



Script:

#!/bin/bash
# Description: Verify the robustness of file availability checks.

# Test: Retrieve the implementation of the CheckFileAvailiable method.
ast-grep --lang csharp --pattern $'public static bool CheckFileAvailiable(string file) {
  $$$
}' --json

# Test: Check for error handling in the calling methods.
rg --type csharp 'try' -A 5 -B 5

Length of output: 57400



Script:

#!/bin/bash
# Description: Verify the robustness of file availability checks.

# Test: Retrieve the implementation of the CheckFileAvailiable method with a refined search.
rg --type csharp 'public static bool CheckFileAvailiable' -A 10 -B 2

Length of output: 1549

@@ -15,7 +15,7 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\Natasha.CSharp.Compiler\Natasha.CSharp.Compiler.csproj" />
<ProjectReference Include="..\..\..\Natasha.CSharp.Compiler\Natasha.CSharp.Compiler.csproj" />
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The path specified in the project reference is incorrect. The correct path for Natasha.CSharp.Compiler.csproj is src/Natasha.CSharp/Natasha.CSharp.Compiler/Natasha.CSharp.Compiler.csproj.

  • Update the project reference in src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.Extension.HotExecutor/Natasha.CSharp.Extension.HotExecutor.csproj to:
    <ProjectReference Include="..\..\Natasha.CSharp\Natasha.CSharp.Compiler\Natasha.CSharp.Compiler.csproj" />
Analysis chain

The updated project reference path looks correct, assuming the directory structure has been updated as described.


The path specified in the project reference is incorrect. Let's locate the correct path for Natasha.CSharp.Compiler.csproj.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the new project reference path is correct.

# Test: Check if the path exists.
if [ -d "src/Natasha.CSharp/Compiler/Natasha.CSharp.Compiler" ]; then
  echo "The path is correct."
else
  echo "The path is incorrect."
fi

Length of output: 119



Script:

#!/bin/bash
# Description: Locate the correct path for Natasha.CSharp.Compiler.csproj

# Use fd to find the Natasha.CSharp.Compiler.csproj file
fd Natasha.CSharp.Compiler.csproj

Length of output: 109

Comment on lines +8 to +75
[Generator]
public class HotExecutorGenerator : ISourceGenerator
{

public void Initialize(GeneratorInitializationContext context)
{
// No initialization required for this one
}

void ISourceGenerator.Execute(GeneratorExecutionContext context)
{
//Debugger.Launch();
var mainFile = string.Empty;
var lineNumber = 0;
var characterPosition = 0;
var syntaxTrees = context.Compilation.SyntaxTrees;
foreach (var tree in syntaxTrees)
{
var methods = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>();
if (methods.Any(method => method.Identifier.Text == "Main"))
{
var mainMethod = methods.FirstOrDefault(method => method.Identifier.Text == "Main");
mainFile = tree.FilePath;

var lineSpan = mainMethod.GetLocation().GetLineSpan();
lineNumber = lineSpan.StartLinePosition.Line + 1;
characterPosition = lineSpan.StartLinePosition.Character + 1;
//Debugger.Launch();
string proxyMethodContent = $@"

using System.Runtime.CompilerServices;

namespace System{{


public static class InterceptMain
{{

[InterceptsLocation(
filePath: @""{mainFile}"",
line: {lineNumber},
character: {characterPosition})]
public static void InterceptMethodMain(string args[])
{{

Console.WriteLine(11);

}}

}}
}}
// <auto-generated/>
namespace System.Runtime.CompilerServices
{{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
file sealed class InterceptsLocationAttribute(string filePath, int line, int character) : Attribute
{{
}}
}}

";

context.AddSource($"NatashaHotExecutorProxy.g.cs", proxyMethodContent);
break;
}
}
}
}
Copy link

Choose a reason for hiding this comment

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

The implementation of HotExecutorGenerator is robust and follows good practices in source generation using Roslyn. Consider adding more comments to explain the logic, especially around the proxy method generation.

+ // This method initializes the generator. Currently, no initialization is needed.
+ // This method executes the source generation logic. It searches for the 'Main' method across all syntax trees,
+ // and generates a proxy method if found.
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
[Generator]
public class HotExecutorGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
// No initialization required for this one
}
void ISourceGenerator.Execute(GeneratorExecutionContext context)
{
//Debugger.Launch();
var mainFile = string.Empty;
var lineNumber = 0;
var characterPosition = 0;
var syntaxTrees = context.Compilation.SyntaxTrees;
foreach (var tree in syntaxTrees)
{
var methods = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>();
if (methods.Any(method => method.Identifier.Text == "Main"))
{
var mainMethod = methods.FirstOrDefault(method => method.Identifier.Text == "Main");
mainFile = tree.FilePath;
var lineSpan = mainMethod.GetLocation().GetLineSpan();
lineNumber = lineSpan.StartLinePosition.Line + 1;
characterPosition = lineSpan.StartLinePosition.Character + 1;
//Debugger.Launch();
string proxyMethodContent = $@"
using System.Runtime.CompilerServices;
namespace System{{
public static class InterceptMain
{{
[InterceptsLocation(
filePath: @""{mainFile}"",
line: {lineNumber},
character: {characterPosition})]
public static void InterceptMethodMain(string args[])
{{
Console.WriteLine(11);
}}
}}
}}
// <auto-generated/>
namespace System.Runtime.CompilerServices
{{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
file sealed class InterceptsLocationAttribute(string filePath, int line, int character) : Attribute
{{
}}
}}
";
context.AddSource($"NatashaHotExecutorProxy.g.cs", proxyMethodContent);
break;
}
}
}
}
[Generator]
public class HotExecutorGenerator : ISourceGenerator
{
// This method initializes the generator. Currently, no initialization is needed.
public void Initialize(GeneratorInitializationContext context)
{
// No initialization required for this one
}
// This method executes the source generation logic. It searches for the 'Main' method across all syntax trees,
// and generates a proxy method if found.
void ISourceGenerator.Execute(GeneratorExecutionContext context)
{
//Debugger.Launch();
var mainFile = string.Empty;
var lineNumber = 0;
var characterPosition = 0;
var syntaxTrees = context.Compilation.SyntaxTrees;
foreach (var tree in syntaxTrees)
{
var methods = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>();
if (methods.Any(method => method.Identifier.Text == "Main"))
{
var mainMethod = methods.FirstOrDefault(method => method.Identifier.Text == "Main");
mainFile = tree.FilePath;
var lineSpan = mainMethod.GetLocation().GetLineSpan();
lineNumber = lineSpan.StartLinePosition.Line + 1;
characterPosition = lineSpan.StartLinePosition.Character + 1;
//Debugger.Launch();
string proxyMethodContent = $@"
using System.Runtime.CompilerServices;
namespace System{{
public static class InterceptMain
{{
[InterceptsLocation(
filePath: @""{mainFile}"",
line: {lineNumber},
character: {characterPosition})]
public static void InterceptMethodMain(string args[])
{{
Console.WriteLine(11);
}}
}}
}}
// <auto-generated/>
namespace System.Runtime.CompilerServices
{{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
file sealed class InterceptsLocationAttribute(string filePath, int line, int character) : Attribute
{{
}}
}}
";
context.AddSource($"NatashaHotExecutorProxy.g.cs", proxyMethodContent);
break;
}
}
}
}

@NMSAzulX NMSAzulX merged commit 08b1b37 into dev.next Jun 12, 2024
8 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pr_src 此次提交包含 [源码工程] 相关的改动.
Projects
No open projects
Development

Successfully merging this pull request may close these issues.

1 participant