Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install find-untested-sources@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin find-untested-sources v1.0.0 follows the Agent Plugins spec.
gh skills-hub install find-untested-sources Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/find-untested-sources/ Extract the ZIP to .github/skills/ in your repo. The folder name must match find-untested-sources for Copilot to auto-discover it.
Skill Files (3)
SKILL.md 13.0 KB
---
name: find-untested-sources
description: >
MANDATORY for static source-to-test pairing: find or list source files/modules
without corresponding tests, or suggest test locations from repository
structure. Invoke even for a tiny package; do not substitute manual globbing.
Uses Roslyn for C#/.NET and tree-sitter for Python, TS/JS, Go, Java, Rust,
Ruby, Kotlin, Swift, PowerShell, and C++. DO NOT USE FOR: real
line/branch/Cobertura data, coverage-backed test priorities, CRAP risk, or
grading existing tests.
license: MIT
---
# Find Untested Sources
## Purpose
Coverage tools answer "which lines were executed?" — they require a green build
and a passing test run, which is minutes-to-tens-of-minutes on a real repo. The
question this skill answers is different and much cheaper:
> _Which source files have no test file referencing any of their declared
> types/symbols?_
That's the question an agent asks **before** writing a new test — and it can be
answered statically in a few seconds by parsing source files, with **no build,
no dependency resolution, and no compilation**. The output is a deterministic
test-pairing map that lets the agent pick the next file to test without reading
the entire codebase first.
## Two engines — pick one
This skill ships two interchangeable analyzers with a compatible JSON contract:
| Engine | Script | Use when |
|--------|--------|----------|
| **Roslyn (C#)** | `scripts/Find-UntestedSources.cs` | The repo is **.NET-only**. Parses every `.cs` file with the Roslyn syntax API and does strict **namespace disambiguation**, so it is materially more accurate on duplicated short names like `Settings` or `Context`. |
| **tree-sitter (polyglot)** | `scripts/find_untested_sources.py` | The repo is **not exclusively C#**, or you want one tool across C#, Python, TypeScript/JavaScript, Go, Java, Rust, Ruby, Kotlin, Swift, PowerShell, and C++. |
For a .NET-only repository, **prefer the Roslyn engine** — its namespace-aware
pairing beats the polyglot engine's identifier overlap.
## Required workflow
1. Use the narrowest repository or package root named by the caller. Do not scan
a parent workspace when the request identifies a subdirectory.
2. Execute the appropriate analyzer once. Do not replace analyzer execution with
manual globbing, filename matching, or visual inspection.
For polyglot analysis, pass `--include-tested` when the answer must distinguish
paired sources from unpaired sources.
"Static pairing only" prohibits compiling the target repository and running
its tests; it does not prohibit launching this skill's parse-only analyzer.
State that distinction briefly when the caller also says "do not build."
Treat analyzer dependencies as environment prerequisites: do not install
packages, try the wrong engine, build the repository, or fall back to a manual
scan when an analyzer invocation fails. Report the prerequisite failure instead.
3. Base the result on the analyzer's JSON. Preserve its paired/unpaired
classification and suggested relative path; do not guess a different path.
4. When the caller named a subdirectory, prefix analyzer-relative paths with
that subdirectory so reported paths are workspace-relative.
5. Report the requested result plus the static-pairing coverage caveat. Do not
append build, package-install, test-run, or coverage commands. When paired
sources exist, name their covering test files so the unpaired classification
is auditable.
## When to Use
- User asks "where should I add tests based on source pairing?", "which files
have no tests?", "find unpaired source files", or "give me a static test gap
list".
- Before invoking a test-generation agent, to produce a source-pairing worklist.
- After generating tests, to verify each new test file pairs to a source file.
- To enumerate "weakly paired" source files (only one referring test) for
follow-up depth checks.
## When Not to Use
- **Line/branch coverage** — use `coverage-analysis`.
- **Priorities derived from real coverage data** — use `coverage-analysis`.
- **CRAP-score / risk hotspots** — use `coverage-analysis`.
- **Are existing tests strong?** — use `test-gap-analysis` (mutation reasoning)
or `assertion-quality`.
## Roslyn engine (C#)
### Prerequisites
- .NET SDK that supports file-based apps (`dotnet run script.cs`). Pinned in the
repo's `global.json` (SDK 11 preview or later).
- No internet access required beyond the initial NuGet restore of
`Microsoft.CodeAnalysis.CSharp` on first run.
### Usage
```powershell
# From the skill folder
dotnet run scripts/Find-UntestedSources.cs -- <repo-root> [--top N]
# Save the report
dotnet run scripts/Find-UntestedSources.cs -- <repo-root> > pairing.json
# Iterate the untested list, highest-API-surface first
$report = Get-Content pairing.json | ConvertFrom-Json
$report.untested | Select-Object -First 10 source, decl_count, suggested_test_path
```
Diagnostics go to stderr; JSON goes to stdout.
### Output schema
```jsonc
{
"repo": "<absolute path>",
"elapsed_ms": 8883,
"counts": {
"source_files": 3036,
"test_files": 867,
"untested_files": 1852,
"paired_files": 1184
},
"untested": [
{
"source": "src/Foo/Bar.cs",
"decl_count": 8, // # of type declarations in the file
"suggested_test_path": // mirror of source under a discovered test project
"tests/Foo.Tests/Bar/BarTests.cs"
}
],
"source_to_tests": {
"src/Foo/Baz.cs": [
"tests/Foo.Tests/BazTests.cs",
"tests/Foo.IntegrationTests/Scenarios/BazScenarios.cs"
]
}
}
```
### How it works
1. **File discovery** — recursive walk pruning `bin/`, `obj/`, `node_modules/`,
`.git/`, `.vs/`, `packages/`, and any dotted subdir. Skips generated files
(`.g.cs`, `.Designer.cs`, `.AssemblyInfo.cs`).
2. **Test vs source classification** — walks up to the nearest `.csproj` and
marks it a test project if the project name ends in `.Tests`, `.Test`,
`.UnitTests`, `.IntegrationTests`, `.E2E`, `.EndToEnd`, `.Spec`, `.Specs`, or
the content references `Microsoft.NET.Test.Sdk`, `MSTest.Sdk`,
`Microsoft.Testing.Platform`, `xunit`, `NUnit`, `TUnit`, or
`<IsTestProject>true</IsTestProject>`.
3. **Source index (parallel)** — parse each source file with
`CSharpSyntaxTree.ParseText` (syntax only, no compilation); record every
`BaseTypeDeclarationSyntax` / `DelegateDeclarationSyntax` as
`(ShortName, EnclosingNamespace, FilePath)`.
4. **Test scan (parallel)** — parse each test file, collect `using` directives +
enclosing namespace, walk every `IdentifierToken`, look it up in the
short-name index, and **disambiguate strictly**: an identifier is attributed
only if the declaration's namespace matches one of the test file's `using`
directives, the enclosing namespace, or a prefix of them. This avoids noise
where common names like `Settings` or `Context` match every project.
5. **Pairing & suggestion** — invert into `source → [tests]`. Build a
production-to-test project map from `<ProjectReference>` entries; for each
untested source, mirror its in-project relative path under the referencing
test project to suggest a path.
6. **JSON emit** — ordered by declaration count desc, then alphabetical.
## Polyglot engine (tree-sitter)
### Prerequisites
- Python 3.10+.
- `pip install tree-sitter-language-pack` (single self-contained wheel that
bundles parsers for 300+ languages and the high-level `process()` API). No
native build, no per-language grammar install.
### Usage
```powershell
# From the skill folder
python scripts/find_untested_sources.py <repo-root>
# Restrict to a language (repeatable)
python scripts/find_untested_sources.py <repo-root> --lang python --lang typescript
# Truncate the report (top 20 by declared API surface)
python scripts/find_untested_sources.py <repo-root> --limit-untested 20 > pairing.json
# Iterate, highest-API-surface first
$report = Get-Content pairing.json | ConvertFrom-Json
$report.untested_sources | Select-Object -First 10 path, declaration_count, suggested_test_path
```
Pass `--include-tested` to additionally emit `tested_sources` (omitted by
default to keep the payload small for LLM consumption). Diagnostics go to
stderr; JSON goes to stdout.
### Output schema
```jsonc
{
"repo_root": "<absolute path>",
"summary": {
"source_files": 3138,
"test_files": 761,
"tested_source_files": 1419,
"untested_source_files": 1719,
"orphan_test_files": 15,
"languages": ["csharp"]
},
"untested_sources": [
{
"path": "src/Foo/Bar.cs",
"language": "csharp",
"declaration_count": 8,
"declarations": ["Bar", "BarOptions", "IBar", "..."],
"suggested_test_path": "src/Foo/BarTests.cs"
}
],
"orphan_tests": [
{ "path": "tests/SomeIntegrationTest.cs", "language": "csharp" }
]
}
```
### How it works
1. **File discovery** — recursive walk pruning common build/vendor dirs (`bin`,
`obj`, `node_modules`, `target`, `dist`, `build`, `vendor`, `__pycache__`,
`.venv`, `.git`, …) and generated files (`.d.ts`, `.g.cs`, `.Designer.cs`,
`_pb2.py`, `*.min.js`, `AssemblyInfo.cs`, …).
2. **Language detection** — `detect_language_from_path` maps the extension to a
supported language; unknown extensions are skipped.
3. **Test-vs-source classification** — per-language path heuristics:
| Language | Test rule |
|---|---|
| Python | path contains `tests/`/`test/`; or filename starts with `test_` or ends `_test.py`; or `conftest.py`. |
| JS/TS/TSX | path contains `__tests__`, `tests`, `test`, `spec`, `e2e`; or filename contains `.test.`/`.spec.`. |
| Go | filename ends `_test.go`. |
| Java | path contains `test`/`tests`; or filename ends `Test.java`/`Tests.java`. |
| Rust | path contains `tests/`/`benches/`. |
| C# | path contains `tests/`; or project segment ends `.Tests`/`.Test`/`.UnitTests`/`.IntegrationTests`; or filename ends `Tests`/`Test`. |
| Ruby | path contains `spec/`/`test/`; or filename ends `_spec.rb`/`_test.rb`. |
| Kotlin | path contains `test/`/`tests/`/`spec/`; or filename ends `Test.kt`/`Tests.kt`/`Spec.kt`. |
| Swift | path contains `test/`/`tests/`/`uitests/`/`integrationtests/` (case-insensitive); or filename ends `Test.swift`/`Tests.swift`. |
| PowerShell | path contains `test/`/`tests/`/`pester/`; or filename ends `.Tests.ps1`/`.Test.ps1`. |
| C++ | path contains `test/`/`tests/`/`testing/`; or filename starts `test_` or ends `_test.cpp`/`_tests.cpp`. |
4. **Per-file extraction** — `process(text, ProcessConfig(structure, imports,
symbols))` returns declared items, raw import statements, and a flat declared
-name list.
5. **Pairing** — for each test file, union **import resolution** (per language,
e.g. Python `from pkg.mod import x` → `pkg/mod.py`; Java `import a.b.C;` →
`a/b/C.java`; C# `using` is namespace-not-file, so a no-op) with **identifier
overlap** (word-like tokens, length ≥ 4, matched against declared names).
6. **JSON emit** — `untested_sources` ordered by declaration count descending.
## Limitations (be honest with the agent)
Both engines are static, parse-only heuristics that trade a little accuracy for
orders-of-magnitude lower cost than coverage. Known gaps:
- **Reflection / DI-resolved types** referenced only via a string name or
container resolution won't be detected — the type's short name never appears
in the test source.
- **Extension methods** invoked as instance methods (C#): the declaring static
class is not named, so its file is not credited.
- **`var`, target-typed `new()`, pattern matching** lose the type token; the
file-level union usually still catches it through other references.
- **Short identifier names** (polyglot, < 4 chars) are dropped to avoid noisy
pairings on names like `id`, `db`, `Tag`.
- **Monorepo path aliases** (TS path mapping, Java module-info) are not
resolved; a suffix-match fallback may pick the wrong source if two files share
a trailing path segment.
For these cases, run actual coverage (`coverage-analysis`) on the unpaired
candidates the agent has already triaged.
Always label the final result as a static pairing heuristic, not evidence of
line or branch coverage. Include that caveat even when every requested source
file has an obvious matching or missing test.
## Outputs the agent should consume
- `untested[*].source` / `untested_sources[*].path` — pick the next source file
to test (highest declaration count first).
- `*.suggested_test_path` — drop-in target for the new test file; the Roslyn
engine honors the test project that already `<ProjectReference>`s the source's
project, so `dotnet sln add` is not needed. The polyglot engine may suggest a
co-located test when no test root is discoverable. When a source sibling is
already paired, its test directory is the established convention and must be
reused for the missing sibling rather than falling back to source co-location.
- `source_to_tests` (Roslyn) / `--include-tested` `tested_sources` (polyglot) —
verify a newly written test file lands in the list for the intended source.
- `orphan_tests` (polyglot) — tests that don't reference any same-language
source file; useful for triaging stale or integration-only tests.
Find-UntestedSources.cs 24.0 KB
#:package Microsoft.CodeAnalysis.CSharp@4.14.0
#:property PublishAot=false
// Find-UntestedSources.cs
//
// Static, parse-only analysis (no compilation, no metadata, no test execution)
// that produces a JSON report of which C# source files have at least one C#
// test file referencing one of their declared types, and which do not.
//
// Pipeline:
// 1. Walk the repo for *.cs (skip bin/obj/.g.cs/.Designer.cs).
// 2. Classify each file as test vs source by walking up to the nearest .csproj
// and checking for Microsoft.NET.Test.Sdk / MSTest.Sdk / Microsoft.Testing.Platform
// references, or a project name ending in .Tests / .Test / .UnitTests /
// .IntegrationTests / .E2E / .EndToEnd.
// 3. Build a source index in parallel: per source file, parse with
// CSharpSyntaxTree.ParseText (NO Compilation, NO MetadataReferences),
// record every class/record/struct/interface/enum/delegate declaration
// as (ShortName, Namespace, File).
// 4. Scan each test file in parallel: parse, collect `using` directives and
// enclosing namespace, walk identifier tokens, look them up in the index,
// disambiguate by namespace match against the test file's usings.
// 5. Invert into source -> [tests] map, identify unreferenced source files,
// and emit JSON sorted by declaration count descending (highest API
// surface first).
//
// Output: JSON to stdout. Diagnostics to stderr.
//
// Usage:
// dotnet run Find-UntestedSources.cs -- <repo-root> [--top N]
//
// Output schema:
// {
// "repo": "<abs path>",
// "counts": { "source_files", "test_files", "untested_files", "paired_files" },
// "untested": [ { "source", "decl_count", "suggested_test_path" }, ... ],
// "source_to_tests": { "<source>": ["<test1>", "<test2>", ...], ... }
// }
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
bool jsonV1 = args.Contains("json-v1", StringComparer.Ordinal);
int topN = int.MaxValue;
bool includeTested = false;
if (args.Length < 1)
{
Console.Error.WriteLine("usage: dotnet run Find-UntestedSources.cs -- <repo-root> [--top N] [--include-tested] [--output-format legacy|json-v1]");
return 1;
}
for (int i = 1; i < args.Length; i++)
{
if (args[i] == "--include-tested") { includeTested = true; continue; }
if (args[i] == "--output-format" && i + 1 < args.Length && args[i + 1] is "legacy" or "json-v1")
{
jsonV1 = args[++i] == "json-v1";
continue;
}
if ((args[i] == "--top" || args[i] == "--limit-untested") && i + 1 < args.Length &&
int.TryParse(args[i + 1], out int n) && n >= 0)
{
topN = n == 0 ? int.MaxValue : n;
i++;
continue;
}
return InputError($"Invalid argument: {args[i]}", jsonV1);
}
string root;
try { root = Path.GetFullPath(args[0]); }
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException)
{
return InputError(ex.Message, jsonV1);
}
if (!Directory.Exists(root)) { return InputError($"Not a directory: {root}", jsonV1); }
var swTotal = System.Diagnostics.Stopwatch.StartNew();
// 1. Discover .cs files
var allCs = new List<string>();
foreach (var f in EnumerateSourceFiles(root, "*.cs"))
{
allCs.Add(f);
}
Log($"Discovered {allCs.Count} .cs files");
// 2. Classify by walking up to nearest .csproj
var projectForDir = new ConcurrentDictionary<string, ProjectLookup>(StringComparer.OrdinalIgnoreCase);
var isTestProject = new ConcurrentDictionary<string, bool?>(StringComparer.OrdinalIgnoreCase);
ProjectLookup ProjectFor(string filePath)
{
var dir = Path.GetDirectoryName(filePath)!;
return projectForDir.GetOrAdd(dir, d =>
{
var cur = d;
while (cur is not null && cur.Length >= root.Length)
{
string[] csprojs;
try { csprojs = Directory.GetFiles(cur, "*.csproj"); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Report("PROJECT_DISCOVERY_FAILED", cur, ex.Message);
return new ProjectLookup(null, false);
}
if (csprojs.Length > 0)
{
if (csprojs.Length > 1)
{
Report("PROJECT_AMBIGUOUS", cur, "Multiple nearest project files; classification is unresolved.");
return new ProjectLookup(null, false);
}
return new ProjectLookup(csprojs[0], true);
}
cur = Path.GetDirectoryName(cur);
}
return new ProjectLookup(null, true);
});
}
bool? IsTest(string filePath)
{
var lookup = ProjectFor(filePath);
if (!lookup.IsResolved)
{
return null;
}
if (lookup.Path is null)
{
return false;
}
return isTestProject.GetOrAdd(lookup.Path, ClassifyProjectAsTest);
}
var sourceFiles = new List<string>();
var testFiles = new List<string>();
foreach (var f in allCs)
{
var classification = IsTest(f);
if (classification is null)
{
Report("CLASSIFICATION_UNKNOWN", f, "Nearest project discovery or classification could not be completed.");
continue;
}
if (classification.Value)
{
testFiles.Add(f);
}
else
{
sourceFiles.Add(f);
}
}
Log($"Classified: {sourceFiles.Count} source, {testFiles.Count} test");
// 3. Build source index (parse-only, no Compilation)
var declsByShort = new ConcurrentDictionary<string, List<Decl>>(StringComparer.Ordinal);
var declsByFile = new ConcurrentDictionary<string, int>(StringComparer.Ordinal);
var swIndex = System.Diagnostics.Stopwatch.StartNew();
Parallel.ForEach(sourceFiles, file =>
{
var rootNode = ReadSyntax(file);
if (rootNode is null) { return; }
int count = 0;
foreach (var node in rootNode.DescendantNodes())
{
string? name = node switch
{
BaseTypeDeclarationSyntax t => t.Identifier.ValueText,
DelegateDeclarationSyntax d => d.Identifier.ValueText,
_ => null,
};
if (name is null || name.Length == 0)
{
continue;
}
var ns = GetNamespaceFor(node);
var decl = new Decl(name, ns, file);
var list = declsByShort.GetOrAdd(name, _ => new List<Decl>());
lock (list)
{
list.Add(decl);
}
count++;
}
declsByFile[file] = count;
});
swIndex.Stop();
Log($"Indexed {sourceFiles.Count} source files in {swIndex.ElapsedMilliseconds} ms ({declsByShort.Count} distinct short names)");
// 4. Scan test files
var sourceToTests = new ConcurrentDictionary<string, ConcurrentDictionary<string, byte>>(StringComparer.Ordinal);
foreach (var s in sourceFiles)
{
sourceToTests[s] = new ConcurrentDictionary<string, byte>(StringComparer.Ordinal);
}
var swScan = System.Diagnostics.Stopwatch.StartNew();
Parallel.ForEach(testFiles, file =>
{
var rootNode = ReadSyntax(file);
if (rootNode is null) { return; }
var usings = new HashSet<string>(StringComparer.Ordinal);
foreach (var u in rootNode.DescendantNodes().OfType<UsingDirectiveSyntax>())
{
var nm = u.Name?.ToString();
if (!string.IsNullOrEmpty(nm))
{
usings.Add(nm);
}
}
var localNs = rootNode.DescendantNodes().OfType<BaseNamespaceDeclarationSyntax>()
.FirstOrDefault()?.Name.ToString() ?? "";
var ids = new HashSet<string>(StringComparer.Ordinal);
foreach (var tok in rootNode.DescendantTokens())
{
if (tok.IsKind(SyntaxKind.IdentifierToken))
{
ids.Add(tok.ValueText);
}
}
var refs = new HashSet<string>(StringComparer.Ordinal);
foreach (var id in ids)
{
if (!declsByShort.TryGetValue(id, out var decls))
{
continue;
}
List<Decl>? preferred = null;
foreach (var d in decls)
{
// Declarations in the global namespace are visible without a
// using directive, so accept them unconditionally. (Skipping
// them previously meant types declared without a namespace were
// never attributed to any test file.)
if (d.Namespace.Length == 0
|| usings.Contains(d.Namespace)
|| d.Namespace == localNs
|| (localNs.Length > 0 && localNs.StartsWith(d.Namespace + ".", StringComparison.Ordinal))
|| IsUsingPrefix(usings, d.Namespace))
{
(preferred ??= new List<Decl>()).Add(d);
}
}
// Strict: skip identifiers whose declarations don't match any namespace
// visible to this test file. Avoids the noise where a common identifier
// (e.g., a type name shared across unrelated projects) gets attributed
// to every file declaring something with the same short name.
if (preferred is null)
{
continue;
}
foreach (var d in preferred)
{
refs.Add(d.File);
}
}
foreach (var src in refs)
{
sourceToTests[src][file] = 0;
}
});
swScan.Stop();
Log($"Scanned {testFiles.Count} test files in {swScan.ElapsedMilliseconds} ms");
// 5. Build suggested test paths for untested files
var untested = sourceToTests
.Where(kv => kv.Value.IsEmpty && !AnalysisState.FailedFiles.ContainsKey(kv.Key))
.Select(kv => kv.Key)
.OrderBy(s => s, StringComparer.Ordinal)
.ToList();
// Cache: source proj -> candidate test project paths
var testProjectsByProductionProject = BuildProductionToTestProjectMap(root);
string? SuggestTestPath(string srcFile)
{
var lookup = ProjectFor(srcFile);
var proj = lookup.Path;
if (!lookup.IsResolved || proj is null)
{
return null;
}
if (!testProjectsByProductionProject.TryGetValue(proj, out var testProj))
{
return null;
}
var srcProjDir = Path.GetDirectoryName(proj)!;
var testProjDir = Path.GetDirectoryName(testProj)!;
var rel = Path.GetRelativePath(srcProjDir, srcFile);
var relDir = Path.GetDirectoryName(rel) ?? "";
var fname = Path.GetFileNameWithoutExtension(rel);
return Path.Combine(testProjDir, relDir, fname + "Tests.cs");
}
// 6. Emit JSON
var untestedReport = untested.Select(s => new
{
source = ToRel(root, s),
decl_count = declsByFile.TryGetValue(s, out var c) ? c : 0,
suggested_test_path = SuggestTestPath(s) is string p ? ToRel(root, p) : null,
})
.OrderByDescending(x => x.decl_count)
.ThenBy(x => x.source, StringComparer.Ordinal)
.Take(topN)
.ToList();
var pairedReport = new SortedDictionary<string, List<string>>(StringComparer.Ordinal);
foreach (var kv in sourceToTests)
{
if (kv.Value.IsEmpty)
{
continue;
}
pairedReport[ToRel(root, kv.Key)] = kv.Value.Keys
.Select(t => ToRel(root, t))
.OrderBy(s => s, StringComparer.Ordinal)
.ToList();
}
swTotal.Stop();
var result = new
{
repo = root,
elapsed_ms = swTotal.ElapsedMilliseconds,
counts = new
{
source_files = sourceFiles.Count,
test_files = testFiles.Count,
untested_files = untested.Count,
paired_files = sourceFiles.Count - untested.Count,
},
untested = untestedReport,
source_to_tests = pairedReport,
};
var opts = new JsonSerializerOptions
{
WriteIndented = true,
TypeInfoResolver = new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver(),
};
var diagnostics = AnalysisState.Diagnostics
.OrderBy(d => d.path, StringComparer.Ordinal).ThenBy(d => d.code, StringComparer.Ordinal)
.ThenBy(d => d.message, StringComparer.Ordinal).Distinct().ToArray();
foreach (var diagnostic in diagnostics) { Console.Error.WriteLine($"{diagnostic.code}: {diagnostic.path}: {diagnostic.message}"); }
if (jsonV1)
{
var declarations = declsByShort.Values.SelectMany(values => values)
.GroupBy(d => ToRel(root, d.File), StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.Select(d => d.ShortName).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(), StringComparer.Ordinal);
var pairedTests = pairedReport.Values.SelectMany(tests => tests).ToHashSet(StringComparer.Ordinal);
var orphanTests = testFiles.Where(file => !AnalysisState.FailedFiles.ContainsKey(file) && !pairedTests.Contains(ToRel(root, file)))
.Order(StringComparer.Ordinal).Select(file => new { path = ToRel(root, file), language = "csharp" }).ToArray();
var unassessed = allCs.Where(AnalysisState.FailedFiles.ContainsKey).Order(StringComparer.Ordinal)
.Select(file => new { path = ToRel(root, file), language = "csharp" }).ToArray();
var data = new Dictionary<string, object?>
{
["repo_root"] = root,
["summary"] = new
{
files = allCs.Count, source_files = sourceFiles.Count, test_files = testFiles.Count,
tested_source_files = pairedReport.Count, untested_source_files = untested.Count,
orphan_test_files = orphanTests.Length, unassessed_files = unassessed.Length,
languages = allCs.Count > 0 ? new[] { "csharp" } : Array.Empty<string>(),
},
["untested_sources"] = untestedReport.Select(entry => new
{
path = entry.source, language = "csharp", declaration_count = entry.decl_count,
declarations = declarations.GetValueOrDefault(entry.source, Array.Empty<string>()),
suggested_test_path = entry.suggested_test_path,
}).ToArray(),
["orphan_tests"] = orphanTests,
["unassessed_files"] = unassessed,
["test_regions"] = Array.Empty<object>(),
};
if (includeTested)
{
data["tested_sources"] = pairedReport.Select(entry => new
{
path = entry.Key, language = "csharp",
declaration_count = declsByFile.GetValueOrDefault(Path.GetFullPath(Path.Combine(root, entry.Key))),
declarations = declarations.GetValueOrDefault(entry.Key, Array.Empty<string>()),
covering_tests = entry.Value,
}).ToArray();
}
var envelope = new
{
schema_version = "1", tool = "Find-UntestedSources", tool_version = "1.0",
status = diagnostics.Length > 0 ? "partial" : "complete",
scope = new
{
root, source_revision = (string?)null, evidence = "static-reference-pairing",
engine = "Roslyn", engine_version = typeof(CSharpSyntaxTree).Assembly.GetName().Version?.ToString(),
declarations = "C# type and delegate syntax declarations; not behavioral coverage",
languages = new[] { "csharp" }, exclude_symlinks = true,
untested_limit = topN == int.MaxValue ? 0 : topN, truncated = untestedReport.Count < untested.Count,
},
inputs = AnalysisState.Inputs.OrderBy(entry => entry.Key, StringComparer.Ordinal)
.Select(entry => new { path = ToRel(root, entry.Key), sha256 = entry.Value }).ToArray(),
diagnostics, data,
};
Console.WriteLine(JsonSerializer.Serialize(envelope, opts));
}
else if (diagnostics.Length == 0)
{
Console.WriteLine(JsonSerializer.Serialize(result, opts));
}
Log($"Total time: {swTotal.ElapsedMilliseconds} ms");
return diagnostics.Length > 0 ? 3 : 0;
// ============================================================================
// Helpers
// ============================================================================
static IEnumerable<string> EnumerateSourceFiles(string root, string pattern)
{
var stack = new Stack<string>();
stack.Push(root);
while (stack.Count > 0)
{
var dir = stack.Pop();
IEnumerable<string> subdirs;
try { subdirs = Directory.GetDirectories(dir); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Report("WALK_FAILED", dir, ex.Message);
continue;
}
foreach (var sub in subdirs)
{
if (IsLink(sub)) { continue; }
var name = Path.GetFileName(sub);
if (name.Length == 0)
{
continue;
}
if (string.Equals(name, "bin", StringComparison.OrdinalIgnoreCase)
|| string.Equals(name, "obj", StringComparison.OrdinalIgnoreCase)
|| string.Equals(name, "node_modules", StringComparison.OrdinalIgnoreCase)
|| string.Equals(name, ".git", StringComparison.OrdinalIgnoreCase)
|| string.Equals(name, ".vs", StringComparison.OrdinalIgnoreCase)
|| string.Equals(name, "packages", StringComparison.OrdinalIgnoreCase)
|| name.StartsWith(".", StringComparison.Ordinal))
{
continue;
}
stack.Push(sub);
}
IEnumerable<string> files;
try { files = Directory.GetFiles(dir, pattern); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Report("WALK_FAILED", dir, ex.Message);
continue;
}
foreach (var f in files)
{
if (IsSkippedFile(f) || IsLink(f))
{
continue;
}
yield return f;
}
}
}
static bool IsSkippedFile(string path)
{
string[] skippedSuffixes =
{
".g.cs",
".Designer.cs",
".AssemblyInfo.cs",
".AssemblyAttributes.cs",
".GlobalUsings.g.cs",
};
foreach (var suffix in skippedSuffixes)
{
if (path.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
static bool? ClassifyProjectAsTest(string csproj)
{
try
{
var content = ReadSnapshot(csproj);
var name = Path.GetFileNameWithoutExtension(csproj);
string[] testSuffixes = { ".Tests", ".Test", ".UnitTests", ".IntegrationTests", ".E2E", ".EndToEnd", ".Spec", ".Specs" };
if (testSuffixes.Any(suffix => name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))) { return true; }
if (content.Contains("Microsoft.NET.Test.Sdk", StringComparison.OrdinalIgnoreCase)) { return true; }
if (content.Contains("MSTest.Sdk", StringComparison.OrdinalIgnoreCase)) { return true; }
if (content.Contains("Microsoft.Testing.Platform", StringComparison.OrdinalIgnoreCase)) { return true; }
if (content.Contains("<IsTestProject>true</IsTestProject>", StringComparison.OrdinalIgnoreCase)) { return true; }
if (content.Contains("xunit", StringComparison.OrdinalIgnoreCase)) { return true; }
if (content.Contains("NUnit", StringComparison.OrdinalIgnoreCase)) { return true; }
if (content.Contains("TUnit", StringComparison.OrdinalIgnoreCase)) { return true; }
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DecoderFallbackException)
{
Report("PROJECT_READ_FAILED", csproj, ex.Message);
return null;
}
return false;
}
static string GetNamespaceFor(SyntaxNode node)
{
// Walk all enclosing namespace declarations and join from outermost to
// innermost so nested blocks (namespace A { namespace B { ... } }) yield
// "A.B" rather than just "B".
List<string>? parts = null;
foreach (var ns in node.Ancestors().OfType<BaseNamespaceDeclarationSyntax>())
{
(parts ??= new List<string>()).Add(ns.Name.ToString());
}
if (parts is null)
{
return "";
}
parts.Reverse();
return string.Join(".", parts);
}
static bool IsUsingPrefix(HashSet<string> usings, string ns)
{
if (ns.Length == 0)
{
return false;
}
foreach (var u in usings)
{
if (ns.StartsWith(u + ".", StringComparison.Ordinal))
{
return true;
}
}
return false;
}
static Dictionary<string, string> BuildProductionToTestProjectMap(string root)
{
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
List<string> allCsproj = EnumerateSourceFiles(root, "*.csproj").ToList();
// Sort so the deterministic "first write wins" rule below selects the
// same test project across runs/machines regardless of filesystem
// enumeration order.
allCsproj.Sort(StringComparer.Ordinal);
foreach (var testProj in allCsproj)
{
if (ClassifyProjectAsTest(testProj) != true)
{
continue;
}
string content;
try { content = ReadSnapshot(testProj); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DecoderFallbackException)
{
Report("PROJECT_READ_FAILED", testProj, ex.Message);
continue;
}
var testDir = Path.GetDirectoryName(testProj)!;
var matches = System.Text.RegularExpressions.Regex.Matches(content,
@"<ProjectReference\s+Include=""([^""]+)""");
foreach (System.Text.RegularExpressions.Match m in matches)
{
var rel = m.Groups[1].Value.Replace('\\', Path.DirectorySeparatorChar);
var abs = Path.GetFullPath(Path.Combine(testDir, rel));
if (File.Exists(abs) && !map.ContainsKey(abs))
{
map[abs] = testProj;
}
}
}
return map;
}
static string ToRel(string root, string path)
{
return Path.GetRelativePath(root, path).Replace('\\', '/');
}
static void Log(string msg) => Console.Error.WriteLine($"[find-untested-sources] {msg}");
static int InputError(string message, bool jsonV1)
{
Console.Error.WriteLine($"INVALID_INPUT: {message}");
if (jsonV1)
{
Console.WriteLine(JsonSerializer.Serialize(new
{
schema_version = "1", tool = "Find-UntestedSources", tool_version = "1.0", status = "error",
scope = new { }, inputs = Array.Empty<object>(), data = new { },
diagnostics = new[] { new { code = "INVALID_INPUT", severity = "error", message } },
}));
}
return jsonV1 ? 2 : 1;
}
static void Report(string code, string path, string message)
{
AnalysisState.Diagnostics.Enqueue(new DiagnosticRecord(code, "warning", path, message));
AnalysisState.FailedFiles[path] = 0;
}
static bool IsLink(string path)
{
try { return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0; }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Report("STAT_FAILED", path, ex.Message);
return true;
}
}
static string ReadSnapshot(string path)
{
byte[] bytes = File.ReadAllBytes(path);
string hash = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
if (AnalysisState.Inputs.TryGetValue(path, out string? previous) && previous != hash)
{
Report("INPUT_CHANGED", path, "Input changed during analysis.");
}
AnalysisState.Inputs[path] = hash;
using var stream = new MemoryStream(bytes, writable: false);
using var reader = new StreamReader(stream, new UTF8Encoding(false, true), detectEncodingFromByteOrderMarks: true);
return reader.ReadToEnd();
}
static SyntaxNode? ReadSyntax(string path)
{
try
{
var tree = CSharpSyntaxTree.ParseText(ReadSnapshot(path));
var errors = tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Take(3).ToArray();
if (errors.Length > 0)
{
Report("SYNTAX_ERROR", path, string.Join("; ", errors.Select(d => d.ToString())));
return null;
}
return tree.GetRoot();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DecoderFallbackException)
{
Report("READ_FAILED", path, ex.Message);
return null;
}
}
internal readonly record struct Decl(string ShortName, string Namespace, string File);
internal readonly record struct ProjectLookup(string? Path, bool IsResolved);
internal sealed record DiagnosticRecord(string code, string severity, string path, string message);
internal static class AnalysisState
{
internal static readonly ConcurrentQueue<DiagnosticRecord> Diagnostics = new();
internal static readonly ConcurrentDictionary<string, string> Inputs = new(StringComparer.Ordinal);
internal static readonly ConcurrentDictionary<string, byte> FailedFiles = new(StringComparer.Ordinal);
}
find_untested_sources.py 35.1 KB
"""Polyglot source-to-test pairing analyzer using tree-sitter.
Given a repo root, identifies which source files are NOT referenced by any test
file via two complementary heuristics:
1. Identifier overlap: a test file declares (or references) the same name
a source file declares as a top-level symbol.
2. Import resolution: a test file imports a module/path that resolves to a
source file.
Supports any language tree-sitter-language-pack can parse and classify (Python,
TypeScript, JavaScript, Go, Java, Rust, C#, Ruby, Kotlin, Swift, PowerShell,
C++, ...).
Output: legacy engine-specific JSON, or a shared envelope with --output-format
json-v1. Pairing is heuristic static evidence, not behavioral coverage.
Dependencies:
pip install tree-sitter-language-pack==1.8.1
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.metadata
import json
import posixpath
import re
import sys
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from typing import Iterable
try:
from tree_sitter_language_pack import (
ProcessConfig,
detect_language_from_path,
get_parser,
process,
)
except ImportError as e:
print(
"ERROR: tree-sitter-language-pack is not installed.\n"
"Run: pip install tree-sitter-language-pack",
file=sys.stderr,
)
if "json-v1" in sys.argv or "--output-format=json-v1" in sys.argv:
print(json.dumps({
"schema_version": "1", "tool": "find_untested_sources", "tool_version": "1.0",
"status": "error", "scope": {}, "inputs": [], "data": {},
"diagnostics": [{"code": "DEPENDENCY_MISSING", "severity": "error", "message": str(e)}],
}))
raise SystemExit(2) from e
# Languages we'll process. Anything not in this set is skipped even if the
# pack can parse it, because we have no test-detection heuristic for it.
SUPPORTED_LANGUAGES = {
"python",
"typescript",
"tsx",
"javascript",
"go",
"java",
"rust",
"csharp",
"ruby",
"kotlin",
"swift",
"powershell",
"cpp",
}
# Directories we never descend into. Lowercase match on segment name.
PRUNE_DIRS = {
".git",
".hg",
".svn",
".vs",
".vscode",
".idea",
"node_modules",
"bower_components",
"vendor",
"third_party",
"dist",
"build",
"out",
"target", # rust + java
"bin",
"obj",
"packages",
"__pycache__",
".pytest_cache",
".mypy_cache",
".tox",
".venv",
"venv",
"env",
".nuget",
"testresults",
"coverage",
".next",
".nuxt",
".cache",
".gradle",
".terraform",
"site-packages",
}
# Filename patterns to skip (generated, minified, declaration files).
SKIP_FILENAME_PATTERNS = (
re.compile(r"\.min\.(js|css)$", re.IGNORECASE),
re.compile(r"\.d\.ts$", re.IGNORECASE),
re.compile(r"\.designer\.cs$", re.IGNORECASE),
re.compile(r"\.g\.cs$", re.IGNORECASE),
re.compile(r"\.g\.i\.cs$", re.IGNORECASE),
re.compile(r"\.generated\.cs$", re.IGNORECASE),
re.compile(r"AssemblyInfo\.cs$"),
re.compile(r"AssemblyAttributes\.cs$"),
re.compile(r"GlobalUsings?\.cs$"),
re.compile(r"_pb2\.py$"),
re.compile(r"_pb\.go$"),
re.compile(r"\.pb\.go$"),
)
def is_test_path(rel: PurePosixPath, lang: str) -> bool:
"""Best-effort per-language test classification using path/filename."""
parts = [p.lower() for p in rel.parts]
name = rel.name.lower()
stem = rel.stem.lower()
if lang == "python":
if any(p in ("tests", "test") for p in parts):
return True
if name.startswith("test_") or stem.endswith("_test"):
return True
if "conftest.py" in name:
return True
return False
if lang in ("typescript", "tsx", "javascript"):
if any(p in ("__tests__", "tests", "test", "spec", "e2e") for p in parts):
return True
if any(s in stem for s in (".test", ".spec")):
return True
return False
if lang == "go":
return stem.endswith("_test")
if lang == "java":
if "test" in parts or "tests" in parts:
return True
return name.endswith("test.java") or name.endswith("tests.java")
if lang == "rust":
if any(p in ("tests", "benches") for p in parts):
return True
return False
if lang == "csharp":
if any(p in ("tests", "test") for p in parts):
return True
for p in parts:
if p.endswith(".tests") or p.endswith(".test") or p.endswith(".unittests") or p.endswith(".integrationtests"):
return True
# Tokenize the original (un-lowered) stem on PascalCase boundaries
# and treat it as a test file when the final word is "Test" / "Tests".
# This matches the .NET convention (`UserServiceTests`, `MyTest`)
# without misclassifying non-test files whose lower-cased stem
# coincidentally ends in "test"/"tests" (e.g. "Contest.cs",
# "Latest.cs", "Manifest.cs").
words = re.findall(r"[A-Z][a-z]*|[a-z]+|[0-9]+", rel.stem)
if words and words[-1] in ("Test", "Tests"):
return True
return False
if lang == "ruby":
if any(p in ("spec", "test", "tests") for p in parts):
return True
return stem.endswith("_spec") or stem.endswith("_test")
if lang == "kotlin":
if any(p in ("test", "tests", "spec", "specs") for p in parts):
return True
words = re.findall(r"[A-Z][a-z]*|[a-z]+|[0-9]+", rel.stem)
return bool(words and words[-1] in ("Test", "Tests", "Spec", "Specs"))
if lang == "swift":
if any(p in ("test", "tests", "uitests", "integrationtests") for p in parts):
return True
words = re.findall(r"[A-Z][a-z]*|[a-z]+|[0-9]+", rel.stem)
return bool(words and words[-1] in ("Test", "Tests"))
if lang == "powershell":
if any(p in ("test", "tests", "pester") for p in parts):
return True
return name.endswith(".tests.ps1") or name.endswith(".test.ps1")
if lang == "cpp":
if any(p in ("test", "tests", "testing") for p in parts):
return True
return (
stem.startswith("test_")
or stem.endswith("_test")
or stem.endswith("_tests")
)
return False
@dataclass
class FileInfo:
path: Path
rel: PurePosixPath
lang: str
is_test: bool
declarations: set[str] = field(default_factory=set)
referenced_identifiers: set[str] = field(default_factory=set)
imports: list[str] = field(default_factory=list)
is_source: bool = True
complete: bool = True
sha256: str | None = None
test_regions: list[dict] = field(default_factory=list)
def __hash__(self) -> int:
return id(self)
def __eq__(self, other: object) -> bool:
return self is other
def should_skip_filename(name: str) -> bool:
return any(p.search(name) for p in SKIP_FILENAME_PATTERNS)
def diagnostic(diagnostics: list[dict], code: str, path: str, error: object) -> None:
diagnostics.append({"code": code, "severity": "warning", "path": path, "message": str(error)})
def language_family(lang: str) -> str:
return "javascript" if lang in {"typescript", "tsx", "javascript"} else lang
def walk_files(
root: Path, lang_filter: set[str] | None = None, diagnostics: list[dict] | None = None
) -> Iterable[Path]:
"""Yield files under root, pruning common build/vendor directories."""
stack = [root]
if diagnostics is None:
diagnostics = []
while stack:
current = stack.pop()
try:
children = sorted(current.iterdir())
except OSError as exc:
diagnostic(diagnostics, "WALK_FAILED", str(current), exc)
continue
for child in children:
try:
if child.is_symlink():
continue
is_dir, is_file = child.is_dir(), child.is_file()
except OSError as exc:
diagnostic(diagnostics, "STAT_FAILED", str(child), exc)
continue
if is_dir:
if child.name.lower() in PRUNE_DIRS:
continue
stack.append(child)
continue
if not is_file:
continue
if should_skip_filename(child.name):
continue
lang = detect_language_from_path(str(child))
if lang is None:
continue
if lang not in SUPPORTED_LANGUAGES:
continue
if lang_filter is not None and lang not in lang_filter:
continue
yield child
def syntax_nodes(root):
stack = [root]
while stack:
node = stack.pop()
if "comment" in node.kind():
continue
yield node
stack.extend(node.named_child(i) for i in reversed(range(node.named_child_count())))
def node_text(node, source: bytes) -> str:
return source[node.start_byte():node.end_byte()].decode("utf-8")
def harvest_identifiers(text: str, lang: str, root=None, regions=None) -> set[str]:
root = root if root is not None else get_parser(lang).parse(text).root_node()
source = text.encode("utf-8")
kinds = {
"identifier", "type_identifier", "field_identifier", "property_identifier",
"constant", "simple_name", "simple_identifier", "command_name",
}
result = set()
for node in syntax_nodes(root):
if node.kind() not in kinds:
continue
if regions is not None and not any(start <= node.start_byte() < end for start, end in regions):
continue
value = node_text(node, source)
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]*", value):
result.add(value)
return result
def harvest_declarations(text: str, lang: str, root=None) -> set[str]:
"""Recover common declarations when the language-pack symbol view is sparse."""
if lang not in {"powershell", "cpp"}:
return set()
root = root if root is not None else get_parser(lang).parse(text).root_node()
source = bytearray(text.encode("utf-8"))
stack = [root]
while stack:
node = stack.pop()
if "comment" in node.kind() or "string" in node.kind():
source[node.start_byte():node.end_byte()] = b" " * (node.end_byte() - node.start_byte())
continue
stack.extend(node.named_child(i) for i in range(node.named_child_count()))
code = source.decode("utf-8")
if lang == "powershell":
return set(re.findall(r"(?im)^\s*function\s+([A-Za-z_][A-Za-z0-9-]*)", code))
if lang == "cpp":
return set(
re.findall(
r"\b(?:class|struct|enum(?:\s+class)?)\s+([A-Za-z_][A-Za-z0-9_]*)",
code,
)
)
return set()
def rust_regions(root, source: bytes) -> tuple[list[tuple[int, int]], list[dict]]:
excluded = []
tests = []
for parent in syntax_nodes(root):
attributes = []
for i in range(parent.named_child_count()):
node = parent.named_child(i)
kind = node.kind()
if kind == "attribute_item":
attributes.append(node_text(node, source))
continue
if kind in {"mod_item", "function_item"}:
if any(re.search(r"#\[\s*cfg\s*\(\s*test\s*\)\s*\]", attr) for attr in attributes):
excluded.append((node.start_byte(), node.end_byte()))
if kind == "function_item" and any(
re.fullmatch(r"#\[\s*(?:\w+::)*test(?:\s*\([^]]*\))?\s*\]", attr)
for attr in attributes
):
excluded.append((node.start_byte(), node.end_byte()))
name = node.child_by_field_name("name")
tests.append({
"name": node_text(name, source),
"start_line": source[:node.start_byte()].count(b"\n") + 1,
"end_line": source[:node.end_byte()].count(b"\n") + 1,
"start_byte": node.start_byte(), "end_byte": node.end_byte(),
"kind": "inline-test",
})
attributes = []
return excluded, tests
def parse_file(path: Path, root: Path, diagnostics: list[dict] | None = None) -> FileInfo | None:
rel_str = path.relative_to(root).as_posix()
rel = PurePosixPath(rel_str)
lang = detect_language_from_path(str(path))
if lang is None or lang not in SUPPORTED_LANGUAGES:
return None
if diagnostics is None:
diagnostics = []
is_test = is_test_path(rel, lang)
info = FileInfo(path=path, rel=rel, lang=lang, is_test=is_test, is_source=not is_test)
try:
raw = path.read_bytes()
info.sha256 = hashlib.sha256(raw).hexdigest()
text = raw.decode("utf-8-sig")
except (OSError, UnicodeError) as exc:
info.complete = False
diagnostic(diagnostics, "READ_FAILED", rel_str, exc)
return info
try:
syntax = get_parser(lang).parse(text).root_node()
if syntax.has_error():
info.complete = False
diagnostic(diagnostics, "SYNTAX_ERROR", rel_str, "Parser reported missing or erroneous syntax.")
cfg = ProcessConfig(language=lang, structure=True, imports=True, symbols=True)
result = process(text, cfg)
except Exception as exc:
info.complete = False
diagnostic(diagnostics, "PARSE_FAILED", rel_str, exc)
return info
# Top-level declarations: union of structure + symbols. The two views are
# complementary depending on the language — e.g. for Go, `structure` lists
# functions/methods but not `type` declarations, while `symbols` lists the
# types. We filter `module`/`namespace` kinds (they're packaging, not
# declarations) to avoid false-positive pairings on package names.
excluded_kinds = {"module", "namespace"}
def _kind_str(item: object) -> str:
k = getattr(item, "kind", None)
return str(k).lower() if k is not None else ""
for item in getattr(result, "structure", None) or []:
if _kind_str(item) in excluded_kinds:
continue
name = getattr(item, "name", None)
if name:
info.declarations.add(name)
for sym in getattr(result, "symbols", None) or []:
if _kind_str(sym) in excluded_kinds:
continue
name = getattr(sym, "name", None)
if name:
info.declarations.add(name)
info.declarations.update(harvest_declarations(text, lang, syntax))
reference_regions = None
if lang == "rust":
source = text.encode("utf-8")
excluded, info.test_regions = rust_regions(syntax, source)
if raw.startswith(b"\xef\xbb\xbf"):
for region in info.test_regions:
region["start_byte"] += 3
region["end_byte"] += 3
info.declarations = set()
for node in syntax_nodes(syntax):
if node.kind() not in {"function_item", "struct_item", "enum_item", "trait_item", "type_item", "const_item", "static_item"}:
continue
if any(start <= node.start_byte() < end for start, end in excluded):
continue
name = node.child_by_field_name("name")
if name is not None:
info.declarations.add(node_text(name, source))
if info.test_regions:
info.is_test = True
info.is_source = not is_test and bool(info.declarations)
if not is_test:
reference_regions = excluded
# Imports: keep the raw `source` field; we'll normalize per language.
if getattr(result, "imports", None):
for imp in result.imports:
src = getattr(imp, "source", None)
if src:
info.imports.append(src)
if lang == "rust" and info.is_source and info.is_test:
info.imports.clear()
if info.is_test:
info.referenced_identifiers = harvest_identifiers(text, lang, syntax, reference_regions)
return info
# --- Per-language import-to-path resolution --------------------------------
def _strip_quoted(value: str) -> str:
"""Return the first quoted substring or the original string trimmed."""
m = re.search(r"""['"`]([^'"`]+)['"`]""", value)
if m:
return m.group(1)
return value.strip()
def _resolve_relative_js(test_rel: PurePosixPath, target: str) -> set[PurePosixPath]:
"""Resolve ./ or ../ relative import paths to candidate source paths."""
if not (target.startswith("./") or target.startswith("../") or target.startswith("/")):
return set()
base = PurePosixPath(target)
if target.startswith("/"):
joined = PurePosixPath(target.lstrip("/"))
else:
joined = PurePosixPath(posixpath.normpath((test_rel.parent / base).as_posix()))
if ".." in joined.parts:
return set()
# Try various extensions and /index suffix.
extensions = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs")
if joined.suffix in extensions:
return {joined}
candidates = set()
stems = [str(joined)]
if str(joined).endswith("/index"):
stems.append(str(joined)[: -len("/index")])
for stem in stems:
for ext in extensions:
candidates.add(PurePosixPath(stem + ext))
candidates.add(PurePosixPath(stem + "/index.ts"))
candidates.add(PurePosixPath(stem + "/index.tsx"))
candidates.add(PurePosixPath(stem + "/index.js"))
return candidates
def _extract_python_module(import_text: str) -> str | None:
"""Extract `pkg.mod` from `from pkg.mod import x` or `import pkg.mod`."""
s = import_text.strip()
m = re.match(r"from\s+([\.\w]+)\s+import", s)
if m:
return m.group(1)
m = re.match(r"import\s+([\.\w]+)", s)
if m:
return m.group(1)
return None
def _python_module_to_path(
module: str, test_rel: PurePosixPath | None = None
) -> set[PurePosixPath]:
"""Resolve a Python import target to candidate source paths.
Leading dots (PEP 328 relative imports) are resolved against `test_rel`'s
directory: one dot = same package as the test file, each extra dot walks
one directory up. Without a `test_rel` context we cannot resolve them
safely, so we return an empty set rather than risk pairing the test with
an unrelated `utils.py` at the repo root.
"""
leading_dots = len(module) - len(module.lstrip("."))
rest = module[leading_dots:]
if leading_dots > 0:
if test_rel is None or not rest:
# Either we have no context to resolve against, or this is a
# `from . import x` form where the regex captured only the dots
# and we don't know the imported name. Skip rather than guess.
return set()
base_dir = test_rel.parent
for _ in range(leading_dots - 1):
base_dir = base_dir.parent
parts = rest.split(".")
base_path = base_dir.joinpath(*parts) if base_dir.parts else PurePosixPath(*parts)
return {
PurePosixPath(str(base_path) + ".py"),
PurePosixPath(str(base_path) + "/__init__.py"),
}
parts = rest.split(".")
candidates: set[PurePosixPath] = set()
base = "/".join(parts)
candidates.add(PurePosixPath(base + ".py"))
candidates.add(PurePosixPath(base + "/__init__.py"))
return candidates
def _extract_java_fqcn(import_text: str) -> str | None:
m = re.match(r"import\s+(?:static\s+)?([\w\.]+)", import_text.strip())
if not m:
return None
fqcn = m.group(1).rstrip(";").rstrip(".*")
return fqcn
def _java_fqcn_to_path(fqcn: str) -> PurePosixPath:
return PurePosixPath(fqcn.replace(".", "/") + ".java")
def _extract_csharp_using(import_text: str) -> str | None:
m = re.match(r"using\s+(?:static\s+)?([\w\.]+)", import_text.strip())
if not m:
return None
return m.group(1).rstrip(";")
def _extract_rust_use(import_text: str) -> set[str]:
"""Extract crate-relative paths from `use foo::bar::Baz;`."""
s = import_text.strip().rstrip(";")
m = re.match(r"use\s+(.+)", s)
if not m:
return set()
body = m.group(1).strip()
# Strip `as` aliases; ignore grouped imports for simplicity.
body = body.split(" as ")[0].strip()
return {body}
def _extract_go_import_targets(import_text: str) -> set[str]:
s = import_text.strip()
targets: set[str] = set()
for m in re.finditer(r'"([^"]+)"', s):
targets.add(m.group(1))
return targets
# --- Pairing engine --------------------------------------------------------
def _build_indexes(sources: list[FileInfo]) -> dict:
"""Build lookup indexes used to resolve test imports to source files."""
by_rel: dict[str, FileInfo] = {s.rel.as_posix(): s for s in sources}
by_decl: dict[str, list[FileInfo]] = {}
for s in sources:
for d in s.declarations:
by_decl.setdefault(d, []).append(s)
# For Java/C#: index by FQCN-like trailing path.
by_path_suffix: dict[str, list[FileInfo]] = {}
# For Go: index by basename so import resolution is O(1) per target
# instead of O(#sources) per import target.
by_filename: dict[str, list[FileInfo]] = {}
for s in sources:
p = s.rel.as_posix()
parts = p.split("/")
for i in range(len(parts)):
suffix = "/".join(parts[i:])
by_path_suffix.setdefault(suffix, []).append(s)
by_filename.setdefault(s.rel.name, []).append(s)
return {
"by_rel": by_rel,
"by_decl": by_decl,
"by_path_suffix": by_path_suffix,
"by_filename": by_filename,
}
def _resolve_test_imports(test: FileInfo, indexes: dict, lang: str) -> set[FileInfo]:
"""Given a test file's imports, return source files those imports resolve to."""
found: set[FileInfo] = set()
by_rel = indexes["by_rel"]
by_path_suffix = indexes["by_path_suffix"]
def add_candidate(path: PurePosixPath) -> None:
key = path.as_posix()
if key in by_rel:
found.add(by_rel[key])
return
# Try matching by suffix (covers monorepo / aliased layouts).
matches = by_path_suffix.get(key, [])
if len(matches) == 1:
found.add(matches[0])
for raw in test.imports:
if lang in ("typescript", "tsx", "javascript"):
target = _strip_quoted(raw)
for c in _resolve_relative_js(test.rel, target):
add_candidate(c)
elif lang == "python":
module = _extract_python_module(raw)
if module is None:
continue
for c in _python_module_to_path(module, test.rel):
add_candidate(c)
elif lang == "go":
by_filename = indexes["by_filename"]
for tgt in _extract_go_import_targets(raw):
segs = tgt.split("/")
if not segs:
continue
last = segs[-1]
key = last + ".go"
for info in by_filename.get(key, ()):
if not info.is_test:
found.add(info)
elif lang == "java":
fqcn = _extract_java_fqcn(raw)
if fqcn:
add_candidate(_java_fqcn_to_path(fqcn))
elif lang == "rust":
for use_path in _extract_rust_use(raw):
segs = use_path.split("::")
if not segs:
continue
last = segs[-1]
add_candidate(PurePosixPath(last + ".rs"))
if len(segs) >= 2:
add_candidate(PurePosixPath(segs[-2] + ".rs"))
elif lang == "csharp":
ns = _extract_csharp_using(raw)
if ns:
# using maps to namespace, not file; we fall back to identifier overlap.
pass
elif lang == "ruby":
target = _strip_quoted(raw)
if target:
add_candidate(PurePosixPath(target + ".rb"))
elif lang == "kotlin":
target = _strip_quoted(raw)
if target:
add_candidate(PurePosixPath(target.replace(".", "/") + ".kt"))
elif lang in ("swift", "powershell", "cpp"):
# These ecosystems commonly import modules, dot-source scripts, or
# include headers rather than source files. Identifier overlap is
# the reliable cross-project fallback for this analyzer.
pass
return found
def _resolve_test_by_identifiers(
test: FileInfo,
indexes: dict,
) -> set[FileInfo]:
"""Pair test with sources whose declarations appear in the test's token set."""
found: set[FileInfo] = set()
by_decl = indexes["by_decl"]
# Iterate the test's referenced identifiers (typically O(hundreds))
# rather than scanning every declaration in the index (O(#decls × #tests)
# across all tests), so pairing stays linear in repo size on large
# codebases.
for ident in test.referenced_identifiers:
if len(ident) < 4:
continue
sources = by_decl.get(ident)
if not sources or len(sources) != 1:
continue
for s in sources:
if language_family(s.lang) == language_family(test.lang):
found.add(s)
return found
def build_pairings(
sources: list[FileInfo],
tests: list[FileInfo],
) -> tuple[dict[FileInfo, set[FileInfo]], list[FileInfo]]:
"""Return (source -> covering tests) and the list of orphan test files."""
by_lang_indexes: dict[str, dict] = {}
for lang in {language_family(lang) for lang in SUPPORTED_LANGUAGES}:
lang_sources = [s for s in sources if language_family(s.lang) == lang and s.complete]
if lang_sources:
by_lang_indexes[lang] = _build_indexes(lang_sources)
source_to_tests: dict[FileInfo, set[FileInfo]] = {s: set() for s in sources}
orphans: list[FileInfo] = []
for t in tests:
if not t.complete:
continue
idx = by_lang_indexes.get(language_family(t.lang))
if idx is None:
orphans.append(t)
continue
matched = _resolve_test_imports(t, idx, t.lang) | _resolve_test_by_identifiers(t, idx)
if not matched:
orphans.append(t)
continue
for s in matched:
source_to_tests[s].add(t)
return source_to_tests, orphans
# --- Output ----------------------------------------------------------------
def _test_filename(source: FileInfo) -> str:
rel = source.rel
lang = source.lang
stem = rel.stem
if lang == "python":
return f"test_{stem}.py"
if lang == "go":
return f"{stem}_test.go"
if lang in ("typescript", "tsx"):
return f"{stem}.test.{rel.suffix.lstrip('.')}"
if lang == "javascript":
return f"{stem}.test.js"
if lang == "java":
return f"{stem}Test.java"
if lang == "rust":
return ""
if lang == "csharp":
return f"{stem}Tests.cs"
if lang == "ruby":
return f"{stem}_spec.rb"
if lang == "kotlin":
return f"{stem}Test.kt"
if lang == "swift":
return f"{stem}Tests.swift"
if lang == "powershell":
return f"{stem}.Tests.ps1"
if lang == "cpp":
return f"{stem}_test.cpp"
return ""
def _suggest_test_path(
source: FileInfo,
sibling_test_dirs: dict[tuple[str, PurePosixPath], PurePosixPath],
) -> str:
filename = _test_filename(source)
if source.lang == "rust":
# A sibling *_test.rs is not a Cargo target. Suggest the source file
# for an inline #[cfg(test)] module without creating or editing it.
return source.rel.as_posix()
if not filename:
return ""
family = language_family(source.lang)
parent = sibling_test_dirs.get((family, source.rel.parent), source.rel.parent)
return (parent / filename).as_posix()
def build_output(
sources: list[FileInfo],
tests: list[FileInfo],
source_to_tests: dict[FileInfo, set[FileInfo]],
orphans: list[FileInfo],
repo_root: Path,
) -> dict:
untested: list[dict] = []
tested: list[dict] = []
sibling_test_dirs: dict[tuple[str, PurePosixPath], PurePosixPath] = {}
for paired_source, covering_tests in source_to_tests.items():
family = language_family(paired_source.lang)
key = (family, paired_source.rel.parent)
for test in covering_tests:
candidate = test.rel.parent
current = sibling_test_dirs.get(key)
if current is None or candidate.as_posix() < current.as_posix():
sibling_test_dirs[key] = candidate
for s in sources:
if not s.complete:
continue
covering = sorted(source_to_tests.get(s, set()), key=lambda t: t.rel.as_posix())
entry = {
"path": s.rel.as_posix(),
"language": s.lang,
"declaration_count": len(s.declarations),
"declarations": sorted(s.declarations),
}
if covering:
entry["covering_tests"] = [c.rel.as_posix() for c in covering]
tested.append(entry)
else:
entry["suggested_test_path"] = _suggest_test_path(s, sibling_test_dirs)
if s.lang == "rust":
entry["suggestion_kind"] = "inline-test-module"
untested.append(entry)
return {
"repo_root": str(repo_root),
"summary": {
"files": len({s.rel for s in sources + tests}),
"source_files": len(sources),
"test_files": len(tests),
"tested_source_files": len(tested),
"untested_source_files": len(untested),
"orphan_test_files": len(orphans),
"languages": sorted({s.lang for s in sources} | {t.lang for t in tests}),
"unassessed_files": len({s.rel for s in sources + tests if not s.complete}),
},
"untested_sources": sorted(untested, key=lambda e: (-e["declaration_count"], e["path"])),
"tested_sources": sorted(tested, key=lambda e: e["path"]),
"orphan_tests": [
{"path": t.rel.as_posix(), "language": t.lang} for t in sorted(orphans, key=lambda t: t.rel.as_posix())
],
"test_regions": [
{"path": t.rel.as_posix(), **region}
for t in sorted(tests, key=lambda t: t.rel.as_posix())
for region in t.test_regions
],
"unassessed_files": [
{"path": info.rel.as_posix(), "language": info.lang}
for info in sorted(set(sources + tests), key=lambda info: info.rel.as_posix())
if not info.complete
],
}
def main() -> int:
parser = argparse.ArgumentParser(
description="Find untested source files in a polyglot repository using tree-sitter."
)
parser.add_argument("root", type=Path, help="Path to repository root.")
parser.add_argument(
"--lang",
action="append",
choices=sorted(SUPPORTED_LANGUAGES),
help="Restrict analysis to specified language(s). Repeatable.",
)
parser.add_argument(
"--limit-untested",
type=int,
default=0,
help="If > 0, truncate the untested_sources list to N entries.",
)
parser.add_argument(
"--output-format", choices=("legacy", "json-v1"), default="legacy",
help="Use json-v1 for versioned provenance and explicit partial results.",
)
parser.add_argument(
"--include-tested",
action="store_true",
help="Include tested_sources in the output (omitted by default to keep payload small).",
)
args = parser.parse_args()
root = args.root.resolve()
if not root.is_dir():
print(f"ERROR: not a directory: {root}", file=sys.stderr)
if args.output_format == "json-v1":
print(json.dumps(error_report("INVALID_INPUT", f"Not a directory: {root}")))
return 2
return 1
if args.limit_untested < 0:
if args.output_format == "json-v1":
message = "--limit-untested must be nonnegative"
print(f"INVALID_INPUT: {message}", file=sys.stderr)
print(json.dumps(error_report("INVALID_INPUT", message)))
return 2
parser.error("--limit-untested must be nonnegative")
lang_filter = set(args.lang) if args.lang else None
print(f"Scanning {root}...", file=sys.stderr)
sources: list[FileInfo] = []
tests: list[FileInfo] = []
diagnostics: list[dict] = []
parsed_count = 0
for path in walk_files(root, lang_filter=lang_filter, diagnostics=diagnostics):
info = parse_file(path, root, diagnostics)
if info is None:
continue
parsed_count += 1
if info.is_test:
tests.append(info)
if info.is_source:
sources.append(info)
print(f"Parsed {parsed_count} files: {len(sources)} source, {len(tests)} test.", file=sys.stderr)
source_to_tests, orphans = build_pairings(sources, tests)
output = build_output(sources, tests, source_to_tests, orphans, root)
if args.limit_untested and args.limit_untested > 0:
output["untested_sources"] = output["untested_sources"][: args.limit_untested]
if not args.include_tested:
output.pop("tested_sources", None)
for item in diagnostics:
print(f"{item['code']}: {item['path']}: {item['message']}", file=sys.stderr)
if args.output_format == "json-v1":
files = sorted(set(sources + tests), key=lambda item: item.rel.as_posix())
output = {
"schema_version": "1", "tool": "find_untested_sources", "tool_version": "1.0",
"status": "partial" if diagnostics else "complete",
"scope": {
"root": str(root), "source_revision": None, "evidence": "static-reference-pairing",
"engine": "tree-sitter-language-pack",
"engine_version": importlib.metadata.version("tree-sitter-language-pack"),
"declarations": "syntax declarations; language-dependent, not a behavioral metric",
"languages": sorted(lang_filter or SUPPORTED_LANGUAGES),
"excluded_directories": sorted(PRUNE_DIRS), "exclude_symlinks": True,
"untested_limit": args.limit_untested,
"truncated": len(output["untested_sources"]) < output["summary"]["untested_source_files"],
},
"inputs": [{"path": item.rel.as_posix(), "sha256": item.sha256} for item in files],
"diagnostics": diagnostics, "data": output,
}
elif diagnostics:
return 3
json.dump(output, sys.stdout, indent=2)
sys.stdout.write("\n")
return 3 if diagnostics else 0
def error_report(code: str, message: str) -> dict:
return {
"schema_version": "1", "tool": "find_untested_sources", "tool_version": "1.0",
"status": "error", "scope": {}, "inputs": [], "data": {},
"diagnostics": [{"code": code, "severity": "error", "message": message}],
}
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("CANCELLED: analysis interrupted", file=sys.stderr)
sys.exit(130)
except Exception as exc:
print(f"TOOL_ERROR: {exc}", file=sys.stderr)
if "json-v1" in sys.argv or "--output-format=json-v1" in sys.argv:
print(json.dumps(error_report("TOOL_ERROR", str(exc))))
sys.exit(2)
License (MIT)
View full license text
The MIT License (MIT) Copyright (c) .NET Foundation and Contributors All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.