Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/cli/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,28 @@ directories.
<path>drafts/*.rst</path>
</exclude>

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

<guides input-format="rst,md">
<exclude>
<path>AGENTS.md</path>
</exclude>
</guides>

* 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
Expand Down
2 changes: 1 addition & 1 deletion packages/guides-cli/src/Command/SettingsBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
9 changes: 7 additions & 2 deletions packages/guides-cli/src/DevServer/RerenderListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand All @@ -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,
Expand Down
20 changes: 18 additions & 2 deletions packages/guides-cli/src/Internal/RunCommandHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -37,6 +38,7 @@
use function array_reduce;
use function array_shift;
use function assert;
use function implode;
use function method_exists;

class RunCommandHandler
Expand All @@ -61,7 +63,7 @@ public function handle(RunCommand $command): array
new ParseDirectoryCommand(
$sourceFileSystem,
'',
$settings->getInputFormat(),
implode(',', $settings->getInputFormats()),
$projectNode,
$this->getExclude($settings, $command->input),
),
Expand All @@ -72,7 +74,7 @@ public function handle(RunCommand $command): array
$sourceFileSystem,
'',
$settings->getInputFile(),
$settings->getInputFormat(),
$this->getInputFileFormat($sourceFileSystem, $settings),
1,
$projectNode,
true,
Expand Down Expand Up @@ -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')) {
Expand Down
21 changes: 19 additions & 2 deletions packages/guides-cli/src/Validation/AnnotationDetails.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
101 changes: 101 additions & 0 deletions packages/guides-cli/tests/unit/Internal/RunCommandHandlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

declare(strict_types=1);

/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link https://phpdoc.org
*/

namespace phpDocumentor\Guides\Cli\Internal;

use League\Tactician\CommandBus;
use phpDocumentor\Guides\Handlers\CompileDocumentsCommand;
use phpDocumentor\Guides\Handlers\ParseFileCommand;
use phpDocumentor\Guides\Nodes\DocumentNode;
use phpDocumentor\Guides\Nodes\ProjectNode;
use phpDocumentor\Guides\Settings\ProjectSettings;
use phpDocumentor\Guides\Twig\Theme\ThemeConfig;
use phpDocumentor\Guides\Twig\Theme\ThemeManager;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
use Twig\Loader\FilesystemLoader;

use function is_dir;
use function mkdir;
use function rmdir;
use function sys_get_temp_dir;
use function touch;
use function uniqid;
use function unlink;

final class RunCommandHandlerTest extends TestCase
{
/** @param list<string> $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, array{string, list<string>, 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'];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, DocumentNode> $tempDocuments keyed by filePath across all collections */
Expand All @@ -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;
Expand All @@ -106,7 +106,7 @@ public function __invoke(PostParseProcess $event): void
$origin,
$sourceDir,
$file,
$inputFormat,
$files->getExtension($file) ?? $inputFormats[0],
1,
$projectNode,
false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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, '/');

Expand All @@ -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;
Expand All @@ -87,7 +87,7 @@ public function __invoke(PostParseProcess $event): void
$origin,
$sourceDir,
$file,
$inputFormat,
$files->getExtension($file) ?? $inputFormats[0],
1,
$projectNode,
false,
Expand Down
Loading
Loading