Skip to content

Commit a2c7d62

Browse files
committed
feat(extractor): accept .csproj/.sln input (roslyn-tools CLI-first project resolution)
The first borrowed plyushka from the roslyn-tools tooling shape: the OwnSharp Roslyn extractor now takes a .csproj or .sln as input (positional, or via --project / --solution), not just a .cs file list. ProjectCsFiles resolves a project to its source set the dependency-free way — scan the project directory for *.cs (SDK default-compile-items) plus concrete linked <Compile> files, no MSBuild evaluation; SolutionProjects fans a .sln out over its member projects. This deliberately stops short of the full project/package/reference graph (the ProjectDependencies-category work parked for DI/solution scans). - Program.cs: ProjectCsFiles + SolutionProjects helpers, wired into Expand; --project/--solution flag aliases; usage text updated. - New project-input-sample/ (outside samples/ so it doesn't perturb the directory-scan jobs): an SDK csproj + an injected-bus event leak. - CI wpf-extractor: a step pinning the .csproj path to a golden, asserting the leak surfaces as OWN001 and that positional == --project. - README + roslyn-tools-and-cli note: document the input forms; mark this plyushka landed and re-aim the next PR at extract/check/explain subcommands. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KzA6KGQVRzP52tBEKwJ3SW
1 parent ce2fee3 commit a2c7d62

6 files changed

Lines changed: 225 additions & 16 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,30 @@ jobs:
945945
fi
946946
done
947947
echo "OK: WinForms modeless Form.Show() = call-site release (framework-owned); conditional show leaks on the no-show path; modal ShowDialog() leak caught; disposed modal silent"
948+
# Project-file input (the CLI-first project/solution resolution borrowed from the
949+
# roslyn-tools tooling shape): point the extractor at a .csproj instead of a file
950+
# list and assert the same event leak surfaces. Proves ProjectCsFiles resolves the
951+
# SDK-style project to its source set and feeds the core identically to the per-file
952+
# path. Both the positional and the `--project` flag forms are exercised.
953+
- name: Project-file input (.csproj -> source set -> core)
954+
run: |
955+
dotnet run --project frontend/roslyn/OwnSharp.Extractor -- \
956+
frontend/roslyn/project-input-sample/ProjectInputSample.csproj \
957+
-o "$RUNNER_TEMP/proj-facts.json"
958+
out=$(python -m ownlang ownir "$RUNNER_TEMP/proj-facts.json" || true)
959+
echo "$out"
960+
echo "$out" | grep -q "CustomerSubscription.cs" \
961+
|| { echo "FAIL: .csproj input did not resolve CustomerSubscription.cs"; exit 1; }
962+
echo "$out" | grep -qE "CustomerSubscription\.cs:[0-9]+:.*\[OWN001\]" \
963+
|| { echo "FAIL: expected OWN001 via .csproj input"; exit 1; }
964+
# the `--project` flag form must resolve to the same source set as the positional form.
965+
dotnet run --project frontend/roslyn/OwnSharp.Extractor -- \
966+
--project frontend/roslyn/project-input-sample/ProjectInputSample.csproj \
967+
-o "$RUNNER_TEMP/proj-facts-flag.json"
968+
diff <(python -m ownlang ownir "$RUNNER_TEMP/proj-facts.json" || true) \
969+
<(python -m ownlang ownir "$RUNNER_TEMP/proj-facts-flag.json" || true) \
970+
|| { echo "FAIL: --project flag and positional .csproj disagree"; exit 1; }
971+
echo "OK: .csproj input resolves to its source set and feeds the core identically (positional == --project)"
948972
949973
# The distribution surface (Уровень 1): the own-check.sh orchestrator walks a
950974
# directory of real C# and prints findings in the host-parseable formats the

‎docs/notes/roslyn-tools-and-cli.md‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -93,20 +93,42 @@ frontend (generics / async / interprocedural dataflow) is explicitly rejected as
9393
It must **not** decide ownership, join states at merges, reason about borrows,
9494
or otherwise produce an alternative truth. One checker; the C# side feeds it.
9595

96-
## Next PR (concrete, no scope creep)
96+
## Project/solution input (landed)
9797

98-
`OwnSharp.Extractor` CLI: turn a `.csproj` into `facts.ownir.json`, then firm up
99-
the contract and a golden until it's presentable.
98+
The first borrowed plyushka is real: the extractor now accepts a `.csproj` or
99+
`.sln` as input (positional or via `--project` / `--solution`), not just a file
100+
list — the CLI-first project resolution the mature tooling repos start from.
100101

101102
```bash
102-
dotnet run --project frontend/roslyn/OwnSharp.Extractor \
103-
--project samples/WpfLeakSample/WpfLeakSample.csproj \
104-
--out artifacts/facts.ownir.json
103+
dotnet run --project frontend/roslyn/OwnSharp.Extractor -- \
104+
frontend/roslyn/project-input-sample/ProjectInputSample.csproj \
105+
-o artifacts/facts.ownir.json
105106
python -m ownlang ownir artifacts/facts.ownir.json
106-
# -> CustomerViewModel.cs:9: error: [OWN001] event 'bus.CustomerChanged'
107+
# -> CustomerSubscription.cs:11: warning: [OWN001] event 'bus.CustomerChanged'
107108
# is subscribed (handler 'OnCustomerChanged') but never unsubscribed
108109
```
109110

111+
Resolution is **dependency-free** (text/XML, no MSBuild evaluation): a `.csproj`
112+
maps to its directory's `*.cs` the SDK default-compile-items way plus concrete
113+
linked `<Compile>` files; a `.sln` fans out over its member projects (see
114+
`ProjectCsFiles` / `SolutionProjects` in `Program.cs`). It deliberately stops
115+
short of the full project/package/reference graph — that is the
116+
`ProjectDependencies`-category work, parked for DI/solution scans. A
117+
`wpf-extractor` CI step pins the `.csproj` path to a golden (positional ==
118+
`--project`).
119+
120+
## Next PR (concrete, no scope creep)
121+
122+
Firm up the rest of the advertised CLI: `extract` / `check` / `explain`
123+
subcommands (`System.CommandLine`), and `--ref-dir`-from-project-`bin`
124+
auto-derivation once `ProjectDependencies`-style graph reading lands.
125+
126+
```bash
127+
ownsharp extract --project App.csproj --out facts.ownir.json
128+
ownsharp check --solution App.sln
129+
ownsharp explain OWN001 --json diagnostic.json
130+
```
131+
110132
A facts record carries enough to place and explain the finding — kind, resource,
111133
owner, subject, location, and domain-neutral metadata:
112134

‎frontend/roslyn/OwnSharp.Extractor/Program.cs‎

Lines changed: 111 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,16 @@
1616
// `.Stop()` call. The IDisposable/pool/local detectors remain syntactic for now
1717
// (P-014 rollout: the event fact goes type-aware first).
1818
//
19-
// Usage: ownsharp-extract <file.cs | dir> [more ...] [-o facts.json]
19+
// Usage: ownsharp-extract <file.cs | dir | *.csproj | *.sln> [more ...] [-o facts.json]
20+
// ownsharp-extract --project App.csproj (flag twin of the positional form)
21+
// ownsharp-extract --solution App.sln
2022
//
21-
// Inputs may be .cs files or directories. A directory is walked recursively for
22-
// *.cs, skipping build output (bin/obj), VCS/vendor dirs (.git, node_modules)
23-
// and generated files (*.g.cs, *.Designer.cs) — so you can point it at a whole
24-
// repo (this is what the `own-check` script / GitHub Action do).
23+
// Inputs may be .cs files, directories, a .csproj, or a .sln. A directory is walked
24+
// recursively for *.cs, skipping build output (bin/obj), VCS/vendor dirs (.git,
25+
// node_modules) and generated files (*.g.cs, *.Designer.cs) — so you can point it at a
26+
// whole repo (this is what the `own-check` script / GitHub Action do). A .csproj resolves
27+
// to its source set (SDK-style directory scan + concrete linked <Compile> files; no full
28+
// MSBuild evaluation — see ProjectCsFiles); a .sln fans out over its member projects.
2529

2630
using System.Text.Json;
2731
using System.Xml.Linq;
@@ -67,6 +71,11 @@
6771
for (int i = 0; i < args.Length; i++)
6872
{
6973
if (args[i] == "-o" && i + 1 < args.Length) outPath = args[++i];
74+
// `--project <App.csproj>` / `--solution <App.sln>`: the explicit-flag twin of passing the
75+
// project/solution as a positional input (both resolve through Expand). The flag form matches
76+
// the advertised `ownsharp extract --project ...` UX borrowed from the roslyn-tools CLI shape;
77+
// the positional form keeps the command unambiguous next to dotnet's own `run --project`.
78+
else if ((args[i] == "--project" || args[i] == "--solution") && i + 1 < args.Length) rawInputs.Add(args[++i]);
7079
else if (args[i] == "--ref-dir" && i + 1 < args.Length) refDirs.Add(args[++i]);
7180
else if (args[i] == "--no-event-leaks") emitEvents = false;
7281
else if (args[i] == "--flow-locals") flowLocals = true;
@@ -77,7 +86,7 @@
7786

7887
if (rawInputs.Count == 0)
7988
{
80-
Console.Error.WriteLine("usage: ownsharp-extract <file.cs | dir> [...] [-o facts.json] [--ref-dir <bin-dir>]");
89+
Console.Error.WriteLine("usage: ownsharp-extract <file.cs | dir | *.csproj | *.sln> [...] [-o facts.json] [--ref-dir <bin-dir>]");
8190
return 2;
8291
}
8392

@@ -113,9 +122,91 @@ static bool IsSkipped(string path)
113122
return IsGenerated(path);
114123
}
115124

116-
// Expand directories into their .cs files; pass explicit files through as-is.
117-
// IgnoreInaccessible tolerates an unreadable subdir mid-walk (otherwise the
118-
// whole scan would abort with an unhandled exception on a locked directory).
125+
// Resolve a `.csproj` to its C# source set. Doing this the MSBuild way needs a full
126+
// project evaluation (and the `Microsoft.CodeAnalysis.Workspaces.MSBuild` + MSBuildLocator
127+
// dependency that P-014 / the "ProjectDependencies as a category" note deliberately parks
128+
// for the DI/solution-graph work — not for the v0 leak extractor). The pragmatic resolution
129+
// that covers the SDK-style common case WITHOUT that baggage: scan the project's directory
130+
// recursively for *.cs — exactly the SDK default-compile-items behaviour, with bin/obj and
131+
// generated files already excluded by IsSkipped — and additionally pick up any concrete
132+
// linked `<Compile Include="..\Shared\Foo.cs" />` that points OUTSIDE the project tree.
133+
// This can over-approximate a legacy explicit-list project (it analyses sibling *.cs the
134+
// project might exclude), which for a fact extractor is harmless: it never invents files,
135+
// it only reads a few extra. Globs inside <Compile Include> are left to the directory scan.
136+
// Builds a list rather than yielding so the XML read can sit in a try/catch (an iterator
137+
// may not yield from inside one) and a malformed project degrades to the directory scan.
138+
static List<string> ProjectCsFiles(string csproj, EnumerationOptions opts)
139+
{
140+
var full = Path.GetFullPath(csproj);
141+
var dir = Path.GetDirectoryName(full) ?? ".";
142+
var result = new List<string>();
143+
foreach (var f in Directory.EnumerateFiles(dir, "*.cs", opts))
144+
if (!IsSkipped(f))
145+
result.Add(f);
146+
147+
XDocument? doc = null;
148+
try { doc = XDocument.Load(full); }
149+
catch (Exception ex)
150+
{
151+
Console.Error.WriteLine(
152+
$"ownsharp-extract: {csproj}: reading <Compile> links failed ({ex.Message}); used directory scan only");
153+
}
154+
155+
var dirPrefix = dir.EndsWith(Path.DirectorySeparatorChar) ? dir : dir + Path.DirectorySeparatorChar;
156+
foreach (var inc in (doc?.Descendants() ?? Enumerable.Empty<XElement>())
157+
.Where(e => e.Name.LocalName == "Compile")
158+
.Select(e => e.Attribute("Include")?.Value)
159+
.Where(v => !string.IsNullOrWhiteSpace(v)))
160+
{
161+
if (inc!.IndexOfAny(new[] { '*', '?' }) >= 0) continue; // a glob — the dir scan covers it
162+
var path = Path.GetFullPath(Path.Combine(dir, inc.Replace('\\', Path.DirectorySeparatorChar)));
163+
if (path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)
164+
&& File.Exists(path) && !IsSkipped(path)
165+
&& !path.StartsWith(dirPrefix, StringComparison.Ordinal)) // in-dir links already yielded
166+
result.Add(path);
167+
}
168+
return result;
169+
}
170+
171+
// Resolve a classic `.sln` to its member `.csproj` paths. The solution file lists each project
172+
// as `Project("{type-guid}") = "Name", "rel\path.csproj", "{guid}"`; solution folders use the
173+
// same line shape but their path is not a `.csproj`, so filtering on the extension drops them.
174+
// Text parsing (no MSBuild) keeps this dependency-free; a missing member is reported and skipped,
175+
// never fatal — a solution-wide scan should survive one stale project reference.
176+
static List<string> SolutionProjects(string sln)
177+
{
178+
var dir = Path.GetDirectoryName(Path.GetFullPath(sln)) ?? ".";
179+
var projects = new List<string>();
180+
string[] lines;
181+
try { lines = File.ReadAllLines(sln); }
182+
catch (Exception ex)
183+
{
184+
Console.Error.WriteLine($"ownsharp-extract: cannot read solution {sln} ({ex.Message})");
185+
return projects;
186+
}
187+
foreach (var line in lines)
188+
{
189+
var t = line.TrimStart();
190+
if (!t.StartsWith("Project(", StringComparison.Ordinal)) continue;
191+
var eq = t.IndexOf('=');
192+
if (eq < 0) continue;
193+
// After '=' the fields are comma-separated, each double-quoted: "Name", "relpath", "{guid}".
194+
var parts = t.Substring(eq + 1).Split(',');
195+
if (parts.Length < 2) continue;
196+
var rel = parts[1].Trim().Trim('"');
197+
if (!rel.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) continue;
198+
var path = Path.GetFullPath(Path.Combine(dir, rel.Replace('\\', Path.DirectorySeparatorChar)));
199+
if (File.Exists(path)) projects.Add(path);
200+
else Console.Error.WriteLine($"ownsharp-extract: {sln}: project not found: {rel}");
201+
}
202+
return projects;
203+
}
204+
205+
// Expand inputs into their .cs files. A directory is walked recursively; a `.csproj`/`.sln`
206+
// is resolved to its source set (so `ownsharp-extract App.csproj` / `App.sln` works, the
207+
// CLI-first project input borrowed from the roslyn-tools tooling shape); an explicit file
208+
// passes through as-is. IgnoreInaccessible tolerates an unreadable subdir mid-walk (otherwise
209+
// the whole scan would abort with an unhandled exception on a locked directory).
119210
static IEnumerable<string> Expand(IEnumerable<string> roots)
120211
{
121212
var opts = new EnumerationOptions
@@ -131,6 +222,17 @@ static IEnumerable<string> Expand(IEnumerable<string> roots)
131222
if (!IsSkipped(f))
132223
yield return f;
133224
}
225+
else if (p.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
226+
{
227+
foreach (var proj in SolutionProjects(p))
228+
foreach (var f in ProjectCsFiles(proj, opts))
229+
yield return f;
230+
}
231+
else if (p.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase))
232+
{
233+
foreach (var f in ProjectCsFiles(p, opts))
234+
yield return f;
235+
}
134236
else
135237
{
136238
yield return p;

‎frontend/roslyn/README.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,28 @@ python -m ownlang ownir facts.json
2828
# (OrdersViewModel unsubscribes in Dispose -> nothing reported)
2929
```
3030

31+
### Inputs: files, directories, `.csproj`, `.sln`
32+
33+
Inputs may be `.cs` files, directories (walked recursively, skipping `bin`/`obj`/
34+
generated), a **`.csproj`**, or a **`.sln`** — so you can hand the extractor a
35+
project or solution the way the borrowed roslyn-tools CLI shape advertises:
36+
37+
```bash
38+
dotnet run --project OwnSharp.Extractor -- App.csproj -o facts.json # positional
39+
dotnet run --project OwnSharp.Extractor -- --project App.csproj -o facts.json
40+
dotnet run --project OwnSharp.Extractor -- --solution App.sln -o facts.json
41+
```
42+
43+
A `.csproj` resolves to its source set by scanning the project's directory for
44+
`*.cs` (the SDK default-compile-items behaviour) plus any concrete linked
45+
`<Compile Include="..\Shared\Foo.cs" />` outside the project tree; a `.sln` fans
46+
out over its member projects. This is a **dependency-free** resolution (text/XML,
47+
no MSBuild evaluation), so it can over-approximate a legacy explicit-list project —
48+
harmless for a fact extractor, which never invents files. Full MSBuild evaluation
49+
(and the project/package/reference graph) is the `ProjectDependencies`-category
50+
work parked for DI/solution scans, not the v0 leak extractor — see
51+
[`docs/notes/roslyn-tools-and-cli.md`](../../docs/notes/roslyn-tools-and-cli.md).
52+
3153
## Use it on a real repo / in CI (P-013)
3254

3355
The two stages are chained by one orchestrator script, so you don't run them by
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System;
2+
3+
// SUBSCRIPTION LEAK, discovered via PROJECT-FILE input (not an explicit file list).
4+
// The extractor is pointed at ProjectInputSample.csproj; ProjectCsFiles resolves the
5+
// project to this source file (SDK default-compile-items directory scan), so the same
6+
// `bus.CustomerChanged += handler` with no matching `-=` surfaces as OWN001 — proving
7+
// the .csproj seam feeds the core exactly as the per-file path does.
8+
public sealed class CustomerSubscription
9+
{
10+
public CustomerSubscription(IEventBus bus)
11+
{
12+
bus.CustomerChanged += OnCustomerChanged; // no matching -= anywhere -> leak
13+
}
14+
15+
private void OnCustomerChanged(object? sender, EventArgs e) { }
16+
}
17+
18+
// Local event-bus contract so the subscription binds type-aware (P-014 Tier A) without
19+
// an external reference — keeps this sample self-contained (no OWN050 "unchecked" note).
20+
public interface IEventBus
21+
{
22+
event EventHandler CustomerChanged;
23+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<!-- A throwaway SDK-style project used only to exercise project-file input
4+
resolution (pointing ownsharp-extract at App.csproj rather than a file list).
5+
It is never built or referenced by the extractor's own build; the extractor
6+
reads it only as a source manifest (ProjectCsFiles scans this directory for
7+
.cs files the SDK-default way). The CI wpf-extractor job points the extractor
8+
at this csproj and asserts the known event leak in CustomerSubscription.cs
9+
surfaces as OWN001, proving the project-input seam matches the per-file path. -->
10+
<PropertyGroup>
11+
<OutputType>Library</OutputType>
12+
<TargetFramework>net8.0</TargetFramework>
13+
<Nullable>enable</Nullable>
14+
</PropertyGroup>
15+
16+
</Project>

0 commit comments

Comments
 (0)