< Summary

Information
Class: ToolCore.RoslynSearchService
Assembly: ToolCore
File(s): /home/runner/work/InvAit/InvAit/ToolCore/RoslynSearchService.cs
Tag: 194_44631168438
Line coverage
0%
Covered lines: 0
Uncovered lines: 58
Coverable lines: 58
Total lines: 139
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 32
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
FindReferencesAsync()0%600240%
FindDeclarationsAsync()0%7280%

File(s)

/home/runner/work/InvAit/InvAit/ToolCore/RoslynSearchService.cs

#LineLine coverage
 1using System.Text;
 2using Microsoft.CodeAnalysis;
 3using Microsoft.CodeAnalysis.FindSymbols;
 4using Microsoft.VisualStudio.ComponentModelHost;
 5using Microsoft.VisualStudio.LanguageServices;
 6using Shared.Contracts;
 7
 8namespace ToolCore;
 9
 10public class RoslynSearchService
 11{
 12    public async Task<VsResponse> FindReferencesAsync(object globalServiceProvider, string symbolName)
 13    {
 14        // Корректный уход на фоновый поток в .NET
 015        await Task.Yield();
 16
 17        try
 18        {
 19            // Инициализируем компоненты Roslyn внутри метода
 020            var sp = (IServiceProvider)globalServiceProvider;
 021            var componentModel = (IComponentModel)sp.GetService(typeof(SComponentModel));
 022            if (componentModel == null)
 23            {
 024                return new VsResponse { Success = false, Payload = "ComponentModel service not found." };
 25            }
 26
 027            var workspace = componentModel.GetService<VisualStudioWorkspace>();
 028            if (workspace == null)
 29            {
 030                return new VsResponse { Success = false, Payload = "VisualStudioWorkspace not found." };
 31            }
 32
 033            var solution = workspace.CurrentSolution;
 34
 35            // Находим декларации символов по текстовому имени во всем решении
 036            var symbols = (await SymbolFinder.FindSourceDeclarationsWithPatternAsync(
 037                solution,
 038                symbolName,
 039                SymbolFilter.Type | SymbolFilter.Member)).ToList();
 40
 041            if (symbols.Count == 0)
 42            {
 043                return new VsResponse { Success = false, Payload = $"Symbol '{symbolName}' isn't found." };
 44            }
 45
 046            var sb = new StringBuilder();
 47
 48            // Для каждого найденного символа
 049            foreach (var symbol in symbols)
 50            {
 51                // Вызываем поиск зависимостей
 052                var references = await SymbolFinder.FindReferencesAsync(symbol, solution);
 053                var refs = new Dictionary<string, HashSet<int>>();
 54
 055                foreach (var reference in references)
 56                {
 057                    foreach (var location in reference.Locations)
 58                    {
 059                        if (location.Document == null)
 60                            continue;
 61
 062                        if (!refs.TryGetValue(location.Document.FilePath, out var lines))
 63                        {
 064                            refs[location.Document.FilePath] = lines = new HashSet<int>();
 65                        }
 66
 067                        var linePos = location.Location.GetLineSpan().StartLinePosition.Line + 1;
 068                        lines.Add(linePos);
 69                    }
 70                }
 71
 072                if (refs.Count == 0)
 73                {
 74                    continue;
 75                }
 76
 077                sb.AppendLine($"--- References for: {symbol.ToDisplayString()} ---");
 078                foreach (var r in refs)
 79                {
 080                    var sortedLines = r.Value.OrderBy(n => n);
 081                    sb.AppendLine($"Used in: {r.Key}, line: {string.Join(", ", sortedLines)}");
 82                }
 083            }
 84
 085            return new VsResponse { Payload = sb.ToString() };
 86        }
 087        catch (Exception ex)
 88        {
 89            // Если Roslyn упадет из-за версий сборок, мы перехватим это здесь
 090            return new VsResponse { Success = false, Payload = $"Roslyn Error: {ex.Message}\n{ex.StackTrace}" };
 91        }
 092    }
 93
 94    public async Task<VsResponse> FindDeclarationsAsync(object globalServiceProvider, string symbolName)
 95    {
 96        // Уходим на фоновый поток ThreadPool
 097        await Task.Yield();
 98
 99        try
 100        {
 0101            var sp = (IServiceProvider)globalServiceProvider;
 0102            var componentModel = (IComponentModel)sp.GetService(typeof(SComponentModel));
 0103            if (componentModel == null)
 104            {
 0105                return new VsResponse { Success = false, Payload = "ComponentModel service not found." };
 106            }
 107
 0108            var workspace = componentModel.GetService<VisualStudioWorkspace>();
 0109            if (workspace == null)
 110            {
 0111                return new VsResponse { Success = false, Payload = "VisualStudioWorkspace not found." };
 112            }
 113
 0114            var solution = workspace.CurrentSolution;
 115
 116            // Находим декларации символов по текстовому имени во всем решении
 0117            var symbols = (await SymbolFinder.FindSourceDeclarationsWithPatternAsync(
 0118                solution,
 0119                symbolName,
 0120                SymbolFilter.Type | SymbolFilter.Member)).ToList();
 121
 0122            if (symbols.Count == 0)
 123            {
 0124                return new VsResponse { Success = false, Payload = $"Symbol '{symbolName}' isn't found." };
 125            }
 126
 127            // Собираем строки с информацией о декларациях
 0128            var resultLines = symbols.Select(s =>
 0129                $"{s.Name} | {s.Kind} | {s.Locations.FirstOrDefault()?.SourceTree?.FilePath}")
 0130                .ToList();
 131
 0132            return new VsResponse { Payload = string.Join("\n", resultLines) };
 133        }
 0134        catch (Exception ex)
 135        {
 0136            return new VsResponse { Success = false, Payload = $"Roslyn Error: {ex.Message}\n{ex.StackTrace}" };
 137        }
 0138    }
 139}