| Name | Message | Date |
|---|---|---|
| 📄 Cfa.Cli.csproj | 5 days ago | |
| 📄 packages.lock.json | 5 days ago | |
| 📄 Program.cs | 7 days ago | |
| 📄 ScanCommand.cs | 4 days ago |
📄
cli/src/ScanCommand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.CommandLine; using System.CommandLine.Invocation; using System.CommandLine.Parsing; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using GlobExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Spectre.Console; namespace Cfa.Cli; internal sealed class ScanCommand : Command { private static Argument<FileInfo> PathArgument { get; } = new("path") { Description = "Path to the solution file, or the directory containing it. (Defaults to the current directory.)", DefaultValueFactory = result => { var directory = new DirectoryInfo(Directory.GetCurrentDirectory()); switch ( directory .GetFiles("*.sln?", SearchOption.TopDirectoryOnly) .Where(f => f.Extension is ".sln" or ".slnx") .ToArray() ) { case []: result.AddError("No solution files found in the current directory."); return null!; case [var file]: return file; default: result.AddError("Multiple solution files found in the current directory."); return null!; } }, CustomParser = result => { if (result.Tokens is not [var token] || string.IsNullOrWhiteSpace(token.Value)) { result.AddError("No path specified."); return null; } if (Directory.Exists(token.Value)) { var directory = new DirectoryInfo(token.Value); switch ( directory .GetFiles("*.sln?", SearchOption.TopDirectoryOnly) .Where(f => f.Extension is ".sln" or ".slnx") .ToArray() ) { case []: result.AddError("No solution files found in the specified directory."); return null; case [var file]: return file; default: result.AddError("Multiple solution files found in the specified directory."); return null; } } if (File.Exists(token.Value)) { return new FileInfo(token.Value); } result.AddError("The specified path does not exist."); return null; }, }; private static Option<(FileInfo, int)> StartFileOption { get; } = new("--start-file", "-f") { Description = "The start file and line number for the analysis.", Required = true, CustomParser = result => { if (result.Tokens is not [var fileAndLine]) { result.AddError("Start file must be specified."); return default; } if (fileAndLine.Value.Split(":", 2) is not [var file, var lineString]) { result.AddError("Start file must include a line number separated by ':'."); return default; } if (!int.TryParse(lineString, out var line) || line <= 0) { result.AddError("Invalid line number specified."); return default; } return (new FileInfo(file), line); }, }; private static Option<IImmutableList<Glob>> IncludeOption { get; } = new("--include", "-i") { Description = "Glob patterns matched against project filenames (e.g. 'MyApp*.csproj'). Include projects matching any pattern.", Arity = ArgumentArity.OneOrMore, CustomParser = PatternParser, }; private static Option<IImmutableList<Glob>> ExcludeOption { get; } = new("--exclude", "-e") { Description = "Glob patterns matched against project filenames (e.g. '*Tests*'). Exclude projects matching any pattern.", Arity = ArgumentArity.OneOrMore, CustomParser = PatternParser, }; private static IImmutableList<Glob>? PatternParser(ArgumentResult result) { if (result.Tokens is []) { result.AddError("No pattern specified."); return default; } return [.. result.Tokens.Select(token => new Glob(token.Value))]; } private static Option<FileInfo> ConfigOption { get; } = new("--config") { Description = "JSON file containing message publisher and handler registration routes. (Defaults to ./.cfa.json)", }; public ScanCommand() : base("scan", "Scan the code for analysis") { Action = new ScanAction(); Arguments.Add(PathArgument); Options.Add(StartFileOption); Options.Add(IncludeOption); Options.Add(ExcludeOption); Options.Add(ConfigOption); } internal sealed class ScanAction : AsynchronousCommandLineAction { public override async Task<int> InvokeAsync(ParseResult parseResult, CancellationToken cancellationToken) { var solutionFile = parseResult.GetRequiredValue(PathArgument); var options = new ScannerOptions() { Messages = parseResult.GetValue(ConfigOption) is { FullName: var configPath } ? MessageOptions.LoadJson(configPath) : MessageOptions.LoadJson(".cfa.json", optional: true), IncludePatterns = parseResult.GetValue(IncludeOption) ?? [], ExcludePatterns = parseResult.GetValue(ExcludeOption) ?? [], }; var callGraphAnalysis = await AnsiConsole .Status() .StartAsync( "Loading solution...", async ctx => { using var scanner = await Scanner.Create(solutionFile, options, cancellationToken); ctx.Status = "Building call graph..."; var (startFile, startLine) = parseResult.GetRequiredValue(StartFileOption); var callGraph = await scanner.BuildCallGraph(startFile, startLine, cancellationToken); ctx.Status = "Analyzing call graph..."; return Analyzer.Analyze(callGraph); } ); PrintCallGraph( callGraphAnalysis.Origin, TrimToEvents(callGraphAnalysis.Origin, callGraphAnalysis.CalledFrom), callGraphAnalysis.Appearances, reverse: true ); PrintMember(callGraphAnalysis.Origin, callGraphAnalysis.Appearances[callGraphAnalysis.Origin]); PrintCallGraph( callGraphAnalysis.Origin, TrimToEvents(callGraphAnalysis.Origin, callGraphAnalysis.CallsTo), callGraphAnalysis.Appearances ); return 0; } private static IImmutableDictionary<ISymbol, IImmutableList<CallAnalysis>> TrimToEvents( ISymbol origin, IImmutableDictionary<ISymbol, IImmutableList<CallAnalysis>> links ) { var visited = new HashSet<ISymbol>(SymbolEqualityComparer.Default); Trim(origin); return links; bool Trim(ISymbol current) { if (!visited.Add(current) || !links.TryGetValue(current, out var direct)) { return false; } var sawEvent = false; foreach (var call in direct) { if (call.LinkKind is LinkKind.Event) { sawEvent |= true; Trim(call.Target); } else if (Trim(call.Target)) { sawEvent |= true; } else { direct = direct.Remove(call); } } if (sawEvent) { links = links.SetItem(current, direct); } else { links = links.Remove(current); } return sawEvent; } } private static void PrintCallGraph( ISymbol origin, IImmutableDictionary<ISymbol, IImmutableList<CallAnalysis>> links, IImmutableDictionary<ISymbol, uint> appearances, bool reverse = false, string indent = "" ) { if (!links.TryGetValue(origin, out var direct)) { return; } for (var i = 0; i < direct.Count; i++) { var target = direct[i].Target; var isEnd = reverse ? i == 0 : i == direct.Count - 1; var branch = indent + (isEnd ? (reverse ? "┌─ " : "└─ ") : "├─ "); var reach = $"({direct[i].Reach}) "; if (!reverse) { PrintMember(target, appearances[target], branch, reach); } PrintCallGraph(target, links.Remove(origin), appearances, reverse, indent + (isEnd ? " " : "│ ")); if (reverse) { PrintMember(target, appearances[target], branch, reach); } } } private static void PrintMember(ISymbol origin, uint appearances, string branch = "", string reach = "") { Console.Write(branch); Console.Write(reach); var syntaxTree = origin.DeclaringSyntaxReferences.FirstOrDefault()?.SyntaxTree; if (syntaxTree is not null) { var path = syntaxTree.FilePath; var start = syntaxTree.GetLineSpan(origin.DeclaringSyntaxReferences.First().Span).StartLinePosition; var line = start.Line + 1; var column = start.Character + 1; Console.Write($"\e]8;;file://{path}#{line}:{column}\e\\"); } Console.Write(origin); if (syntaxTree is not null) { Console.Write("\e]8;;\e\\"); } Console.Write($" ({appearances})"); Console.WriteLine(); } } }