Skip to content

refactor: complexity, duplication and coverage clean-up (stacked on #33) - #34

Merged
davidnmbond merged 12 commits into
mainfrom
refactor/template-js
Nov 17, 2026
Merged

davidnmbond merged 12 commits into
mainfrom
refactor/template-js

Conversation

@davidnmbond

Copy link
Copy Markdown
Contributor

Stacked on #33 (merge that first; this branch contains its commits).

  • Template JavaScript: every function now small; duplicate helpers and dead copies removed (several functions were defined twice in the concatenated script and only the last definition ran, so the unreachable copies are deleted). Layout measuring moved into the new layout-metrics.js (embedded and added to the generation list). Rendered SVG for the sample DbContext is structurally identical before and after, and the UI actions (grouping dialog, selection, zoom, move, auto layout, toggles) were exercised in headless Chrome without errors. One real bug fixed on the way: clicking a foreign key icon called entities.find on an object and threw.
  • CoreSchemaAnalysisService split into partial files; entity JSON for all four sample DbContexts is byte-identical before and after.
  • ModularHtmlTemplate: the document GUID is now emitted as an escaped JSON string literal, so a hostile --guid can no longer inject script. Public API is source and binary compatible: the optional parameters on Generate and AnalyzeDbContextWithEntityFiles became overloads (S2360); nothing was removed from SchemaMagic.Core.
  • New internal GitHubSourceHelpers in Core (InternalsVisibleTo the CLI, web app and tests) replaces three copies of repository URL parsing, DbContext detection and entity discovery.
  • CLI GitHubService and web GitHubService/SchemaAnalysisService restructured; GitHubService constructor and FindDbContextFilesAsync optional parameters replaced by overloads (CLI and web app are not libraries). One behaviour change: in the CLI a rate limit while reading DbContext or entity-by-name files now stops with the rate-limit message instead of logging and continuing.
  • Stylelint and ESLint findings fixed; PropertyExtractionTests now exercise the real service instead of a copy of its logic.
  • New offline tests (46 to 75): snapshot foreign keys, model and solution directory discovery, inheritance, comments, failure paths, HTML template generation and GUID escaping, GitHub source helpers. Local line coverage of SchemaMagic.Core 86.7 percent.

@codacy-production

codacy-production Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics -39 complexity · -67 duplication

Metric Results
Complexity -39
Duplication -67

View in Codacy

🟢 Coverage 92.47% diff coverage · +45.88% coverage variation

Metric Results
Coverage variation ✅ +45.88% coverage variation (-1.00%)
Diff coverage ✅ 92.47% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (a8aae7b) 791 363 45.89%
Head commit (35f56f3) 547 (-244) 502 (+139) 91.77% (+45.88%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#34) 478 442 92.47%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes.

@codacy-production codacy-production Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

⚠️ Resolve issues before merging

Two high-risk issues should be addressed before merging: the browser launcher may permit command injection through a caller-controlled path, and user-editable grouping patterns can trigger catastrophic regular-expression backtracking on the UI thread.

Additional logic regressions were identified in per-file discovery error handling and saved grouping-rule preservation. Several acceptance areas remain only partially covered, particularly CLI/web behavior, fallback paths, and template interaction behavior.

About this PR

  • Automated coverage does not yet exercise several newly refactored CLI, web-service, fallback, and template-interaction paths. Add focused tests for these branches before relying on the cleanup as a coverage improvement.

Test suggestions

  • Core discovery, inheritance, comments, snapshots, fallback entities, and failure paths
  • GUID escaping, CSS merging, default CSS, and HTML placeholder replacement
  • GitHubSourceHelpers URL parsing, DbContext detection, entity extraction, and directory prioritization
  • Malformed source and exceptional filesystem/project-search paths produce warnings without crashing
  • Embedded-template fallback to filesystem resources
  • CLI GitHub analysis, entity-file discovery, rate-limit behavior, output creation, and browser launching
  • Web GitHub service and asynchronous schema analysis behavior
  • Template JavaScript UI actions: grouping, selection, zoom, dragging, auto-layout, toggles, and downloaded state
  • Large-schema layout and relationship rendering after JavaScript extraction
Prompt proposal for missing tests
Consider implementing these tests if applicable:
1. Malformed source and exceptional filesystem/project-search paths produce warnings without crashing
2. Embedded-template fallback to filesystem resources
3. CLI GitHub analysis, entity-file discovery, rate-limit behavior, output creation, and browser launching
4. Web GitHub service and asynchronous schema analysis behavior
5. Template JavaScript UI actions: grouping, selection, zoom, dragging, auto-layout, toggles, and downloaded state
6. Large-schema layout and relationship rendering after JavaScript extraction

TIP Add a Jira or Linear ticket key to the branch or title so the reviewer can check the PR against it. Using another tracker? Tell us.
TIP How was this review? Give us feedback

Comment thread Templates/variables.js Outdated
if (NESTED_QUANTIFIER.test(pattern)) {
throw new Error("Pattern contains nested quantifiers");
}
return new RegExp(pattern, "i");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 HIGH RISK

Make grouping-pattern matching resistant to ReDoS by using a linear-time approach or rejecting unsupported constructs with execution safeguards. Add tests for adversarial and normal patterns.

See Issue in Codacy
See Issue in Codacy

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Comment thread SchemaMagic/BrowserLauncher.cs Outdated
throw new FileNotFoundException("Only an existing .html file can be opened.", fullPath);
}

using var process = Process.Start(CreateStartInfo(fullPath));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 HIGH RISK

Avoid passing an uncontrolled path directly to a platform command. Constrain targets to an application-owned directory and use safe platform-specific APIs or validated filenames; add traversal and invalid-extension tests.

See Issue in Codacy

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Comment on lines +7 to +8
Array.from(document.querySelectorAll("[data-entity]")).find(
(element) => element.getAttribute("data-entity") === entityName,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Replace the repeated full-DOM scans with a safe direct lookup or entity-to-element map while retaining support for unusual entity names.

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Comment on lines +63 to +64
const matches = findRuleMatches(rule, entityNames);
return matches !== null && matches.length > 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Do not silently delete saved rules that fail the new pattern restrictions. Preserve them for editing and surface an appropriate validation message.

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Console.WriteLine($"📁 Looking for entity models in: {modelsDirectory}");
foreach (var modelFile in Directory.GetFiles(modelsDirectory, "*.cs"))
{
modelClasses.AddRange(TryParseClasses(File.ReadAllText(modelFile), Path.GetFileName(modelFile)));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Restore per-file error handling around model-file reads so unreadable files produce warnings and analysis continues for the remaining models.

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Comment thread TestDbContext.cs
@@ -1,3 +1,4 @@
using System.Linq.Expressions;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Suggestion: Split the fixture into focused context, relationship-configuration, and entity files without changing the example schema or discoverability.

See Issue in Codacy

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Comment thread Templates/settings.js
fullHeightMode = settings.fullHeightMode ?? false;
snapToGrid = settings.snapToGrid ?? true;
legendVisible = settings.legendVisible ?? true;
function applySavedViewSettings(settings) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Suggestion: Normalize settings against a defaults object, then update the DOM separately, preserving behavior for empty, partial, and complete settings.

See Issue in Codacy

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

return foreignKeys;
}

private static void CollectSnapshotForeignKeys(string snapshotContent, Dictionary<string, List<string>> foreignKeys)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Suggestion: Split snapshot parsing into focused helpers and add coverage for malformed lines, multiple foreign keys, multiline fluent chains, and provider-specific formatting.

See Issue in Codacy

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

}

public async Task<List<DbContextInfo>> FindDbContextFilesAsync(string repoUrl, string? accessToken = null)
public async Task<List<DbContextInfo>> FindDbContextFilesAsync(string repoUrl, string? accessToken)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Suggestion: Extract the repository validation and search strategies into focused helpers, preserving user-facing errors and adding tests for invalid URLs, access failures, rate limits, and fallback search failures.

See Issue in Codacy

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

@davidnmbond
davidnmbond merged commit 2455a7a into main Nov 17, 2026
8 checks passed
@davidnmbond
davidnmbond deleted the refactor/template-js branch November 17, 2026 12:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant