From cbebff78732b968189e33e821378d9d93407a3b0 Mon Sep 17 00:00:00 2001 From: Argo Zhang Date: Sun, 15 Nov 2026 10:26:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(LLMsDocsGenerator):=20=E6=A0=B8=E5=BF=83?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E6=8C=89=E7=BB=84=E4=BB=B6=E7=94=9F=E6=88=90?= =?UTF-8?q?=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ArgumentsHelper.cs | 7 +- .../BootstrapBlazor.LLMsDocsGenerator.csproj | 6 +- .../ComponentAnalyzer.cs | 179 ++++++++++++++++-- .../DocsGenerator.cs | 88 +++++++-- .../MarkdownBuilder.cs | 8 +- .../README.md | 17 +- .../README.zh-CN.md | 17 +- 7 files changed, 268 insertions(+), 54 deletions(-) diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs index 80272669..b7888df7 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/ArgumentsHelper.cs @@ -12,10 +12,9 @@ internal static class ArgumentsHelper public static ParseResult Parse(string[] args) { const string defaultFolder = "."; - var rootFolderOption = new Option("--root") + var rootFolderOption = new Option("--root") { - Description = "Set the root folder of project", - DefaultValueFactory = _ => defaultFolder + Description = "Set the Server project folder (core-only can instead run from the core project)" }; var outputFolderOption = new Option("--output") { @@ -37,7 +36,7 @@ public static ParseResult Parse(string[] args) rootCommand.SetAction(async result => { var rootFolder = result.GetValue(rootFolderOption); - if (string.IsNullOrEmpty(rootFolder)) + if (rootFolder != null && string.IsNullOrWhiteSpace(rootFolder)) { throw new ArgumentException("Project root folder must not be empty."); } diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/BootstrapBlazor.LLMsDocsGenerator.csproj b/tools/BootstrapBlazor.LLMsDocsGenerator/BootstrapBlazor.LLMsDocsGenerator.csproj index 74aebb73..fe2f6316 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/BootstrapBlazor.LLMsDocsGenerator.csproj +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/BootstrapBlazor.LLMsDocsGenerator.csproj @@ -1,7 +1,7 @@  - 11.0.1 + 11.0.2 Exe false @@ -23,4 +23,8 @@ + + + + diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs index 0b1fb7d3..fb99d395 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/ComponentAnalyzer.cs @@ -25,7 +25,7 @@ public partial class ComponentAnalyzer { private readonly string _sourcePath; private readonly string _componentsPath; - private readonly string _samplesPath; + private readonly string? _samplesPath; private readonly string? _extensionsSourcePath; private readonly IReadOnlyDictionary? _extensionProjects; @@ -47,10 +47,18 @@ public partial class ComponentAnalyzer public ComponentAnalyzer(string sourcePath, string? extensionsSourcePath = null, IReadOnlyDictionary? extensionProjects = null) + : this(sourcePath, extensionsSourcePath, extensionProjects, includeSamples: true) + { + } + + internal ComponentAnalyzer(string sourcePath, string? extensionsSourcePath, + IReadOnlyDictionary? extensionProjects, bool includeSamples) { _sourcePath = sourcePath; _componentsPath = Path.Combine(sourcePath, "Components"); - _samplesPath = Path.Combine(Path.GetDirectoryName(sourcePath)!, "BootstrapBlazor.Server", "Components", "Samples"); + _samplesPath = includeSamples + ? Path.Combine(Path.GetDirectoryName(sourcePath)!, "BootstrapBlazor.Server", "Components", "Samples") + : null; _extensionsSourcePath = extensionsSourcePath; _extensionProjects = extensionProjects; } @@ -91,9 +99,82 @@ public async Task> AnalyzeAllComponentsAsync() } } + var componentDirectory = Path.GetFullPath(_componentsPath) + Path.DirectorySeparatorChar; + var declarations = _compilation!.SyntaxTrees + .Where(tree => tree.FilePath.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) && + Path.GetFullPath(tree.FilePath).StartsWith(componentDirectory, StringComparison.OrdinalIgnoreCase)) + .SelectMany(tree => tree.GetRoot().DescendantNodes().OfType()) + .OrderBy(declaration => string.Equals(Path.GetFileNameWithoutExtension(declaration.SyntaxTree.FilePath), + declaration.Identifier.Text, StringComparison.Ordinal) ? 0 : 1) + .ThenBy(declaration => declaration.SyntaxTree.FilePath, StringComparer.Ordinal); + + foreach (var declaration in declarations) + { + var model = _compilation.GetSemanticModel(declaration.SyntaxTree); + if (model.GetDeclaredSymbol(declaration) is not INamedTypeSymbol symbol || + symbol.DeclaredAccessibility != Accessibility.Public || symbol.ContainingType != null || + seenTypes.Contains(symbol.ToDisplayString(FullNameFormat)) || !IsComponentType(symbol)) + { + continue; + } + + var component = BuildComponentInfo(symbol, declaration, declaration.SyntaxTree.FilePath); + if (component.Parameters.Count > 0 && seenTypes.Add(component.FullName)) + { + components.Add(component); + } + } + return components.OrderBy(c => c.Name).ToList(); } + private bool IsComponentType(INamedTypeSymbol symbol) + { + var pending = new Stack(); + var seen = new HashSet(SymbolEqualityComparer.Default); + pending.Push(symbol); + while (pending.TryPop(out var current)) + { + if (!seen.Add(current)) + { + continue; + } + + foreach (var declaration in current.DeclaringSyntaxReferences.Select(reference => reference.GetSyntax()) + .OfType()) + { + if (declaration.BaseList == null) + { + continue; + } + + var model = _compilation!.GetSemanticModel(declaration.SyntaxTree); + foreach (var baseType in declaration.BaseList.Types) + { + var type = model.GetTypeInfo(baseType.Type).Type; + if (type == null) + { + continue; + } + + if (type.Name is "ComponentBase" or "IComponent" && + (type.TypeKind == TypeKind.Error || + type.ToDisplayString() == $"Microsoft.AspNetCore.Components.{type.Name}")) + { + return true; + } + + if (type is INamedTypeSymbol { TypeKind: not TypeKind.Error } baseSymbol) + { + pending.Push(baseSymbol); + } + } + } + } + + return false; + } + /// /// Analyze a specific component by name /// @@ -134,25 +215,89 @@ public async Task> AnalyzeServicesAsync(IEnumerable var symbol = _compilation!.GetSymbolsWithName(name, SymbolFilter.Type) .OfType() .FirstOrDefault(); - var syntax = symbol?.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax(); - if (symbol == null || syntax == null) + if (symbol == null || symbol.DeclaringSyntaxReferences.Length == 0) { throw new InvalidDataException($"Service type not found in analyzed sources: {name}"); } - services.Add(new ComponentInfo - { - Name = symbol.Name, - FullName = symbol.ToDisplayString(FullNameFormat), - Summary = ExtractXmlSummary(syntax), - SourcePath = GetRelativePath(syntax.SyntaxTree.FilePath), - PublicMethods = CollectMethods(symbol) - }); + services.Add(BuildServiceInfo(symbol)); } return services; } + internal async Task> AnalyzeCoreServicesAsync(IEnumerable components) + { + await EnsureCompilationAsync(); + + var servicePath = Path.GetFullPath(Path.Combine(_sourcePath, "Services")) + Path.DirectorySeparatorChar; + var componentPath = Path.GetFullPath(_componentsPath) + Path.DirectorySeparatorChar; + var componentTypes = components.Select(component => component.FullName).ToHashSet(StringComparer.Ordinal); + var symbols = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var tree in _compilation!.SyntaxTrees) + { + var path = Path.GetFullPath(tree.FilePath); + var inServices = path.StartsWith(servicePath, StringComparison.OrdinalIgnoreCase); + var inComponents = path.StartsWith(componentPath, StringComparison.OrdinalIgnoreCase); + if (!inServices && !inComponents) + { + continue; + } + + var model = _compilation.GetSemanticModel(tree); + foreach (var declaration in tree.GetRoot().DescendantNodes().OfType()) + { + if (model.GetDeclaredSymbol(declaration) is not INamedTypeSymbol symbol || + symbol.DeclaredAccessibility != Accessibility.Public || symbol.ContainingType != null || symbol.IsStatic || + symbol.DeclaringSyntaxReferences.Select(reference => reference.GetSyntax()) + .OfType().SelectMany(type => type.AttributeLists) + .SelectMany(list => list.Attributes).Any(attribute => + attribute.Name.ToString().Split('.').Last() is "Obsolete" or "ObsoleteAttribute")) + { + continue; + } + + var isService = symbol.TypeKind == TypeKind.Interface && + (inServices || symbol.Name.EndsWith("Service", StringComparison.Ordinal) || symbol.Name.EndsWith("Provider", StringComparison.Ordinal)) + || symbol.TypeKind == TypeKind.Class && symbol.Name.EndsWith("Service", StringComparison.Ordinal); + if (!isService) + { + continue; + } + + if (componentTypes.Contains(symbol.ToDisplayString(FullNameFormat))) + { + continue; + } + + if (symbols.TryGetValue(symbol.Name, out var existing) && !SymbolEqualityComparer.Default.Equals(existing, symbol)) + { + throw new InvalidDataException($"Core service names collide: {existing.ToDisplayString()} and {symbol.ToDisplayString()}"); + } + + symbols[symbol.Name] = symbol; + } + } + + return symbols.Values.OrderBy(symbol => symbol.Name, StringComparer.Ordinal) + .Select(symbol => BuildServiceInfo(symbol, includeTypeParameters: true)).ToList(); + } + + private ComponentInfo BuildServiceInfo(INamedTypeSymbol symbol, bool includeTypeParameters = false) + { + var syntax = symbol.DeclaringSyntaxReferences.First().GetSyntax(); + return new ComponentInfo + { + Name = symbol.Name, + FullName = symbol.ToDisplayString(FullNameFormat), + Summary = ExtractXmlSummary(syntax), + TypeParameters = includeTypeParameters ? symbol.TypeParameters.Select(type => type.Name).ToList() : new(), + SourcePath = GetRelativePath(syntax.SyntaxTree.FilePath), + PublicMethods = CollectMethods(symbol) + }; + } + /// /// Analyze arbitrary types by name (extension components and services) into /// ComponentInfo records with parameters, methods and source path. The compilation @@ -910,17 +1055,19 @@ private string GetRelativePath(string fullPath) } } - // Normalize first: _sourcePath is "/../BootstrapBlazor", so without - // GetFullPath the ".." segment throws off GetDirectoryName and the result - // becomes "../BootstrapBlazor/..." instead of "src/BootstrapBlazor/...". var sourceRoot = Path.GetFullPath(_sourcePath); + if (full.StartsWith(sourceRoot + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + { + return Path.Combine("src", "BootstrapBlazor", Path.GetRelativePath(sourceRoot, full)).Replace('\\', '/'); + } + var basePath = Path.GetDirectoryName(Path.GetDirectoryName(sourceRoot))!; return Path.GetRelativePath(basePath, full).Replace('\\', '/'); } private string? FindSamplePath(string componentName) { - if (!Directory.Exists(_samplesPath)) + if (_samplesPath == null || !Directory.Exists(_samplesPath)) return null; // Try common sample file naming patterns diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs index f7c9d4bb..551941e0 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/DocsGenerator.cs @@ -12,9 +12,9 @@ internal static class DocsGenerator /// /// Generate all documentation files /// - public static async Task GenerateAllAsync(string rootFolder, string outputFolder, bool coreOnly = false) + public static async Task GenerateAllAsync(string? rootFolder, string outputFolder, bool coreOnly = false) { - var _sourcePath = Path.Combine(rootFolder, "..", "BootstrapBlazor"); + var _sourcePath = GetSourcePath(rootFolder, coreOnly); var _outputPath = coreOnly ? outputFolder : Path.Combine(outputFolder, "wwwroot", "llms"); Logger($"Source path: {_sourcePath}"); @@ -27,17 +27,19 @@ public static async Task GenerateAllAsync(string rootFolder, string outputFolder Logger("Analyzing components..."); - // The extensions repository sits next to the core repo: - // /.. / BootstrapBlazor.Extensions / src - var coreRepoRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(_sourcePath)))!; - var extensionsSrc = Path.Combine(Path.GetDirectoryName(coreRepoRoot)!, "BootstrapBlazor.Extensions", "src"); + var extensionsSrc = string.Empty; + if (!coreOnly) + { + var coreRepoRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(_sourcePath)))!; + extensionsSrc = Path.Combine(Path.GetDirectoryName(coreRepoRoot)!, "BootstrapBlazor.Extensions", "src"); + } var hasExtensions = !coreOnly && Directory.Exists(extensionsSrc); var extensionProjects = hasExtensions ? ReadExtensionProjects(Path.GetDirectoryName(extensionsSrc)!) : new Dictionary(StringComparer.OrdinalIgnoreCase); var _analyzer = new ComponentAnalyzer(_sourcePath, hasExtensions ? extensionsSrc : null, - extensionProjects); + extensionProjects, includeSamples: !coreOnly); var components = await _analyzer.AnalyzeAllComponentsAsync(); Logger($"Found {components.Count} components"); if (components.Count == 0) @@ -45,19 +47,42 @@ public static async Task GenerateAllAsync(string rootFolder, string outputFolder throw new InvalidDataException("No core components found."); } - // Derive index categories, injected services and extension packages from docs.json. - var serverPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(_sourcePath))!, "BootstrapBlazor.Server"); - var provider = new CategoryProvider(serverPath); - var categories = provider.Parse(); + CategoryProvider? provider = null; + if (!coreOnly) + { + var serverPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(_sourcePath))!, "BootstrapBlazor.Server"); + provider = new CategoryProvider(serverPath); + } + + var categories = coreOnly ? GetCoreCategories(components) : provider!.Parse(); Logger($"Found {categories.Count} categories"); - var services = await _analyzer.AnalyzeServicesAsync(provider.ParseServices()); + var services = coreOnly + ? await _analyzer.AnalyzeCoreServicesAsync(components) + : await _analyzer.AnalyzeServicesAsync(provider!.ParseServices()); Logger($"Found {services.Count} services"); if (services.Count == 0) { throw new InvalidDataException("No core services found."); } - var configuredPackages = coreOnly ? new List() : provider.ParseExtensions(); + if (coreOnly) + { + var duplicateComponent = components.GroupBy(component => component.Name, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(group => group.Skip(1).Any()); + if (duplicateComponent != null) + { + throw new InvalidDataException($"Core component names collide: {duplicateComponent.Key}"); + } + + var componentNames = components.Select(component => component.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); + var duplicate = services.FirstOrDefault(service => componentNames.Contains(service.Name)); + if (duplicate != null) + { + throw new InvalidDataException($"Core component and service names collide: {duplicate.Name}"); + } + } + + var configuredPackages = coreOnly ? new List() : provider!.ParseExtensions(); if (!hasExtensions && configuredPackages.Count > 0) { throw new DirectoryNotFoundException($"Extension sources required by docs.json were not found: {extensionsSrc}"); @@ -98,7 +123,7 @@ public static async Task GenerateAllAsync(string rootFolder, string outputFolder // the components/ directory. Directory.CreateDirectory(_outputPath); var indexPath = Path.Combine(_outputPath, "llms.txt"); - await File.WriteAllTextAsync(indexPath, MarkdownBuilder.BuildIndexDoc(components, categories, services, extComponents, extServices, extPackages, "zh")); + await File.WriteAllTextAsync(indexPath, MarkdownBuilder.BuildIndexDoc(components, categories, services, extComponents, extServices, extPackages, "zh", coreOnly)); Logger($"Generated: {indexPath}"); var componentsOutputPath = Path.Combine(_outputPath, "components"); @@ -137,6 +162,41 @@ public static async Task GenerateAllAsync(string rootFolder, string outputFolder Logger("Documentation generation complete!"); } + private static string GetSourcePath(string? rootFolder, bool coreOnly) + { + if (coreOnly && rootFolder == null) + { + var current = Directory.GetCurrentDirectory(); + if (File.Exists(Path.Combine(current, "BootstrapBlazor.csproj"))) + { + return current; + } + + var repositorySource = Path.Combine(current, "src", "BootstrapBlazor"); + if (File.Exists(Path.Combine(repositorySource, "BootstrapBlazor.csproj"))) + { + return repositorySource; + } + } + + return Path.Combine(rootFolder ?? ".", "..", "BootstrapBlazor"); + } + + private static List GetCoreCategories(IEnumerable components) + { + return components + .Select(component => (Component: component, Parts: component.SourcePath.Split('/'))) + .Where(item => Array.IndexOf(item.Parts, "Components") is var index && index >= 0 && index + 2 < item.Parts.Length) + .GroupBy(item => item.Parts[Array.IndexOf(item.Parts, "Components") + 1], StringComparer.Ordinal) + .OrderBy(group => group.Key, StringComparer.Ordinal) + .Select(group => new ComponentCategory + { + Title = group.Key, + ComponentNames = group.Select(item => item.Component.Name).OrderBy(name => name, StringComparer.Ordinal).ToList() + }) + .ToList(); + } + private static Dictionary ReadExtensionProjects(string repositoryRoot) { var solutionPath = Path.Combine(repositoryRoot, "BootstrapBlazor.Extensions.slnx"); diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs b/tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs index b065e347..8b835d8b 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/MarkdownBuilder.cs @@ -89,7 +89,7 @@ private static string CleanInlineMarkup(string text) [GeneratedRegex("\\s+")] private static partial Regex WhitespaceRegex(); - public static string BuildIndexDoc(List components, List categories, List services, List extensionComponents, List extensionServices, List extensionPackages, string lang) + public static string BuildIndexDoc(List components, List categories, List services, List extensionComponents, List extensionServices, List extensionPackages, string lang, bool coreOnly = false) { var _sb = new StringBuilder(); _sb.AppendLine("# BootstrapBlazor"); @@ -182,9 +182,11 @@ void AppendComponentLink(ComponentInfo component) // Injected services if (services.Count > 0) { - _sb.AppendLine("## 内置服务"); + _sb.AppendLine(coreOnly ? "## 核心服务及相关接口" : "## 内置服务"); _sb.AppendLine(); - _sb.AppendLine("通过依赖注入使用的服务,每个服务在 `components/` 目录下都有独立的文档文件。"); + _sb.AppendLine(coreOnly + ? "核心服务和相关公开接口,每个类型在 `components/` 目录下都有独立的文档文件;并非所有接口都由默认依赖注入注册。" + : "通过依赖注入使用的服务,每个服务在 `components/` 目录下都有独立的文档文件。"); _sb.AppendLine(); foreach (var service in services) { diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/README.md b/tools/BootstrapBlazor.LLMsDocsGenerator/README.md index 175f32ca..8e5f57b5 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/README.md +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/README.md @@ -56,7 +56,7 @@ This design optimizes for LLM and Code Agent consumption: ### 1. Source Code Analysis -The `ComponentAnalyzer` uses Roslyn to parse C# source files, scanning properties marked with the `[Parameter]` attribute and extracting their XML documentation comments. +The `ComponentAnalyzer` uses Roslyn to parse C# source files, scanning properties marked with the `[Parameter]` attribute and extracting their XML documentation comments. Public components defined in plain `.cs` files are discovered through their `ComponentBase` or `IComponent` inheritance chain. ### 2. Documentation Generation @@ -119,13 +119,13 @@ Once installed, the tool is invoked with the command name `llms-docs`. ## Usage -Both path options independently default to the current working directory (`.`). Run `llms-docs` without arguments from BB's `src/BootstrapBlazor.Server` directory to write documentation into that project. With `--core-only`, output is written directly to the `--output` directory without clearing existing contents. Overriding `--root` does not change the default `--output`; specify both when using another checkout or publish directory. +The output defaults to the current working directory (`.`). In default mode, the root also defaults to `.`; run `llms-docs` from BB's `src/BootstrapBlazor.Server` directory to write documentation into that project. With `--core-only`, run from the core project or repository root without specifying `--root`, and output is written directly to the `--output` directory without clearing existing contents. Overriding `--root` does not change the default `--output`. From the Server project directory, `dotnet llms-docs --output=bin\Release\publish\` also works: the omitted `--root` defaults to `.`, and relative output paths are resolved from that same directory. MSBuild can use `dotnet llms-docs --output=$(PublishDir)` when the path contains no spaces. | Option | Required | Description | |--------|----------|-------------| -| `--root` | No | Project root folder. Defaults to `.`. Component source is read from `/../BootstrapBlazor`. | +| `--root` | No | Server project folder. When specified, core source is read from `/../BootstrapBlazor`. Default mode uses `.`; core-only can discover the core project from the current core project, repository root, or Server directory. | | `--output` | No | Output folder. Defaults to `.`. Default mode writes to `/wwwroot/llms/`; `--core-only` writes directly to `/`. | | `--core-only` | No | Generate only core components and built-in services for BootstrapBlazor packaging. Defaults to `false`; extension configuration and sources are not analyzed. | @@ -135,7 +135,7 @@ Only source projects listed in `BootstrapBlazor.Extensions.slnx` are scanned. Pa If extension packages are configured but the sibling extension source checkout is missing, generation fails before changing existing documentation. Unresolved configured component or service types also fail generation before writing files or removing stale documents. Services shared by multiple packages retain one document listing the registration method for each configured package; choose the registration matching the package in use. -With `--core-only`, the `extensions` section is ignored without editing `docs.json`, and no extension checkout or solution is required or read, even when present. Core categories and services still come from `docs.json`, which remains required. No extension documents or extension index sections/links are generated; services also provided by extensions remain in the core service documentation. The output is `/llms.txt` and `/components/*.txt`, with relative index links suitable for a package. The output directory is created if needed; existing contents are not cleared. Stale files carrying the generator marker are removed while unmarked files and subdirectories are preserved. +With `--core-only`, no Server `docs.json`, sample files, extension checkout or solution is read. Component index groups are derived from the first directory under `Components`. Services are discovered from public, non-obsolete top-level types: interfaces under `Services`, and interfaces ending in `Service` or `Provider` under `Components`; public non-static classes ending in `Service` in either directory are also included unless already recognized as components. These are service-related APIs, not necessarily DI registrations. Duplicate names that would overwrite documentation cause generation to fail. No extension documents or extension index sections/links are generated. The output is `/llms.txt` and `/components/*.txt`, with relative index links suitable for a package. The output directory is created if needed; existing contents are not cleared. Stale files carrying the generator marker are removed while unmarked files and subdirectories are preserved. Explicit `` items in each source project's `.csproj` (including aliases and static imports) are applied to that project's C# files, without leaking these imports into other projects in the combined analysis. @@ -145,10 +145,11 @@ Declare extension services by the types actually registered for injection. For e Generation errors and explicitly empty paths return a nonzero process exit code so MSBuild and CI can stop. -Run the integration checks with PowerShell 7. They build the tool and invoke its actual CLI against isolated source fixtures for core-only packaging and full website generation: +Build the tool and run the core-only integration checks with PowerShell 7: ```powershell -.\tools\BootstrapBlazor.LLMsDocsGenerator\tests\Verify-Generation.ps1 +dotnet build .\tools\BootstrapBlazor.LLMsDocsGenerator -c Release +.\tools\BootstrapBlazor.LLMsDocsGenerator\tests\Verify-CoreOnly.ps1 ``` ### Example @@ -180,10 +181,10 @@ dotnet run --project "..\BootstrapBlazor.Extensions\tools\BootstrapBlazor.LLMsDo From the `BootstrapBlazor` repository root, generate core-only documentation directly into the skill references directory: ```powershell -dotnet llms-docs --core-only --root "src\BootstrapBlazor.Server" --output "src\BootstrapBlazor\skills\bootstrapblazor\references" +dotnet llms-docs --core-only --output "src\BootstrapBlazor\skills\bb-api\references" ``` -No staging copy of `docs.json` with extensions removed is needed. BootstrapBlazor.Server publishing must omit `--core-only` to keep the full website index, core documentation and extension documentation; its existing command and output paths are unchanged. +No `docs.json` is needed. BootstrapBlazor.Server publishing must omit `--core-only` to keep the full website index, core documentation and extension documentation; its existing command and output paths are unchanged. ## CI/CD Integration diff --git a/tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md b/tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md index e2c3b6d5..a3dc9bd0 100644 --- a/tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md +++ b/tools/BootstrapBlazor.LLMsDocsGenerator/README.zh-CN.md @@ -56,7 +56,7 @@ AI 编程助手(Claude Code、Cursor、GitHub Copilot)经常因为缺乏准 ### 1. 源码分析 -`ComponentAnalyzer` 使用 Roslyn 解析 C# 源文件,扫描标记了 `[Parameter]` 特性的属性,并提取其 XML 文档注释。 +`ComponentAnalyzer` 使用 Roslyn 解析 C# 源文件,扫描标记了 `[Parameter]` 特性的属性,并提取其 XML 文档注释。纯 `.cs` 文件中定义的公开组件通过 `ComponentBase` 或 `IComponent` 继承链发现。 ### 2. 文档生成 @@ -119,13 +119,13 @@ dotnet tool uninstall --global BootstrapBlazor.LLMsDocsGenerator ## 使用方法 -两个路径参数各自默认为当前工作目录(`.`)。在 BB 的 `src/BootstrapBlazor.Server` 目录直接执行 `llms-docs` 即可将文档生成到该工程。使用 `--core-only` 时,输出直接写入 `--output` 目录,不会清空已有内容。覆盖 `--root` 不会改变 `--output` 的默认值;使用其他仓库或发布目录时请分别指定。 +输出路径默认为当前工作目录(`.`)。默认模式下 `--root` 也默认为 `.`,在 BB 的 `src/BootstrapBlazor.Server` 目录直接执行 `llms-docs` 即可将文档生成到该工程。使用 `--core-only` 时,可在核心工程目录或仓库根目录运行,无需指定 `--root`;输出直接写入 `--output` 目录,不会清空已有内容。覆盖 `--root` 不会改变 `--output` 的默认值。 在 Server 工程目录运行时也支持 `dotnet llms-docs --output=bin\Release\publish\`,省略的 `--root` 使用 `.`,相对输出路径也基于当前 Server 目录解析。MSBuild 中可使用 `dotnet llms-docs --output=$(PublishDir)`(路径不含空格时)。 | 选项 | 必需 | 说明 | |------|------|------| -| `--root` | 否 | 项目根目录,默认为 `.`。组件源码从 `/../BootstrapBlazor` 读取。 | +| `--root` | 否 | Server 工程目录。指定时组件源码从 `/../BootstrapBlazor` 读取;默认模式使用 `.`,核心模式可从核心工程、仓库根目录或 Server 目录发现核心工程。 | | `--output` | 否 | 输出目录,默认为 `.`。默认模式生成到 `/wwwroot/llms/`;`--core-only` 直接生成到 `/`。 | | `--core-only` | 否 | 用于 BootstrapBlazor 打包,仅生成核心组件与内置服务文档。默认为 `false`,启用后不分析扩展配置与源码。 | @@ -135,7 +135,7 @@ dotnet tool uninstall --global BootstrapBlazor.LLMsDocsGenerator 配置了扩展包但缺少同级扩展源码仓库时,生成会失败且不改动已有文档。配置中的组件或服务类型无法解析时,也会在写入文件、清理过期文档之前报错。多个包共用的服务接口仍使用一份文档,按配置的包分别列出注册方法,使用时选择对应包的注册方式。 -使用 `--core-only` 时,无需修改 `docs.json`,生成器会忽略 `extensions` 节;无需扩展仓库或解决方案,即使存在也不会读取。核心分类与内置服务仍从 `docs.json` 获取,因此该文件仍为必需。不生成扩展文档、扩展索引章节或链接;扩展也提供的服务仍保留核心服务文档。输出为 `/llms.txt` 与 `/components/*.txt`,索引使用适合包内引用的相对链接。不存在的输出目录会自动创建,不会清空已有内容;仅删除带生成器标记的过期文件,无标记文件与子目录会保留。 +使用 `--core-only` 时,不读取 Server 的 `docs.json`、示例文件或扩展仓库及解决方案。组件索引按 `Components` 下的第一级目录分组。服务从公开、非过时的顶层类型发现:`Services` 下的接口、`Components` 下以 `Service` 或 `Provider` 结尾的接口,以及这两个目录下以 `Service` 结尾且尚未识别为组件的公开非静态类。这些是服务相关 API,不一定都由依赖注入注册;名称冲突会导致生成失败,避免覆盖文档。不生成扩展文档、扩展索引章节或链接。输出为 `/llms.txt` 与 `/components/*.txt`,索引使用适合包内引用的相对链接。不存在的输出目录会自动创建,不会清空已有内容;仅删除带生成器标记的过期文件,无标记文件与子目录会保留。 源码工程 `.csproj` 中显式声明的 ``(包括别名和静态导入)会应用到该工程的 C# 文件,不会在合并分析时泄漏到其他工程。 @@ -145,10 +145,11 @@ dotnet tool uninstall --global BootstrapBlazor.LLMsDocsGenerator 生成错误或显式传入空路径时会返回非零进程退出码,便于 MSBuild 和 CI 中止。 -使用 PowerShell 7 执行集成检查;脚本会构建工具,并使用隔离源码夹具调用实际 CLI,验证核心打包与完整官网生成: +构建工具后,使用 PowerShell 7 执行核心模式集成检查: ```powershell -.\tools\BootstrapBlazor.LLMsDocsGenerator\tests\Verify-Generation.ps1 +dotnet build .\tools\BootstrapBlazor.LLMsDocsGenerator -c Release +.\tools\BootstrapBlazor.LLMsDocsGenerator\tests\Verify-CoreOnly.ps1 ``` ### 示例 @@ -180,10 +181,10 @@ dotnet run --project "..\BootstrapBlazor.Extensions\tools\BootstrapBlazor.LLMsDo 在 `BootstrapBlazor` 仓库根目录,将核心文档直接生成到 skill 的 references 目录: ```powershell -dotnet llms-docs --core-only --root "src\BootstrapBlazor.Server" --output "src\BootstrapBlazor\skills\bootstrapblazor\references" +dotnet llms-docs --core-only --output "src\BootstrapBlazor\skills\bb-api\references" ``` -无需再使用移除扩展配置的暂存 `docs.json`。BootstrapBlazor.Server 发布时不要传 `--core-only`,以保持完整官网索引、核心与扩展文档;原有发布命令及输出路径不变。 +无需 `docs.json`。BootstrapBlazor.Server 发布时不要传 `--core-only`,以保持完整官网索引、核心与扩展文档;原有发布命令及输出路径不变。 ## CI/CD 集成