From da6a40f299982a2e160a3d0de725c00b41a555f0 Mon Sep 17 00:00:00 2001 From: Sebastian Mendel Date: Sun, 8 Nov 2026 21:50:09 +0100 Subject: [PATCH] [FEATURE] Render reStructuredText and Markdown files in one project The input-format setting takes a comma-separated list. With "rst,md" every .rst file is parsed as reStructuredText and every .md file as Markdown, in one document tree. A single format behaves as before. Two files that differ only in their extension stop the run with an error naming both. Signed-off-by: Sebastian Mendel --- docs/cli/configuration.rst | 22 ++++ .../src/Command/SettingsBuilder.php | 2 +- .../src/DevServer/RerenderListener.php | 9 +- .../src/Internal/RunCommandHandler.php | 20 ++- .../src/Validation/AnnotationDetails.php | 21 ++- .../unit/Command/SettingsBuilderTest.php | 2 +- .../unit/Internal/RunCommandHandlerTest.php | 101 +++++++++++++++ .../GithubActionsViolationFormatTest.php | 36 ++++++ .../ParseContentTypeListener.php | 6 +- .../EventListener/ParsePagesListener.php | 6 +- packages/guides/src/FileCollector.php | 34 ++++- packages/guides/src/Files.php | 18 ++- .../src/Handlers/ParseDirectoryCommand.php | 8 ++ .../src/Handlers/ParseDirectoryHandler.php | 29 +++-- .../PageHyperlinkResolver.php | 27 +++- .../guides/src/Settings/ProjectSettings.php | 32 ++++- .../guides/tests/unit/FileCollectorTest.php | 55 ++++++++ .../Handlers/ParseDirectoryHandlerTest.php | 121 ++++++++++++++++++ .../PageHyperlinkResolverTest.php | 67 ++++++++++ .../unit/Settings/ProjectSettingsTest.php | 42 ++++++ .../expected/index.html | 29 +++++ .../expected/specs/diagram.svg | 1 + .../expected/specs/spec.html | 15 +++ .../input/AGENTS.md | 4 + .../input/guides.xml | 10 ++ .../input/index.rst | 11 ++ .../input/setup.rst | 5 + .../input/specs/diagram.svg | 1 + .../input/specs/spec.md | 7 + 29 files changed, 706 insertions(+), 35 deletions(-) create mode 100644 packages/guides-cli/tests/unit/Internal/RunCommandHandlerTest.php create mode 100644 packages/guides/tests/unit/Settings/ProjectSettingsTest.php create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/expected/index.html create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/expected/specs/diagram.svg create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/expected/specs/spec.html create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/input/AGENTS.md create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/input/guides.xml create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/input/index.rst create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/input/setup.rst create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/input/specs/diagram.svg create mode 100644 tests/Integration/tests/configuration/config-mixed-input-formats/input/specs/spec.md diff --git a/docs/cli/configuration.rst b/docs/cli/configuration.rst index 3051b799d..73f0cce04 100644 --- a/docs/cli/configuration.rst +++ b/docs/cli/configuration.rst @@ -43,6 +43,28 @@ directories. drafts/*.rst +reStructuredText and Markdown in one project +============================================ + +The ``input-format`` setting takes a comma-separated list. With ``rst,md``, every ``.rst`` file is parsed as +reStructuredText and every ``.md`` file as Markdown. + +.. code-block:: xml + + + + AGENTS.md + + + +* The index file can be written in either format, ``index.rst`` or ``index.md``. +* A link to a page of the other format names its file, with the extension of that format: ``setup.rst`` in a + Markdown link, ``setup.md`` in a reStructuredText hyperlink. +* Two files that differ only in their extension, ``setup.rst`` and ``setup.md``, stop the run with an error; rename or + exclude one. +* Markdown files that are not documentation, like an ``AGENTS.md`` or a ``README.md`` next to the documentation, + become pages as soon as ``md`` is in the list. Exclude them. + .. _violation_formats_ci: Annotations in GitHub Actions and GitLab CI diff --git a/packages/guides-cli/src/Command/SettingsBuilder.php b/packages/guides-cli/src/Command/SettingsBuilder.php index 56f4983a9..fb019642a 100644 --- a/packages/guides-cli/src/Command/SettingsBuilder.php +++ b/packages/guides-cli/src/Command/SettingsBuilder.php @@ -180,7 +180,7 @@ public function configureCommand(Command $command): void 'input-format', null, InputOption::VALUE_REQUIRED, - 'Format of the input can be "RST", or "Markdown"', + 'Input format as file extension: "rst", "md", or a list such as "rst,md"', ); $command->addOption( 'output-format', diff --git a/packages/guides-cli/src/DevServer/RerenderListener.php b/packages/guides-cli/src/DevServer/RerenderListener.php index 9c158124f..89519b90e 100644 --- a/packages/guides-cli/src/DevServer/RerenderListener.php +++ b/packages/guides-cli/src/DevServer/RerenderListener.php @@ -32,9 +32,13 @@ use function array_find_key; use function assert; use function current; +use function pathinfo; use function sprintf; +use function strlen; use function substr; +use const PATHINFO_EXTENSION; + final class RerenderListener { /** @param DocumentNode[] $documents */ @@ -57,14 +61,15 @@ public function __invoke(FileModifiedEvent $event): void $event->path, ), ); - $file = substr($event->path, 0, -4); + $extension = pathinfo($event->path, PATHINFO_EXTENSION); + $file = substr($event->path, 0, -strlen('.' . $extension)); $document = $this->commandBus->handle( new ParseFileCommand( $this->sourceFileSystem, '', $file, - $this->settings->getInputFormat(), + $extension, 1, $this->projectNode, true, diff --git a/packages/guides-cli/src/Internal/RunCommandHandler.php b/packages/guides-cli/src/Internal/RunCommandHandler.php index 122530613..9dfb51973 100644 --- a/packages/guides-cli/src/Internal/RunCommandHandler.php +++ b/packages/guides-cli/src/Internal/RunCommandHandler.php @@ -19,6 +19,7 @@ use Flyfinder\Specification\OrSpecification; use Flyfinder\Specification\SpecificationInterface; use League\Tactician\CommandBus; +use phpDocumentor\FileSystem\FileSystem; use phpDocumentor\FileSystem\Finder\Exclude; use phpDocumentor\FileSystem\FlySystemAdapter; use phpDocumentor\Guides\Compiler\CompilerContext; @@ -37,6 +38,7 @@ use function array_reduce; use function array_shift; use function assert; +use function implode; use function method_exists; class RunCommandHandler @@ -61,7 +63,7 @@ public function handle(RunCommand $command): array new ParseDirectoryCommand( $sourceFileSystem, '', - $settings->getInputFormat(), + implode(',', $settings->getInputFormats()), $projectNode, $this->getExclude($settings, $command->input), ), @@ -72,7 +74,7 @@ public function handle(RunCommand $command): array $sourceFileSystem, '', $settings->getInputFile(), - $settings->getInputFormat(), + $this->getInputFileFormat($sourceFileSystem, $settings), 1, $projectNode, true, @@ -107,6 +109,20 @@ public function handle(RunCommand $command): array return $documents; } + /** + * With several input formats, the format of the input file is the first one a file exists for. + */ + private function getInputFileFormat(FileSystem $sourceFileSystem, ProjectSettings $settings): string + { + foreach ($settings->getInputFormats() as $inputFormat) { + if ($sourceFileSystem->has($settings->getInputFile() . '.' . $inputFormat)) { + return $inputFormat; + } + } + + return $settings->getInputFormat(); + } + private function getExclude(ProjectSettings $settings, InputInterface|null $input = null): Exclude|SpecificationInterface|null { if (method_exists($settings, 'getExcludes')) { diff --git a/packages/guides-cli/src/Validation/AnnotationDetails.php b/packages/guides-cli/src/Validation/AnnotationDetails.php index f95a9bd0e..284b3046a 100644 --- a/packages/guides-cli/src/Validation/AnnotationDetails.php +++ b/packages/guides-cli/src/Validation/AnnotationDetails.php @@ -18,6 +18,7 @@ use Stringable; use function getcwd; +use function is_file; use function is_int; use function is_scalar; use function is_string; @@ -50,12 +51,28 @@ public function getFile(Violation $violation): string|null } $settings = $this->settingsManager->getProjectSettings(); + $path = rtrim($settings->getInput(), '/') . '/' . ltrim($document, '/'); // Depending on where a violation is found, the document is named with or without its extension if (preg_match('/\.(rst|md)$/', $document) !== 1) { - $document .= '.' . $settings->getInputFormat(); + $path .= '.' . $this->getInputFormat($path); } - return self::fromWorkingDirectory(rtrim($settings->getInput(), '/') . '/' . ltrim($document, '/')); + return self::fromWorkingDirectory($path); + } + + /** + * With several input formats, the format of a document is the first one a file exists for. + */ + private function getInputFormat(string $pathWithoutExtension): string + { + $settings = $this->settingsManager->getProjectSettings(); + foreach ($settings->getInputFormats() as $inputFormat) { + if (is_file($pathWithoutExtension . '.' . $inputFormat)) { + return $inputFormat; + } + } + + return $settings->getInputFormat(); } /** diff --git a/packages/guides-cli/tests/unit/Command/SettingsBuilderTest.php b/packages/guides-cli/tests/unit/Command/SettingsBuilderTest.php index 0126f179f..3b4d839ee 100644 --- a/packages/guides-cli/tests/unit/Command/SettingsBuilderTest.php +++ b/packages/guides-cli/tests/unit/Command/SettingsBuilderTest.php @@ -115,7 +115,7 @@ public function testConfigureCommandAddsInputFormatOption(): void self::assertTrue($this->inputDefinition->hasOption('input-format')); $option = $this->inputDefinition->getOption('input-format'); self::assertTrue($option->isValueRequired()); - self::assertSame('Format of the input can be "RST", or "Markdown"', $option->getDescription()); + self::assertSame('Input format as file extension: "rst", "md", or a list such as "rst,md"', $option->getDescription()); } public function testConfigureCommandAddsOutputFormatOption(): void diff --git a/packages/guides-cli/tests/unit/Internal/RunCommandHandlerTest.php b/packages/guides-cli/tests/unit/Internal/RunCommandHandlerTest.php new file mode 100644 index 000000000..a18472fe2 --- /dev/null +++ b/packages/guides-cli/tests/unit/Internal/RunCommandHandlerTest.php @@ -0,0 +1,101 @@ + $existingFiles */ + #[DataProvider('provideInputFiles')] + public function testTheInputFileIsParsedWithTheFormatItExistsIn(string $inputFormat, array $existingFiles, string $expected): void + { + $input = sys_get_temp_dir() . '/guides-run-' . uniqid(); + mkdir($input); + foreach ($existingFiles as $file) { + touch($input . '/' . $file); + } + + $settings = new ProjectSettings(); + $settings->setInput($input); + $settings->setInputFile('spec'); + $settings->setInputFormat($inputFormat); + $settings->setOutput($input . '/output'); + $settings->setOutputFormats([]); + + $extensions = []; + $commandBus = $this->createMock(CommandBus::class); + $commandBus->method('handle')->willReturnCallback( + static function (object $command) use (&$extensions): mixed { + if ($command instanceof ParseFileCommand) { + $extensions[] = $command->getExtension(); + + return new DocumentNode('hash', $command->getFile()); + } + + self::assertInstanceOf(CompileDocumentsCommand::class, $command); + + return $command->getDocuments(); + }, + ); + + $themeManager = new ThemeManager(new FilesystemLoader(), []); + $themeManager->registerTheme(new ThemeConfig('default', [])); + + try { + (new RunCommandHandler($commandBus, $themeManager, new NullLogger())) + ->handle(new RunCommand($settings, new ProjectNode(), null)); + } finally { + foreach ($existingFiles as $file) { + unlink($input . '/' . $file); + } + + if (is_dir($input . '/output')) { + rmdir($input . '/output'); + } + + rmdir($input); + } + + self::assertSame([$expected], $extensions); + } + + /** @return iterable, string}> */ + public static function provideInputFiles(): iterable + { + yield 'one format' => ['rst', ['spec.rst'], 'rst']; + yield 'second of two formats' => ['rst,md', ['spec.md'], 'md']; + yield 'first of two formats' => ['rst,md', ['spec.rst'], 'rst']; + yield 'no file, first format' => ['rst,md', [], 'rst']; + } +} diff --git a/packages/guides-cli/tests/unit/Validation/GithubActionsViolationFormatTest.php b/packages/guides-cli/tests/unit/Validation/GithubActionsViolationFormatTest.php index 32b0cae4f..9178b0a9e 100644 --- a/packages/guides-cli/tests/unit/Validation/GithubActionsViolationFormatTest.php +++ b/packages/guides-cli/tests/unit/Validation/GithubActionsViolationFormatTest.php @@ -23,7 +23,13 @@ use function explode; use function getcwd; +use function mkdir; +use function rmdir; use function rtrim; +use function sys_get_temp_dir; +use function touch; +use function uniqid; +use function unlink; final class GithubActionsViolationFormatTest extends TestCase { @@ -94,6 +100,36 @@ public static function fileProvider(): iterable yield 'absolute input elsewhere' => ['/srv/docs', 'rst', 'index', '/srv/docs/index.rst']; } + public function testWithSeveralInputFormatsTheFileIsTheOneThatExists(): void + { + $input = sys_get_temp_dir() . '/guides-annotation-' . uniqid(); + mkdir($input . '/specs', 0o777, true); + touch($input . '/index.rst'); + touch($input . '/specs/spec.md'); + $this->settings->setInput($input); + $this->settings->setInputFormat('rst,md'); + + try { + $this->format->report(Violation::warning('rst.code-block.empty', 'Empty', ['rst-file' => 'index'])); + $this->format->report(Violation::warning('rst.code-block.empty', 'Empty', ['rst-file' => 'specs/spec'])); + $this->format->report(Violation::warning('rst.code-block.empty', 'Empty', ['rst-file' => 'gone'])); + + self::assertSame( + [ + '::warning file=' . $input . '/index.rst,title=rst.code-block.empty::Empty', + '::warning file=' . $input . '/specs/spec.md,title=rst.code-block.empty::Empty', + '::warning file=' . $input . '/gone.rst,title=rst.code-block.empty::Empty', + ], + $this->finish(), + ); + } finally { + unlink($input . '/index.rst'); + unlink($input . '/specs/spec.md'); + rmdir($input . '/specs'); + rmdir($input); + } + } + public function testPlaceholdersAreReplacedFromTheContext(): void { $this->format->report(Violation::error( diff --git a/packages/guides-pages/src/Pages/EventListener/ParseContentTypeListener.php b/packages/guides-pages/src/Pages/EventListener/ParseContentTypeListener.php index 997b29345..ffcea2259 100644 --- a/packages/guides-pages/src/Pages/EventListener/ParseContentTypeListener.php +++ b/packages/guides-pages/src/Pages/EventListener/ParseContentTypeListener.php @@ -71,7 +71,7 @@ public function __invoke(PostParseProcess $event): void $parseDirectoryCommand = $event->getParseDirectoryCommand(); $origin = $parseDirectoryCommand->getOrigin(); - $inputFormat = $parseDirectoryCommand->getInputFormat(); + $inputFormats = $parseDirectoryCommand->getInputFormats(); $projectNode = $parseDirectoryCommand->getProjectNode(); /** @var array $tempDocuments keyed by filePath across all collections */ @@ -88,7 +88,7 @@ public function __invoke(PostParseProcess $event): void continue; } - $files = $this->fileCollector->collect($origin, $sourceDir, $inputFormat); + $files = $this->fileCollector->collect($origin, $sourceDir, $inputFormats); if ($files->count() === 0) { continue; @@ -106,7 +106,7 @@ public function __invoke(PostParseProcess $event): void $origin, $sourceDir, $file, - $inputFormat, + $files->getExtension($file) ?? $inputFormats[0], 1, $projectNode, false, diff --git a/packages/guides-pages/src/Pages/EventListener/ParsePagesListener.php b/packages/guides-pages/src/Pages/EventListener/ParsePagesListener.php index bc48e0a83..eefe7f498 100644 --- a/packages/guides-pages/src/Pages/EventListener/ParsePagesListener.php +++ b/packages/guides-pages/src/Pages/EventListener/ParsePagesListener.php @@ -60,7 +60,7 @@ public function __invoke(PostParseProcess $event): void { $parseDirectoryCommand = $event->getParseDirectoryCommand(); $origin = $parseDirectoryCommand->getOrigin(); - $inputFormat = $parseDirectoryCommand->getInputFormat(); + $inputFormats = $parseDirectoryCommand->getInputFormats(); $projectNode = $parseDirectoryCommand->getProjectNode(); $sourceDir = ltrim($this->sourceDirectory, '/'); @@ -73,7 +73,7 @@ public function __invoke(PostParseProcess $event): void return; } - $files = $this->fileCollector->collect($origin, $sourceDir, $inputFormat); + $files = $this->fileCollector->collect($origin, $sourceDir, $inputFormats); if ($files->count() === 0) { return; @@ -87,7 +87,7 @@ public function __invoke(PostParseProcess $event): void $origin, $sourceDir, $file, - $inputFormat, + $files->getExtension($file) ?? $inputFormats[0], 1, $projectNode, false, diff --git a/packages/guides/src/FileCollector.php b/packages/guides/src/FileCollector.php index 3bec64520..95b015e4f 100644 --- a/packages/guides/src/FileCollector.php +++ b/packages/guides/src/FileCollector.php @@ -27,12 +27,16 @@ use phpDocumentor\FileSystem\Finder\SpecificationFactoryInterface; use phpDocumentor\FileSystem\Path; use phpDocumentor\FileSystem\StorageAttributes; +use RuntimeException; +use function pathinfo; use function sprintf; use function strlen; use function substr; use function trim; +use const PATHINFO_EXTENSION; + final class FileCollector { /** @var array */ @@ -51,10 +55,14 @@ public function __construct(SpecificationFactoryInterface|null $specificationFac * objects, and avoids adding files to the parse queue that have * not changed and whose direct dependencies have not changed. * + * @param string|list $extension * @param SpecificationInterface|Exclude|null $excludedSpecification specification that is used to exclude specific files/directories. * Passing a {@see SpecificationInterface} is deprecated, use {@see Exclude} instead. + * + * @throws RuntimeException when two files with different extensions name the same document, such as "page.rst" + * and "page.md". */ - public function collect(FilesystemInterface|FileSystem $filesystem, string $directory, string $extension, SpecificationInterface|Exclude|null $excludedSpecification = null): Files + public function collect(FilesystemInterface|FileSystem $filesystem, string $directory, string|array $extension, SpecificationInterface|Exclude|null $excludedSpecification = null): Files { if ($excludedSpecification instanceof SpecificationInterface) { Deprecation::triggerIfCalledFromOutside( @@ -67,14 +75,16 @@ public function collect(FilesystemInterface|FileSystem $filesystem, string $dire ); } + $extensions = (array) $extension; $directory = trim($directory, '/'); - $specification = $this->getSpecification($excludedSpecification, $directory, $extension); + $specification = $this->getSpecification($excludedSpecification, $directory, $extensions); /** @var array $files */ $files = $filesystem->find($specification); // completely populate the splFileInfos property $this->fileInfos = []; + $fileExtensions = []; foreach ($files as $fileInfo) { $dirname = $fileInfo['dirname']; @@ -84,8 +94,19 @@ public function collect(FilesystemInterface|FileSystem $filesystem, string $dire } $documentPath = $this->getFilenameFromFile($fileInfo['filename'], $dirname); + $fileExtension = pathinfo($fileInfo['basename'], PATHINFO_EXTENSION); + + if (isset($fileExtensions[$documentPath]) && $fileExtensions[$documentPath] !== $fileExtension) { + throw new RuntimeException(sprintf( + 'The files "%1$s.%2$s" and "%1$s.%3$s" are both the document "%1$s". Rename or exclude one of them.', + $documentPath, + $fileExtensions[$documentPath], + $fileExtension, + )); + } $this->fileInfos[$documentPath] = $fileInfo; + $fileExtensions[$documentPath] = $fileExtension; } $parseQueue = new Files(); @@ -94,7 +115,7 @@ public function collect(FilesystemInterface|FileSystem $filesystem, string $dire continue; } - $parseQueue->add((string) $filename); + $parseQueue->add((string) $filename, $fileExtensions[$filename]); } return $parseQueue; @@ -121,17 +142,18 @@ private function getFilenameFromFile(string $filename, string $dirname): string return $directory . $filename; } - private function getSpecification(Exclude|SpecificationInterface|null $excludedSpecification, string $directory, string $extension): SpecificationInterface + /** @param list $extensions */ + private function getSpecification(Exclude|SpecificationInterface|null $excludedSpecification, string $directory, array $extensions): SpecificationInterface { if ($excludedSpecification instanceof Exclude) { if ($directory === '') { $directory = new Path('./'); } - return $this->specificationFactory->create([$directory], $excludedSpecification, [$extension]); + return $this->specificationFactory->create([$directory], $excludedSpecification, $extensions); } - $specification = new AndSpecification(new InPath(new \Flyfinder\Path($directory)), new HasExtension([$extension])); + $specification = new AndSpecification(new InPath(new \Flyfinder\Path($directory)), new HasExtension($extensions)); if ($excludedSpecification) { $specification = new AndSpecification($specification, new NotSpecification($excludedSpecification)); } diff --git a/packages/guides/src/Files.php b/packages/guides/src/Files.php index c7c185ac0..e571cda1e 100644 --- a/packages/guides/src/Files.php +++ b/packages/guides/src/Files.php @@ -31,13 +31,29 @@ final class Files implements IteratorAggregate, Countable /** @var string[] */ private array $files = []; - public function add(string $filename): void + /** @var array */ + private array $extensions = []; + + public function add(string $filename, string|null $extension = null): void { if (array_key_exists($filename, $this->files)) { return; } $this->files[$filename] = $filename; + if ($extension === null) { + return; + } + + $this->extensions[$filename] = $extension; + } + + /** + * The extension of the file the document was found in, or null when it was added without one. + */ + public function getExtension(string $filename): string|null + { + return $this->extensions[$filename] ?? null; } /** @return Iterator */ diff --git a/packages/guides/src/Handlers/ParseDirectoryCommand.php b/packages/guides/src/Handlers/ParseDirectoryCommand.php index f7882a0d5..786a22719 100644 --- a/packages/guides/src/Handlers/ParseDirectoryCommand.php +++ b/packages/guides/src/Handlers/ParseDirectoryCommand.php @@ -19,6 +19,7 @@ use phpDocumentor\FileSystem\FileSystem; use phpDocumentor\FileSystem\Finder\Exclude; use phpDocumentor\Guides\Nodes\ProjectNode; +use phpDocumentor\Guides\Settings\ProjectSettings; final class ParseDirectoryCommand { @@ -59,11 +60,18 @@ public function getDirectory(): string return $this->directory; } + /** One file extension, or a comma-separated list such as "rst,md". */ public function getInputFormat(): string { return $this->inputFormat; } + /** @return non-empty-list */ + public function getInputFormats(): array + { + return ProjectSettings::splitInputFormats($this->inputFormat); + } + public function getProjectNode(): ProjectNode { return $this->projectNode; diff --git a/packages/guides/src/Handlers/ParseDirectoryHandler.php b/packages/guides/src/Handlers/ParseDirectoryHandler.php index aae3140f1..d08431bd4 100644 --- a/packages/guides/src/Handlers/ParseDirectoryHandler.php +++ b/packages/guides/src/Handlers/ParseDirectoryHandler.php @@ -58,18 +58,18 @@ public function handle(ParseDirectoryCommand $command): array $origin = $command->getOrigin(); $currentDirectory = $command->getDirectory(); - $extension = $command->getInputFormat(); + $extensions = $command->getInputFormats(); $indexName = $this->getDirectoryIndexFile( $origin, $currentDirectory, - $extension, + $extensions, ); $files = $this->fileCollector->collect( $origin, $currentDirectory, - $extension, + $extensions, match (true) { $command->hasExclude() => $command->getExclude(), $command->hasExcludedSpecification() => $command->getExcludedSpecification(), @@ -82,7 +82,11 @@ public function handle(ParseDirectoryCommand $command): array ); assert($postCollectFilesForParsingEvent instanceof PostCollectFilesForParsingEvent); $documents = []; - foreach ($postCollectFilesForParsingEvent->getFiles() as $file) { + $filesToParse = $postCollectFilesForParsingEvent->getFiles(); + foreach ($filesToParse as $file) { + // A listener that filters the files may build a new Files without extensions. A file it adds that was + // not collected is parsed with the first input format. + $extension = $filesToParse->getExtension($file) ?? $files->getExtension($file) ?? $extensions[0]; $document = $this->commandBus->handle( new ParseFileCommand($origin, $currentDirectory, $file, $extension, 1, $command->getProjectNode(), $indexName === $file), ); @@ -98,13 +102,12 @@ public function handle(ParseDirectoryCommand $command): array return $documents; } + /** @param non-empty-list $extensions */ private function getDirectoryIndexFile( FilesystemInterface|FileSystem $filesystem, string $directory, - string $sourceFormat, + array $extensions, ): string { - $extension = $sourceFormat; - // On macOS filesystems, a file-check against "index.rst" // using $filesystem->has() would return TRUE, when in fact // a file might be stored as "Index.rst". Thus, at this point @@ -125,12 +128,14 @@ private function getDirectoryIndexFile( $indexNamesNotFound = []; foreach ($indexFileNames as $indexName) { - $fullIndexFilename = sprintf('%s.%s', $indexName, $extension); - if (isset($hashedContentFromFilesystem[$fullIndexFilename])) { - return $indexName; - } + foreach ($extensions as $extension) { + $fullIndexFilename = sprintf('%s.%s', $indexName, $extension); + if (isset($hashedContentFromFilesystem[$fullIndexFilename])) { + return $indexName; + } - $indexNamesNotFound[] = $fullIndexFilename; + $indexNamesNotFound[] = $fullIndexFilename; + } } throw new InvalidArgumentException( diff --git a/packages/guides/src/ReferenceResolvers/PageHyperlinkResolver.php b/packages/guides/src/ReferenceResolvers/PageHyperlinkResolver.php index 633823fb0..fb8777b08 100644 --- a/packages/guides/src/ReferenceResolvers/PageHyperlinkResolver.php +++ b/packages/guides/src/ReferenceResolvers/PageHyperlinkResolver.php @@ -13,11 +13,13 @@ namespace phpDocumentor\Guides\ReferenceResolvers; +use phpDocumentor\Guides\Nodes\DocumentTree\DocumentEntryNode; use phpDocumentor\Guides\Nodes\Inline\HyperLinkNode; use phpDocumentor\Guides\Nodes\Inline\LinkInlineNode; use phpDocumentor\Guides\Nodes\Inline\PlainTextInlineNode; use phpDocumentor\Guides\RenderContext; use phpDocumentor\Guides\Renderer\UrlGenerator\UrlGeneratorInterface; +use phpDocumentor\Guides\Settings\SettingsManager; use function count; use function explode; @@ -39,6 +41,7 @@ final class PageHyperlinkResolver implements ReferenceResolver public function __construct( private readonly UrlGeneratorInterface $urlGenerator, private readonly DocumentNameResolverInterface $documentNameResolver, + private readonly SettingsManager|null $settingsManager = null, ) { } @@ -61,7 +64,8 @@ public function resolve(LinkInlineNode $node, RenderContext $renderContext, Mess $canonicalDocumentName = substr($canonicalDocumentName, 0, 0 - strlen('.' . $renderContext->getOutputFormat())); } - $document = $renderContext->getProjectNode()->findDocumentEntry($canonicalDocumentName); + $document = $renderContext->getProjectNode()->findDocumentEntry($canonicalDocumentName) + ?? $this->findDocumentEntryInOtherInputFormat($renderContext, $canonicalDocumentName); if ($document === null) { return false; } @@ -74,6 +78,27 @@ public function resolve(LinkInlineNode $node, RenderContext $renderContext, Mess return true; } + /** Each markup parser removes only its own extension, so "page.rst" in Markdown still has it. */ + private function findDocumentEntryInOtherInputFormat(RenderContext $renderContext, string $canonicalDocumentName): DocumentEntryNode|null + { + $inputFormats = $this->settingsManager?->getProjectSettings()->getInputFormats() ?? []; + if (count($inputFormats) < 2) { + return null; + } + + foreach ($inputFormats as $inputFormat) { + if (!str_ends_with($canonicalDocumentName, '.' . $inputFormat)) { + continue; + } + + return $renderContext->getProjectNode()->findDocumentEntry( + substr($canonicalDocumentName, 0, -strlen('.' . $inputFormat)), + ); + } + + return null; + } + public static function getPriority(): int { return self::PRIORITY; diff --git a/packages/guides/src/Settings/ProjectSettings.php b/packages/guides/src/Settings/ProjectSettings.php index dd395f44e..c362ba5b8 100644 --- a/packages/guides/src/Settings/ProjectSettings.php +++ b/packages/guides/src/Settings/ProjectSettings.php @@ -16,6 +16,13 @@ use phpDocumentor\FileSystem\Finder\Exclude; use Psr\Log\LogLevel; +use function array_filter; +use function array_map; +use function array_unique; +use function array_values; +use function explode; +use function trim; + final class ProjectSettings { /** @var array */ @@ -115,16 +122,39 @@ public function setOutput(string $output): void $this->output = $output; } + /** The first configured input format; see {@see self::getInputFormats()}. */ public function getInputFormat(): string { - return $this->inputFormat; + return $this->getInputFormats()[0]; } + /** @return non-empty-list */ + public function getInputFormats(): array + { + return self::splitInputFormats($this->inputFormat); + } + + /** One file extension, or a comma-separated list such as "rst,md". */ public function setInputFormat(string $inputFormat): void { $this->inputFormat = $inputFormat; } + /** + * @internal + * + * @return non-empty-list + */ + public static function splitInputFormats(string $inputFormat): array + { + $formats = array_values(array_unique(array_filter( + array_map(trim(...), explode(',', $inputFormat)), + static fn (string $format): bool => $format !== '', + ))); + + return $formats === [] ? [$inputFormat] : $formats; + } + public function getLogPath(): string { return $this->logPath; diff --git a/packages/guides/tests/unit/FileCollectorTest.php b/packages/guides/tests/unit/FileCollectorTest.php index 7663fa013..e7515658b 100644 --- a/packages/guides/tests/unit/FileCollectorTest.php +++ b/packages/guides/tests/unit/FileCollectorTest.php @@ -23,6 +23,7 @@ use phpDocumentor\FileSystem\FlySystemAdapter; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; +use RuntimeException; use function sort; @@ -92,6 +93,60 @@ public function testCollectExcludesADirectoryWithEverythingInIt(array $excludedP self::assertSame(['_build-notes', 'index'], $this->sorted($files)); } + public function testCollectRecordsTheExtensionOfEachDocumentWhenCollectingSeveralExtensions(): void + { + $filesystem = new LeagueFilesystem(new InMemoryFilesystemAdapter()); + $filesystem->write('index.rst', ''); + $filesystem->write('specs/spec.md', ''); + $filesystem->write('notes.txt', ''); + + $files = (new FileCollector())->collect( + FlySystemAdapter::createFromFileSystem($filesystem), + '', + ['rst', 'md'], + new Exclude(), + ); + + self::assertSame(['index', 'specs/spec'], $this->sorted($files)); + self::assertSame('rst', $files->getExtension('index')); + self::assertSame('md', $files->getExtension('specs/spec')); + } + + public function testCollectFailsWhenTwoFilesOfDifferentExtensionsAreTheSameDocument(): void + { + $filesystem = new LeagueFilesystem(new InMemoryFilesystemAdapter()); + $filesystem->write('index.rst', ''); + $filesystem->write('guide/setup.rst', ''); + $filesystem->write('guide/setup.md', ''); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessageMatches('~"guide/setup\.(rst|md)" and "guide/setup\.(rst|md)" are both the document "guide/setup"~'); + + (new FileCollector())->collect( + FlySystemAdapter::createFromFileSystem($filesystem), + '', + ['rst', 'md'], + new Exclude(), + ); + } + + public function testCollectWithOneExtensionLeavesFilesOfOtherExtensionsAlone(): void + { + $filesystem = new LeagueFilesystem(new InMemoryFilesystemAdapter()); + $filesystem->write('index.rst', ''); + $filesystem->write('index.md', ''); + + $files = (new FileCollector())->collect( + FlySystemAdapter::createFromFileSystem($filesystem), + '', + 'rst', + new Exclude(), + ); + + self::assertSame(['index'], $this->sorted($files)); + self::assertSame('rst', $files->getExtension('index')); + } + /** @return iterable}> */ public static function provideDirectoryExclusions(): iterable { diff --git a/packages/guides/tests/unit/Handlers/ParseDirectoryHandlerTest.php b/packages/guides/tests/unit/Handlers/ParseDirectoryHandlerTest.php index 1887f061d..f7fc8fbd4 100644 --- a/packages/guides/tests/unit/Handlers/ParseDirectoryHandlerTest.php +++ b/packages/guides/tests/unit/Handlers/ParseDirectoryHandlerTest.php @@ -16,14 +16,24 @@ use Doctrine\Deprecations\Deprecation; use Flyfinder\Path; use Flyfinder\Specification\InPath; +use League\Flysystem\Filesystem as LeagueFilesystem; +use League\Flysystem\InMemory\InMemoryFilesystemAdapter; use League\Tactician\CommandBus; use phpDocumentor\FileSystem\FileSystem; use phpDocumentor\FileSystem\Finder\Exclude; +use phpDocumentor\FileSystem\FlySystemAdapter; +use phpDocumentor\Guides\Event\PostCollectFilesForParsingEvent; use phpDocumentor\Guides\FileCollector; +use phpDocumentor\Guides\Files; +use phpDocumentor\Guides\Nodes\DocumentNode; use phpDocumentor\Guides\Nodes\ProjectNode; use PHPUnit\Framework\TestCase; use Psr\EventDispatcher\EventDispatcherInterface; +use function assert; +use function ksort; +use function str_starts_with; + final class ParseDirectoryHandlerTest extends TestCase { public function testHandlerForwardsExcludeToCollectorWithoutTriggeringSpecificationDeprecation(): void @@ -66,6 +76,117 @@ public function testHandlerForwardsLegacySpecificationWithoutFiringExtraDeprecat ); } + public function testEachFileIsParsedWithTheFormatOfItsExtension(): void + { + $parsed = $this->parseDirectory(['index.md' => '', 'setup.rst' => '', 'specs/spec.md' => ''], 'rst,md'); + + self::assertSame(['index' => 'md', 'setup' => 'rst', 'specs/spec' => 'md'], $parsed); + } + + public function testTheIndexFileCanBeInAnyOfTheInputFormats(): void + { + $roots = []; + $this->parseDirectory(['index.md' => '', 'setup.rst' => ''], 'rst,md', static function (ParseFileCommand $command) use (&$roots): void { + if (!$command->isRoot()) { + return; + } + + $roots[] = $command->getFile() . '.' . $command->getExtension(); + }); + + self::assertSame(['index.md'], $roots); + } + + public function testAListenerThatFiltersTheFilesWithoutTheirExtensionsKeepsTheParserOfEachFile(): void + { + $parsed = $this->parseDirectory( + ['index.rst' => '', 'spec.md' => '', 'Localization.de_DE/index.md' => ''], + 'rst,md', + null, + static function (PostCollectFilesForParsingEvent $event): void { + $files = new Files(); + foreach ($event->getFiles() as $file) { + if (str_starts_with($file, 'Localization.')) { + continue; + } + + $files->add($file); + } + + $event->setFiles($files); + }, + ); + + self::assertSame(['index' => 'rst', 'spec' => 'md'], $parsed); + } + + public function testAFileAddedByAListenerWithoutExtensionIsParsedWithTheFirstInputFormat(): void + { + $parsed = $this->parseDirectory( + ['index.rst' => '', 'spec.md' => ''], + 'rst,md', + null, + static function (PostCollectFilesForParsingEvent $event): void { + $event->getFiles()->add('generated'); + }, + ); + + self::assertSame(['generated' => 'rst', 'index' => 'rst', 'spec' => 'md'], $parsed); + } + + /** + * @param array $files + * @param (callable(ParseFileCommand): void)|null $onParse + * @param (callable(PostCollectFilesForParsingEvent): void)|null $onCollect + * + * @return array the extension each document was parsed with, by document name + */ + private function parseDirectory(array $files, string $inputFormat, callable|null $onParse = null, callable|null $onCollect = null): array + { + $filesystem = new LeagueFilesystem(new InMemoryFilesystemAdapter()); + foreach ($files as $path => $contents) { + $filesystem->write($path, $contents); + } + + $parsed = []; + $commandBus = $this->createMock(CommandBus::class); + $commandBus->method('handle')->willReturnCallback( + static function (object $command) use (&$parsed, $onParse): DocumentNode { + assert($command instanceof ParseFileCommand); + $parsed[$command->getFile()] = $command->getExtension(); + if ($onParse !== null) { + $onParse($command); + } + + return new DocumentNode('hash', $command->getFile()); + }, + ); + + $eventDispatcher = $this->createMock(EventDispatcherInterface::class); + $eventDispatcher->method('dispatch')->willReturnCallback( + static function (object $event) use ($onCollect): object { + if ($onCollect !== null && $event instanceof PostCollectFilesForParsingEvent) { + $onCollect($event); + } + + return $event; + }, + ); + + $handler = new ParseDirectoryHandler(new FileCollector(), $commandBus, $eventDispatcher); + $handler->handle(new ParseDirectoryCommand( + FlySystemAdapter::createFromFileSystem($filesystem), + '', + $inputFormat, + new ProjectNode(), + new Exclude(), + )); + + ksort($parsed); + + return $parsed; + } + private function createCommand(Exclude|InPath|null $exclusion = null): ParseDirectoryCommand { $filesystem = $this->createMock(FileSystem::class); diff --git a/packages/guides/tests/unit/ReferenceResolvers/PageHyperlinkResolverTest.php b/packages/guides/tests/unit/ReferenceResolvers/PageHyperlinkResolverTest.php index a3087777f..6271ca05d 100644 --- a/packages/guides/tests/unit/ReferenceResolvers/PageHyperlinkResolverTest.php +++ b/packages/guides/tests/unit/ReferenceResolvers/PageHyperlinkResolverTest.php @@ -19,6 +19,8 @@ use phpDocumentor\Guides\Nodes\TitleNode; use phpDocumentor\Guides\RenderContext; use phpDocumentor\Guides\Renderer\UrlGenerator\UrlGeneratorInterface; +use phpDocumentor\Guides\Settings\ProjectSettings; +use phpDocumentor\Guides\Settings\SettingsManager; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -66,6 +68,71 @@ public function testDocumentNotFound(): void self::assertEquals('', $node->getUrl()); } + #[DataProvider('provideLinksToAPageOfAnotherInputFormat')] + public function testLinkWithTheExtensionOfAnotherInputFormatFindsThePage(string $input, string $path, string $expected): void + { + $subject = new PageHyperlinkResolver($this->urlGenerator, $this->documentNameResolver, $this->settingsWithInputFormat('rst,md')); + $this->documentNameResolver->expects(self::once())->method('canonicalUrl')->with('', $path)->willReturn($path); + $this->urlGenerator->expects(self::once())->method('generateCanonicalOutputUrl')->with($this->renderContext, 'some-document')->willReturn('some-document.html'); + $node = new HyperLinkNode([], $input); + + self::assertTrue($subject->resolve($node, $this->renderContext, new Messages())); + self::assertSame($expected, $node->getUrl()); + } + + /** @return iterable */ + public static function provideLinksToAPageOfAnotherInputFormat(): iterable + { + yield 'reStructuredText page from Markdown' => [ + 'input' => 'some-document.rst', + 'path' => 'some-document.rst', + 'expected' => 'some-document.html', + ]; + + yield 'Markdown page from reStructuredText, with anchor' => [ + 'input' => 'some-document.md#anchor', + 'path' => 'some-document.md', + 'expected' => 'some-document.html#anchor', + ]; + } + + /** With one input format, a link that still has an extension is resolved as before this lookup existed. */ + #[DataProvider('provideLinksWithAnExtension')] + public function testLinkWithAnExtensionIsNotAPageWithOneInputFormat(string $link): void + { + $subject = new PageHyperlinkResolver($this->urlGenerator, $this->documentNameResolver, $this->settingsWithInputFormat('rst')); + $this->documentNameResolver->expects(self::once())->method('canonicalUrl')->with('', $link)->willReturn($link); + $this->urlGenerator->expects(self::never())->method('generateCanonicalOutputUrl'); + $node = new HyperLinkNode([], $link); + + self::assertFalse($subject->resolve($node, $this->renderContext, new Messages())); + } + + /** @return iterable */ + public static function provideLinksWithAnExtension(): iterable + { + yield 'extension of the input format' => ['some-document.rst']; + yield 'extension of another format' => ['some-document.md']; + } + + public function testLinkWithAnExtensionThatIsNoInputFormatIsNotAPage(): void + { + $subject = new PageHyperlinkResolver($this->urlGenerator, $this->documentNameResolver, $this->settingsWithInputFormat('rst,md')); + $this->documentNameResolver->expects(self::once())->method('canonicalUrl')->with('', 'some-document.txt')->willReturn('some-document.txt'); + $this->urlGenerator->expects(self::never())->method('generateCanonicalOutputUrl'); + $node = new HyperLinkNode([], 'some-document.txt'); + + self::assertFalse($subject->resolve($node, $this->renderContext, new Messages())); + } + + private function settingsWithInputFormat(string $inputFormat): SettingsManager + { + $settings = new ProjectSettings(); + $settings->setInputFormat($inputFormat); + + return new SettingsManager($settings); + } + /** @return string[][] */ public static function pathProvider(): array { diff --git a/packages/guides/tests/unit/Settings/ProjectSettingsTest.php b/packages/guides/tests/unit/Settings/ProjectSettingsTest.php new file mode 100644 index 000000000..1a432f40d --- /dev/null +++ b/packages/guides/tests/unit/Settings/ProjectSettingsTest.php @@ -0,0 +1,42 @@ + $expectedFormats */ + #[DataProvider('provideInputFormats')] + public function testInputFormatsAreReadFromACommaSeparatedList( + string $configured, + string $expectedFormat, + array $expectedFormats, + ): void { + $settings = new ProjectSettings(); + $settings->setInputFormat($configured); + + self::assertSame($expectedFormat, $settings->getInputFormat()); + self::assertSame($expectedFormats, $settings->getInputFormats()); + } + + /** @return iterable}> */ + public static function provideInputFormats(): iterable + { + yield 'one format' => ['md', 'md', ['md']]; + yield 'two formats' => ['rst,md', 'rst', ['rst', 'md']]; + yield 'spaces and repetitions' => [' rst , md ,rst,', 'rst', ['rst', 'md']]; + } +} diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/expected/index.html b/tests/Integration/tests/configuration/config-mixed-input-formats/expected/index.html new file mode 100644 index 000000000..d492dc6f7 --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/expected/index.html @@ -0,0 +1,29 @@ + +
+

Mixed docs

+ +

The specification is written in Markdown: the specification, +its requirements, and Specification.

+ +
+ +
+
+ diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/expected/specs/diagram.svg b/tests/Integration/tests/configuration/config-mixed-input-formats/expected/specs/diagram.svg new file mode 100644 index 000000000..2b692e140 --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/expected/specs/diagram.svg @@ -0,0 +1 @@ + diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/expected/specs/spec.html b/tests/Integration/tests/configuration/config-mixed-input-formats/expected/specs/spec.html new file mode 100644 index 000000000..1a57a9fc3 --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/expected/specs/spec.html @@ -0,0 +1,15 @@ + + +
+

Specification

+ +

See Setup and the start page.

+ +
+

Requirements

+ +

Diagram

+ +
+
+ diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/input/AGENTS.md b/tests/Integration/tests/configuration/config-mixed-input-formats/input/AGENTS.md new file mode 100644 index 000000000..7a66bfa7f --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/input/AGENTS.md @@ -0,0 +1,4 @@ +# Instructions for agents + +This file is excluded in guides.xml and is not part of the documentation. +If it were rendered, [this link](not-a-page.md) would log a warning. diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/input/guides.xml b/tests/Integration/tests/configuration/config-mixed-input-formats/input/guides.xml new file mode 100644 index 000000000..2d4355a88 --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/input/guides.xml @@ -0,0 +1,10 @@ + + + + AGENTS.md + + diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/input/index.rst b/tests/Integration/tests/configuration/config-mixed-input-formats/input/index.rst new file mode 100644 index 000000000..d7cc08a47 --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/input/index.rst @@ -0,0 +1,11 @@ +========== +Mixed docs +========== + +The specification is written in Markdown: `the specification `_, +its `requirements `_, and :doc:`specs/spec`. + +.. toctree:: + + specs/spec + setup diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/input/setup.rst b/tests/Integration/tests/configuration/config-mixed-input-formats/input/setup.rst new file mode 100644 index 000000000..619e06fc0 --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/input/setup.rst @@ -0,0 +1,5 @@ +===== +Setup +===== + +Install the package. diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/input/specs/diagram.svg b/tests/Integration/tests/configuration/config-mixed-input-formats/input/specs/diagram.svg new file mode 100644 index 000000000..2b692e140 --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/input/specs/diagram.svg @@ -0,0 +1 @@ + diff --git a/tests/Integration/tests/configuration/config-mixed-input-formats/input/specs/spec.md b/tests/Integration/tests/configuration/config-mixed-input-formats/input/specs/spec.md new file mode 100644 index 000000000..e4b8dabf7 --- /dev/null +++ b/tests/Integration/tests/configuration/config-mixed-input-formats/input/specs/spec.md @@ -0,0 +1,7 @@ +# Specification + +See [Setup](../setup.rst) and [the start page](../index.rst#mixed-docs). + +## Requirements + +![Diagram](diagram.svg)