Skip to content

Commit

Permalink
Merge pull request #245 from dotnetcore/testcodecov
Browse files Browse the repository at this point in the history
Testcodecov
  • Loading branch information
NMSAzulX authored Dec 24, 2023
2 parents 6a52b2d + d9adcb9 commit 2dc41f5
Show file tree
Hide file tree
Showing 59 changed files with 1,188 additions and 400 deletions.
12 changes: 12 additions & 0 deletions .github/project.yml
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,18 @@ src:
project_folder: src/Natasha.CSharp/Natasha.CSharp.Template
labels:
dependency_config:
- using_output:
enable: true
ignores:
id: 63C14375-8D73-43C8-BD7A-4BEC53456E4C
is_ignored: false
is_folded: false
relative_path: src/Natasha.CSharp/Extension/Natasha.CSharp.Codecov/Natasha.CSharp.Codecov.csproj
project_name: Natasha.CSharp.Codecov
package_name: DotNetCore.Natasha.CSharp.Codecov
project_folder: src/Natasha.CSharp/Extension/Natasha.CSharp.Codecov
labels:
dependency_config:
test:
folded_projects: []
global_labels:
Expand Down
7 changes: 7 additions & 0 deletions Natasha.sln
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HotReloadSample", "samples\
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HotReloadPlugin", "samples\HotReloadPlugin\HotReloadPlugin.csproj", "{89A2EC20-B432-4C6A-B740-78BBD1BF80EC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Natasha.CSharp.Codecov", "src\Natasha.CSharp\Extension\Natasha.CSharp.Codecov\Natasha.CSharp.Codecov.csproj", "{63C14375-8D73-43C8-BD7A-4BEC53456E4C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -367,6 +369,10 @@ Global
{89A2EC20-B432-4C6A-B740-78BBD1BF80EC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{89A2EC20-B432-4C6A-B740-78BBD1BF80EC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{89A2EC20-B432-4C6A-B740-78BBD1BF80EC}.Release|Any CPU.Build.0 = Release|Any CPU
{63C14375-8D73-43C8-BD7A-4BEC53456E4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63C14375-8D73-43C8-BD7A-4BEC53456E4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63C14375-8D73-43C8-BD7A-4BEC53456E4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63C14375-8D73-43C8-BD7A-4BEC53456E4C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -436,6 +442,7 @@ Global
{716B9CEC-8CA2-433F-9E9A-974E536C4099} = {F4622BCB-C287-4AFE-916B-8C138BD15A3D}
{7CD6F3A9-85F0-4F01-8B68-7FCC527768E6} = {B4487ABB-27A2-4353-AB16-1A94B31E0210}
{89A2EC20-B432-4C6A-B740-78BBD1BF80EC} = {B4487ABB-27A2-4353-AB16-1A94B31E0210}
{63C14375-8D73-43C8-BD7A-4BEC53456E4C} = {0CB3AF52-50F3-4728-BAC6-389F2E995111}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3004E730-B231-40FA-B75C-58D7DDE17679}
Expand Down
2 changes: 1 addition & 1 deletion samples/HotReloadPlugin/HotReloadPlugin.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFrameworks>net6.0;</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
8 changes: 5 additions & 3 deletions samples/HotReloadSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public unsafe static void Test(Assembly assembly)
foreach (var handle in asmDefinition.NamespaceDefinitions)
{
var nameDefinition = metaReader.GetNamespaceDefinition(handle);
Console.WriteLine($"{nameDefinition.Name.IsNil} : {metaReader.GetString(handle)} : {nameDefinition.TypeDefinitions.Count()}");
Console.WriteLine($"{nameDefinition.Name.IsNil} : {metaReader.GetString(handle)} : {nameDefinition.TypeDefinitions.Length}");
}
}
}
Expand All @@ -118,8 +118,10 @@ private static void HotReloadService_UpdateApplicationEvent(Type[]? obj)

public static Assembly OldAssembly(NatashaReferenceDomain domain)
{
AssemblyCSharpBuilder builder = new AssemblyCSharpBuilder();
builder.Domain = domain;
AssemblyCSharpBuilder builder = new AssemblyCSharpBuilder
{
Domain = domain
};
builder.Add("public class A{ public int Code = 1; public void Show(){ Console.WriteLine(Code); } }", UsingLoadBehavior.WithDefault);
return builder.GetAssembly();
}
Expand Down
159 changes: 89 additions & 70 deletions samples/ReferenceSample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
using Microsoft.CodeAnalysis;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Internal;
using System.Runtime.CompilerServices;
using static System.Diagnostics.DebuggableAttribute;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using HarmonyLib;
using HotReloadPlugin;
using Microsoft.CodeAnalysis;
using Natasha.CSharp.Codecov.Utils;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Reflection.PortableExecutable;
using static System.Reflection.Metadata.BlobBuilder;
using System.Runtime.CompilerServices;

namespace ReferenceSample
{
Expand All @@ -29,12 +23,14 @@ static void Main(string[] args)
//var p = typeof(C).GetProperty("ReferenceSample.Program.B.Name", BindingFlags.NonPublic | BindingFlags.Instance);
//var p1 = typeof(C).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
//Console.WriteLine(p.Name);
TestMini();
//NatashaManagement.Preheating(false, false);
//TestMini();

//var domain = NatashaManagement.CreateRandomDomain();
//var asm = domain.LoadPluginUseDefaultDependency("I:\\OpenSource\\Natasha\\samples\\ReferenceSample\\bin\\Debug\\net8.0\\DynamicLibraryFolders\\Nc0e9a864079d427680ea239b5a9e525e\\a69937be3d244336a20c46843d51d19b.dll");

//TestMini();
//var a = typeof(CodecovMonitor);
//var b = typeof(A);
//NatashaManagement.Preheating(true, true);
TestMini();
//var a = Math.Min(1, args.Length);
//NatashaManagement.Preheating(false, false);
//Console.WriteLine("=============================");
Expand Down Expand Up @@ -85,11 +81,16 @@ public static void TestMini1()
AssemblyCSharpBuilder builder = new();
builder
.UseRandomDomain()
.WithDebugCompile(item => item.WriteToAssembly())
.AddReferenceAndUsingCode(typeof(object).Assembly)
.AddReferenceAndUsingCode(typeof(Math).Assembly)
.AddReferenceAndUsingCode(typeof(MathF).Assembly)
.AddReferenceAndUsingCode(typeof(SuppressMessageAttribute));
.WithCombineUsingCode(UsingLoadBehavior.WithDefault)
.UseSmartMode()
//.UseSimpleMode()
////.WithOutsideReferences([MetadataReference.CreateFromFile("a")])
//.WithDebugCompile(item => item.WriteToAssembly())
//.AddReferenceAndUsingCode(typeof(object).Assembly)
//.AddReferenceAndUsingCode(typeof(Math).Assembly)
//.AddReferenceAndUsingCode(typeof(MathF).Assembly)
//.AddReferenceAndUsingCode(typeof(SuppressMessageAttribute))
;

builder.Add(@"
namespace MyNamespace{
Expand Down Expand Up @@ -117,21 +118,24 @@ public static object Invoke(){
}
public static void TestMini()
{
AssemblyCSharpBuilder builder = new();
builder.WithAnalysisAccessibility()


AssemblyCSharpBuilder builder = new();
builder
.UseRandomDomain()
.WithFileOutput()
.WithDebugCompile(item=>item.WriteToFile())
.AddReferenceAndUsingCode(typeof(HarmonyPatch))
.AddReferenceAndUsingCode(typeof(DebuggableAttribute))
.AddReferenceAndUsingCode(typeof(object).Assembly)
.UseSmartMode()
.ConfigCompilerOption(item => item.WithLowerVersionsAssembly().WithDiagnosticLevel(ReportDiagnostic.Warn))
//.WithFileOutput()
.WithDebugCompile(item => item.WriteToAssembly())
.UseSimpleMode()
.AddReferenceAndUsingCode(typeof(Math).Assembly)
.AddReferenceAndUsingCode(typeof(MathF).Assembly)
.AddReferenceAndUsingCode(typeof(A)).AddDependencyReferences(typeof(A))
.AddReferenceAndUsingCode(typeof(CodecovMonitor)).AddDependencyReferences(typeof(CodecovMonitor))
.AddReferenceAndUsingCode(typeof(SuppressMessageAttribute));


builder.Add(@"
[assembly: TargetFramework("".NETCoreApp,Version=v8.0"", FrameworkDisplayName = "".NET 8.0"")]
public class A{
public static int N1 = 10;
public static float N2 = 1.2F;
Expand All @@ -148,12 +152,17 @@ public static object Invoke2(){
/// 我的动态方法,返回科学计算结果。
/// </summary>
public static object Invoke(){
var type = typeof(HarmonyPatch);
var type2 = typeof(HarmonyPrefix);
int[] a = [1,2,3];
return N1 + MathF.Log10((float)Math.Sqrt(MathF.Sqrt(N2) + Math.Tan(N3)));
if(N1 == 10){
HotReloadPlugin.A asdasd = new();
asdasd.Show();
int[] a = [1,2,3];
Console.WriteLine(a);
return N1 + MathF.Log10((float)Math.Sqrt(MathF.Sqrt(N2) + Math.Tan(N3)));
}
else{
return 0;
}
}
[SuppressMessage(""Microsoft.Performance"", ""CA1801:ReviewUnusedParameters"", MessageId = ""isChecked"")]
public object Test(){
return N1;
}
Expand All @@ -170,49 +179,59 @@ public object Invoke2(){
return new T();
}
}");
builder.Add(@"
namespace Microsoft.CodeAnalysis.Runtime
{
public static class Instrumentation

//a09e6bef-ff64-4b5f-8bb8-fc495ebb50ba
DebugDirectoryBuilder debug = new();
debug.AddReproducibleEntry();
debug.AddReproducibleEntry();



builder.WithCodecov();
var asm = builder.GetAssembly();

//执行A.Invoke
var funcA = asm.GetDelegateFromShortName<Func<object>>("A", "Invoke");
funcA();

//执行B.Invoke2
var typeB = asm.GetType("B");
var funcB = typeB.GetMethod("Invoke2");
funcB.Invoke(Activator.CreateInstance(typeB), null);
var list = asm.GetCodecovCollection();
Show(list);


//重置
Console.WriteLine("===================Reset=============");
asm.ResetCodecov();
//执行B.Invoke2
funcB.Invoke(Activator.CreateInstance(typeB), null);
list = asm.GetCodecovCollection();
Show(list);
//Console.WriteLine(result);
}
public static void Show(List<(string MethodName, bool[] Usage)> list)
{
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int fileIndex, ref bool[] payload, int payloadLength)
{
Console.WriteLine(mvid.ToString());
if (payload == null)
for (int i = 0; i < list!.Count; i++)
{
if (list[i].Usage != null)
{
payload = new bool[payloadLength];
if (list[i].Usage.Length == 0)
{
Console.WriteLine($"{list[i].MethodName} 执行:100%");
}
else
{
var executeCount = list[i].Usage.Count(item => item);
Console.WriteLine($"{list[i].MethodName} 执行:{((double)executeCount / list[i].Usage.Length).ToString("P")}");
}
}
return payload;
}
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int[] fileIndices, ref bool[] payload, int payloadLength)
{
if (payload == null)
else
{
payload = new bool[payloadLength];
Console.WriteLine($"{list[i].MethodName} 未执行!");
}
return payload;
}
public static void FlushPayload()
{
}
}
}");
//a09e6bef-ff64-4b5f-8bb8-fc495ebb50ba
DebugDirectoryBuilder debug = new();
debug.AddReproducibleEntry();
debug.AddReproducibleEntry();
var asm = builder.GetAssembly();
var type = asm.GetType("A");
var type1 = asm.GetType("<PrivateImplementationDetails>");
var method = type.GetMethod("Invoke");
var result = method.Invoke(null, null);
//var method2 = type.GetMethod("Invoke2");
//var result2 = method2.Invoke(Activator.CreateInstance(type), null);
result = method.Invoke(null, null);
Console.WriteLine(result);
}

[MethodImpl(MethodImplOptions.NoInlining)]
Expand Down
6 changes: 4 additions & 2 deletions samples/ReferenceSample/ReferenceSample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>preview</LangVersion>
<SatelliteResourceLanguages>zh-Hans</SatelliteResourceLanguages>
</PropertyGroup>

Expand Down Expand Up @@ -33,11 +34,12 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Natasha.CSharp\Natasha.CSharp.Compiler\Natasha.CSharp.Compiler.csproj" />
<AdditionalDesignTimeBuildInput Remove="FakesAssemblies\**" />
</ItemGroup>

<ItemGroup>
<AdditionalDesignTimeBuildInput Remove="FakesAssemblies\**" />
<ProjectReference Include="..\..\src\Natasha.CSharp\Extension\Natasha.CSharp.Codecov\Natasha.CSharp.Codecov.csproj" />
<ProjectReference Include="..\HotReloadPlugin\HotReloadPlugin.csproj" />
</ItemGroup>

<!--<ItemGroup>
Expand Down
3 changes: 0 additions & 3 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@

</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" />
</ItemGroup>

<ItemGroup Condition=" '$(IsPackable)' != 'false'">
<None Include="$([MSBuild]::NormalizeDirectory('$(SolutionDir)', 'resources'))19404084.png" Link="19404084.png" Pack="true" PackagePath=""/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Natasha.CSharp.Codecov.Utils;
using System.Reflection;


public static class AssemblyExtension
{
public static List<(string MethodName, bool[] Usage)>? GetCodecovCollection(this Assembly assembly)
{
var recorder = CodecovMonitor.GetRecorderFromAssmebly(assembly);
return recorder.ToList();
}

public static void ResetCodecov(this Assembly assembly)
{
var recorder = CodecovMonitor.GetRecorderFromAssmebly(assembly);
recorder.FlushPayload();
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.CodeAnalysis.Emit;
using Natasha.CSharp.Codecov.Utils;
using System.Collections.Immutable;

public static class AssenblyCSharpBuilder
{
public static AssemblyCSharpBuilder WithCodecov(this AssemblyCSharpBuilder builder)
{
builder.ConfigEmitOptions(opt => opt.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
builder.Add(@"
namespace Microsoft.CodeAnalysis.Runtime
{
public static class Instrumentation
{
private static Natasha.CSharp.Codecov.Utils.CodecovRecorder _recorder = default!;
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int fileIndex, ref bool[] payload, int payloadLength)
{
if(_recorder == null)
{
_recorder = CodecovMonitor.GetRecorderFromType(typeof(Instrumentation));
}
return _recorder.CreatePayload(mvid, methodToken, fileIndex, ref payload, payloadLength);
}
public static bool[] CreatePayload(System.Guid mvid, int methodToken, int[] fileIndices, ref bool[] payload, int payloadLength)
{
if(_recorder == null)
{
_recorder = CodecovMonitor.GetRecorderFromType(typeof(Instrumentation));
}
return _recorder.CreatePayload(mvid, methodToken, fileIndices, ref payload, payloadLength);
}
public static void FlushPayload()
{
_recorder.FlushPayload();
}
}
}
");
builder.CompileSucceedEvent += Builder_CompileSucceedEvent;
return builder;
}

private static void Builder_CompileSucceedEvent(Microsoft.CodeAnalysis.CSharp.CSharpCompilation arg1, System.Reflection.Assembly arg2)
{
CodecovMonitor.AnalaysisAssemblyToCache(arg2);
}
}

Loading

0 comments on commit 2dc41f5

Please sign in to comment.