Skip to content

Commit c0422af

Browse files
authored
feat(profiles): support frontmatter-free markdown sources (#466) (#471)
* feat(profiles): support frontmatter-free markdown sources (#466) * fix(profiles): anchor frontmatter detection to the start of the file (#466) The multiline frontmatter pattern let ^--- match any line, so a plain body with two horizontal rules was parsed as frontmatter and the text before the first rule was dropped. Anchor the opening fence with \A and add a regression test. AI assistance: Extra Chill Bot (Claude via Roadie) found and fixed this during review.
1 parent fbfdc5b commit c0422af

7 files changed

Lines changed: 211 additions & 32 deletions

‎README.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,31 @@ segments. Protect roots with filesystem permissions: PHP cannot guarantee an
174174
`openat(2)`-style defense against a concurrent directory replacement immediately
175175
before rename.
176176

177+
### Frontmatter profiles
178+
179+
Select a built-in or registered frontmatter profile with `--profile=<id>`.
180+
`native` preserves WordPress fields; `okf` writes portable Open Knowledge Format
181+
frontmatter. Custom profiles register with
182+
`markdown_db_register_frontmatter_profile( $id, $profile )` and can provide
183+
`import_post_data( array $frontmatter, string $body, array $context )`,
184+
`export_frontmatter( object $post, array $context )`, and
185+
`export_body( object $post, array $context )` callbacks.
186+
187+
The `frontmatter` key accepts `required` (the default) or `optional`. Optional
188+
profiles receive an empty array and the Markdown body for files without YAML
189+
frontmatter (or with an empty block). Required profiles report these files in
190+
the import result's `skipped` list. Returning an empty array from
191+
`export_frontmatter` omits the YAML block entirely; export adds one final LF.
192+
193+
The opt-in `markdown-h1-title` profile imports the first `# ` line as the title,
194+
removes that line and one following blank line, and defaults status to `publish`.
195+
Export writes `# {title}` followed by a blank line and the body, without YAML.
196+
Combine it with a layout profile to derive type, slug, parent and stable source
197+
identity from nested repo paths such as `plugins/foo/docs/user/page.md`. Identity
198+
is retained in WordPress source metadata, not injected into Markdown. Files in
199+
this H1/blank-line format with LF endings and a final newline round-trip
200+
byte-identically; other heading spacing or newline conventions are normalized.
201+
177202
## MySQL/MariaDB import and export
178203

179204
Use `wp markdown-db import` and `wp markdown-db export` (or their abilities) to

‎inc/class-wp-markdown-cli.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,9 @@ static function ( object $a, object $b ): int {
429429
$created = array();
430430
$updated = array();
431431
$skipped = array();
432+
foreach ( $storage->get_skipped_files() as $path => $reason ) {
433+
$skipped[] = array( 'path' => self::relative_path( $path, $content_dir ), 'reason' => $reason );
434+
}
432435
$sample = array();
433436
$create_count = 0;
434437
$update_count = 0;

‎inc/class-wp-markdown-frontmatter-profiles.php‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,11 @@ class WP_Markdown_Frontmatter_Profiles {
2424
/**
2525
* Register a frontmatter profile.
2626
*
27+
* The frontmatter policy is 'required' (default) or 'optional'.
2728
* A profile may provide these callbacks:
2829
* - supports_post( object $post, array $context ): bool
2930
* - export_frontmatter( object $post, array $context ): array
31+
* - export_body( object $post, array $context ): string
3032
* - import_post_data( array $frontmatter, string $body, array $context ): array|object
3133
* - supports_frontmatter( array $frontmatter, string $body, array $context ): bool
3234
*
@@ -36,7 +38,7 @@ class WP_Markdown_Frontmatter_Profiles {
3638
*/
3739
public static function register( string $id, array $profile ): bool {
3840
$id = self::sanitize_id( $id );
39-
if ( '' === $id ) {
41+
if ( '' === $id || ! in_array( $profile['frontmatter'] ?? 'required', array( 'required', 'optional' ), true ) ) {
4042
return false;
4143
}
4244

@@ -133,6 +135,23 @@ public static function resolve_for_import( array $frontmatter, string $body, arr
133135
* Ensure the built-in WordPress-safe profile exists.
134136
*/
135137
private static function ensure_builtin_profiles(): void {
138+
if ( ! isset( self::$profiles['markdown-h1-title'] ) ) {
139+
self::$profiles['markdown-h1-title'] = array(
140+
'id' => 'markdown-h1-title',
141+
'label' => 'Markdown H1 title',
142+
'frontmatter' => 'optional',
143+
'export_frontmatter' => static fn( object $post, array $context ): array => array(),
144+
'export_body' => static fn( object $post, array $context ): string => '# ' . ( $post->post_title ?? '' ) . "\n\n" . ( $post->post_content ?? '' ),
145+
'import_post_data' => static function ( array $frontmatter, string $body ): array {
146+
$title = '';
147+
if ( preg_match( '/^# ([^\n]*)(?:\n(?:\n)?|$)/m', $body, $match, PREG_OFFSET_CAPTURE ) ) {
148+
$title = $match[1][0];
149+
$body = substr_replace( $body, '', $match[0][1], strlen( $match[0][0] ) );
150+
}
151+
return array( 'post_title' => $title, 'post_status' => 'publish', 'post_content' => $body );
152+
},
153+
);
154+
}
136155
if ( isset( self::$profiles[ self::NATIVE_PROFILE ] ) ) {
137156
self::ensure_okf_profile();
138157
return;

‎inc/class-wp-markdown-storage.php‎

Lines changed: 57 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -314,14 +314,7 @@ private function write_post_file( object $post, bool $persist_auto_draft ): stri
314314
// Build frontmatter.
315315
$frontmatter = $this->build_frontmatter( $post );
316316

317-
// Build content.
318-
$content = $post->post_content ?? '';
319-
320-
// Assemble the file.
321-
$output = "---\n";
322-
$output .= WP_Markdown_Yaml::encode_yaml( $frontmatter );
323-
$output .= "---\n\n";
324-
$output .= $content . "\n";
317+
$output = $this->build_file_output( $post, $frontmatter );
325318

326319
$this->observe_file_mutation( $file_path );
327320
$result = file_put_contents( $file_path, $output, LOCK_EX );
@@ -836,7 +829,7 @@ private function write_profile_post( object $post ): string|false {
836829
if ( null === $this->profile_absolute_path( $relative, true ) ) {
837830
return false;
838831
}
839-
$output = "---\n" . WP_Markdown_Yaml::encode_yaml( $frontmatter ) . "---\n\n" . ( $post->post_content ?? '' ) . "\n";
832+
$output = $this->build_file_output( $post, $frontmatter );
840833
$id = (int) ( $post->ID ?? 0 );
841834
$old_path = $id > 0 ? $this->find_file_by_id( $id ) : null;
842835
$tmp_path = $this->stage_profile_write( $file_path, $output );
@@ -1178,7 +1171,19 @@ private function find_file_by_id( int $post_id ): ?string {
11781171
$this->rebuild_index();
11791172
}
11801173

1181-
return $this->index[ $post_id ] ?? null;
1174+
if ( isset( $this->index[ $post_id ] ) ) {
1175+
return $this->index[ $post_id ];
1176+
}
1177+
// Plain Markdown has no embedded ID. Resolve its canonical route from
1178+
// the imported post's source metadata via the layout profile instead.
1179+
if ( $this->profile_enumerates_sources() && function_exists( 'get_post' ) ) {
1180+
$post = get_post( $post_id );
1181+
if ( is_object( $post ) ) {
1182+
$relative = $this->profile_path_for_post( $post );
1183+
return false !== $relative ? $this->profile_absolute_path( $relative ) : null;
1184+
}
1185+
}
1186+
return null;
11821187
}
11831188

11841189
/**
@@ -1375,52 +1380,63 @@ private function parse_file( string $file_path, bool $metadata_only = false ): ?
13751380
}
13761381
}
13771382

1383+
/** @var array<string,string> Files excluded by the active frontmatter policy. */
1384+
private array $skipped_files = array();
1385+
1386+
/** @return array<string,string> Absolute paths mapped to skip reasons. */
1387+
public function get_skipped_files(): array {
1388+
return $this->skipped_files;
1389+
}
1390+
13781391
private function parse_post_file( string $file_path, bool $metadata_only ): ?object {
1379-
if ( $metadata_only ) {
1392+
$context = array(
1393+
'operation' => 'import',
1394+
'file_path' => $file_path,
1395+
'profile' => $this->frontmatter_profile,
1396+
);
1397+
$selected = WP_Markdown_Frontmatter_Profiles::resolve_for_import( array(), '', $context );
1398+
$body_metadata = 'optional' === ( $selected['frontmatter'] ?? 'required' );
1399+
if ( $metadata_only && ! $body_metadata ) {
13801400
// Fast path: read only enough of the file to get the frontmatter.
13811401
// Avoids reading potentially large content bodies during boot.
13821402
$raw = $this->read_frontmatter_only( $file_path );
1403+
if ( false === $raw ) {
1404+
$raw = file_get_contents( $file_path );
1405+
}
13831406
} else {
13841407
$raw = file_get_contents( $file_path );
13851408
}
13861409

1387-
if ( false === $raw || '' === $raw ) {
1410+
if ( false === $raw ) {
13881411
return null;
13891412
}
13901413

1391-
// Split frontmatter and content.
1392-
if ( ! preg_match( '/^---\n(.+?)\n---\n\n?(.*)/s', $raw, $m ) ) {
1393-
return null;
1394-
}
1395-
1396-
$frontmatter = WP_Markdown_Yaml::decode_yaml( $m[1] );
1397-
// write_post() terminates every body with one LF; remove only that terminator.
1398-
$content = $metadata_only ? '' : ( str_ends_with( $m[2], "\n" ) ? substr( $m[2], 0, -1 ) : $m[2] );
1399-
1400-
if ( ! $frontmatter ) {
1414+
// Missing and empty frontmatter are accepted only by an opted-in profile.
1415+
$has_frontmatter = (bool) preg_match( '/\A---\n(.*?)^---\n\n?(.*)/ms', $raw, $m );
1416+
$frontmatter = $has_frontmatter ? (array) WP_Markdown_Yaml::decode_yaml( $m[1] ) : array();
1417+
$body = $has_frontmatter ? $m[2] : $raw;
1418+
// write_post() adds one LF; preserve all other body whitespace.
1419+
$content = str_ends_with( $body, "\n" ) ? substr( $body, 0, -1 ) : $body;
1420+
$profile = WP_Markdown_Frontmatter_Profiles::resolve_for_import( $frontmatter, $content, $context );
1421+
if ( ! $frontmatter && 'optional' !== ( $profile['frontmatter'] ?? 'required' ) ) {
1422+
$this->skipped_files[ $file_path ] = $has_frontmatter ? 'empty_frontmatter' : 'missing_frontmatter';
14011423
return null;
14021424
}
1403-
1404-
$context = array(
1405-
'operation' => 'import',
1406-
'file_path' => $file_path,
1407-
'profile' => $this->frontmatter_profile,
1408-
);
1409-
$profile = WP_Markdown_Frontmatter_Profiles::resolve_for_import( $frontmatter, $content, $context );
1425+
unset( $this->skipped_files[ $file_path ] );
14101426
$data = array();
14111427
if ( ! empty( $profile['import_post_data'] ) && is_callable( $profile['import_post_data'] ) ) {
14121428
$data = (array) call_user_func( $profile['import_post_data'], $frontmatter, $content, array_merge( $context, array( 'profile_id' => $profile['id'] ?? '' ) ) );
14131429
}
14141430

14151431
$post = (object) $data;
1416-
$post->post_content = (string) ( $post->post_content ?? $content );
1432+
$post->post_content = $metadata_only ? '' : (string) ( $post->post_content ?? $content );
14171433
// Derive slug from the filename when the frontmatter has none.
14181434
// Supports the "just drop a file" workflow — an AI agent or git
14191435
// pull creating `wiki/my-topic.md` gets `my-topic` as post_name
14201436
// without needing a slug field. `index.md` files (used when a
14211437
// post has children) fall back to the parent directory name.
14221438
// See GitHub issue #42.
1423-
if ( '' === $post->post_name && '' !== $file_path ) {
1439+
if ( '' === ( $post->post_name ?? '' ) && '' !== $file_path ) {
14241440
$stem = basename( $file_path, '.md' );
14251441
if ( 'index' === $stem ) {
14261442
$stem = basename( dirname( $file_path ) );
@@ -1542,6 +1558,16 @@ private function read_frontmatter_only( string $file_path ) {
15421558
* @param object $post A WordPress post row.
15431559
* @return array Frontmatter key-value pairs.
15441560
*/
1561+
/** Assemble either a YAML document or a plain Markdown body. */
1562+
private function build_file_output( object $post, array $frontmatter ): string {
1563+
$context = array( 'operation' => 'export', 'profile' => $this->frontmatter_profile );
1564+
$profile = WP_Markdown_Frontmatter_Profiles::resolve_for_export( $post, $context );
1565+
$body = is_callable( $profile['export_body'] ?? null )
1566+
? (string) call_user_func( $profile['export_body'], $post, array_merge( $context, array( 'profile_id' => $profile['id'] ?? '' ) ) )
1567+
: (string) ( $post->post_content ?? '' );
1568+
return ( $frontmatter ? "---\n" . WP_Markdown_Yaml::encode_yaml( $frontmatter ) . "---\n\n" : '' ) . $body . "\n";
1569+
}
1570+
15451571
private function build_frontmatter( object $post ): array {
15461572
$native_frontmatter = $this->build_native_frontmatter( $post );
15471573
$context = array(

‎tests/smoke-content-layout-profiles.php‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,46 @@ static function ( string $path ): void {
194194
$failures[] = 'profile paths escaped the content root or claimed state paths';
195195
}
196196

197+
// Repo-backed docs supply hierarchy and identity entirely through their paths.
198+
$plain_source = "# Page title\n\nBody with trailing spaces. \n\n## Details\n\nMore text.\n";
199+
file_put_contents( $root . '/' . $nested_path, $plain_source );
200+
markdown_db_register_content_layout_profile( 'plain-docs-fixture', array(
201+
'enumerate' => static fn(): array => array( 'plugins/foo/docs/user/page.md' ),
202+
'map_source' => static fn( string $path ): array => array( 'post_type' => 'page', 'post_name' => basename( $path, '.md' ), 'post_parent' => 42, 'source_identity' => $path ),
203+
'path_for_post' => static fn(): string => 'plugins/foo/docs/user/page.md',
204+
) );
205+
$plain = new WP_Markdown_Storage( $root );
206+
$plain->set_content_layout_profile( 'plain-docs-fixture' );
207+
$plain->set_frontmatter_profile( 'markdown-h1-title' );
208+
$plain_posts = iterator_to_array( $plain->get_all_posts_iterator() );
209+
$page = $plain_posts[0] ?? null;
210+
if ( ! $page || 'Page title' !== $page->post_title || 'publish' !== $page->post_status || 'page' !== $page->post_name || 42 !== $page->post_parent || 'page' !== $page->post_type || $nested_path !== $page->_source_identity || substr( $plain_source, 14, -1 ) !== $page->post_content ) {
211+
$failures[] = 'plain Markdown did not import title, body, hierarchy and path identity';
212+
} else {
213+
$page->ID = 77;
214+
$plain->write_post( $page );
215+
if ( $plain_source !== file_get_contents( $root . '/' . $nested_path ) || $root . '/' . $nested_path !== $plain->path_for_post( 77 ) ) {
216+
$failures[] = 'plain Markdown export was not byte-identical or indexed by its assigned ID';
217+
}
218+
$again = $plain->read_file( $root . '/' . $nested_path );
219+
if ( $page->post_content !== $again->post_content || $page->post_title !== $again->post_title ) {
220+
$failures[] = 'plain Markdown re-import changed title or content';
221+
}
222+
$metadata = $plain->read_file( $root . '/' . $nested_path, true );
223+
if ( 'Page title' !== $metadata->post_title || '' !== $metadata->post_content ) {
224+
$failures[] = 'plain Markdown metadata read lost its derived title';
225+
}
226+
}
227+
$required = new WP_Markdown_Storage( $root );
228+
$required->set_content_layout_profile( 'plain-docs-fixture' );
229+
$required->set_frontmatter_profile( 'native' );
230+
if ( array() !== iterator_to_array( $required->get_all_posts_iterator() ) || 'missing_frontmatter' !== ( $required->get_skipped_files()[ $root . '/' . $nested_path ] ?? '' ) ) {
231+
$failures[] = 'required-frontmatter exclusion was not reported';
232+
}
233+
if ( markdown_db_register_frontmatter_profile( 'invalid-policy', array( 'frontmatter' => 'sometimes' ) ) ) {
234+
$failures[] = 'invalid frontmatter policy was accepted';
235+
}
236+
197237
if ( ! empty( $failures ) ) {
198238
foreach ( $failures as $failure ) {
199239
echo 'FAIL: ' . $failure . PHP_EOL;

‎tests/smoke-frontmatter-profiles.php‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,36 @@ static function ( int $post_id ): array {
278278
}
279279
}
280280

281+
$plain_storage = new WP_Markdown_Storage( $tmp_root . '/plain' );
282+
$plain_storage->set_frontmatter_profile( 'markdown-h1-title' );
283+
$plain_file = $plain_storage->write_post( (object) array( 'ID' => 80, 'post_type' => 'page', 'post_name' => 'plain', 'post_title' => 'Plain title', 'post_content' => 'Plain body' ) );
284+
if ( ! is_string( $plain_file ) || "# Plain title\n\nPlain body\n" !== file_get_contents( $plain_file ) ) {
285+
$failures[] = 'non-layout write emitted frontmatter for a minimal profile';
286+
}
287+
if ( is_string( $plain_file ) ) {
288+
file_put_contents( $plain_file, "---\n---\n\n# Empty block\n\nBody\n" );
289+
$empty_block = $plain_storage->read_file( $plain_file );
290+
if ( ! $empty_block || 'Empty block' !== $empty_block->post_title || 'Body' !== $empty_block->post_content ) {
291+
$failures[] = 'optional profile did not accept an empty frontmatter block';
292+
}
293+
$plain_storage->set_frontmatter_profile( 'native' );
294+
if ( null !== $plain_storage->read_file( $plain_file ) || 'empty_frontmatter' !== ( $plain_storage->get_skipped_files()[ $plain_file ] ?? '' ) ) {
295+
$failures[] = 'required profile did not report empty frontmatter';
296+
}
297+
}
298+
299+
// Horizontal rules (`---`) inside a plain body must not be mistaken for frontmatter.
300+
$rules_storage = new WP_Markdown_Storage( $tmp_root . '/rules' );
301+
$rules_storage->set_frontmatter_profile( 'markdown-h1-title' );
302+
$rules_file = $tmp_root . '/rules/page/rules.md';
303+
if ( ! is_dir( dirname( $rules_file ) ) ) {
304+
mkdir( dirname( $rules_file ), 0755, true );
305+
}
306+
file_put_contents( $rules_file, "# Rules\n\nIntro\n\n---\n\nMiddle\n\n---\n\nEnd\n" );
307+
$rules_post = $rules_storage->read_file( $rules_file );
308+
if ( ! $rules_post || 'Rules' !== $rules_post->post_title || "Intro\n\n---\n\nMiddle\n\n---\n\nEnd" !== $rules_post->post_content ) {
309+
$failures[] = 'horizontal rules in a plain body were parsed as frontmatter';
310+
}
281311
if ( ! empty( $failures ) ) {
282312
foreach ( $failures as $failure ) {
283313
echo 'FAIL: ' . $failure . PHP_EOL;

‎tests/smoke-mysql-import-export-abilities.php‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,42 @@ static function ( string $content, array $context ): string {
396396
$failures[] = 'dry-run export was incorrectly reported as a failed write';
397397
}
398398

399+
// Exercise the actual import result and source-meta update matching for plain docs.
400+
$GLOBALS['mdi_test_filters']['markdown_db_import_post_content'] = array();
401+
$GLOBALS['mdi_test_filters']['markdown_db_content_format_convert'] = array();
402+
$GLOBALS['mdi_test_posts'] = array();
403+
$GLOBALS['mdi_test_meta'] = array();
404+
$plain_root = $tmp_root . '/plain';
405+
mkdir( $plain_root . '/plugins/foo/docs/user', 0777, true );
406+
$plain_path = $plain_root . '/plugins/foo/docs/user/home.md';
407+
file_put_contents( $plain_path, "# Plain home\n\nPlain body.\n" );
408+
markdown_db_register_content_layout_profile( 'plain-import-fixture', array(
409+
'enumerate' => static fn(): array => array( 'plugins/foo/docs/user/home.md' ),
410+
'map_source' => static fn( string $path ): array => array( 'post_type' => 'page', 'post_name' => 'plain-home', 'source_identity' => $path ),
411+
'path_for_post' => static fn(): string => 'plugins/foo/docs/user/home.md',
412+
) );
413+
$plain_options = array( 'path' => $plain_root, 'layout_profile' => 'plain-import-fixture', 'profile' => 'markdown-h1-title' );
414+
$required_import = WP_Markdown_CLI::import( array_merge( $plain_options, array( 'profile' => 'native' ) ) );
415+
if ( 1 !== $required_import['skipped_count'] || 'missing_frontmatter' !== ( $required_import['skipped'][0]['reason'] ?? '' ) || 'plugins/foo/docs/user/home.md' !== ( $required_import['skipped'][0]['path'] ?? '' ) ) {
416+
$failures[] = 'frontmatter-required CLI import silently dropped a plain file';
417+
}
418+
$plain_import = WP_Markdown_CLI::import( $plain_options );
419+
$plain_id = $plain_import['created'][0]['id'] ?? 0;
420+
$before = $GLOBALS['mdi_test_posts'][ $plain_id ] ?? null;
421+
$repeat = WP_Markdown_CLI::import( $plain_options );
422+
if ( 1 !== $plain_import['create_count'] || 1 !== $repeat['update_count'] || 0 !== $repeat['create_count'] || ! $before || 'Plain home' !== $before->post_title || 'plain-home' !== $before->post_name || 'Plain body.' !== $before->post_content || $before != $GLOBALS['mdi_test_posts'][ $plain_id ] ) {
423+
$failures[] = 'plain docs import/re-import did not update the same source without content changes';
424+
}
425+
$fresh_plain_storage = new WP_Markdown_Storage( $plain_root );
426+
$fresh_plain_storage->set_content_layout_profile( 'plain-import-fixture' );
427+
$fresh_plain_storage->set_frontmatter_profile( 'markdown-h1-title' );
428+
if ( $plain_path !== $fresh_plain_storage->path_for_post( $plain_id ) ) {
429+
$failures[] = 'fresh layout storage could not find a frontmatter-free imported post by ID';
430+
}
431+
$plain_export = WP_Markdown_CLI::export( array_merge( $plain_options, array( 'post_types' => 'page' ) ) );
432+
if ( 1 !== $plain_export['written_count'] || "# Plain home\n\nPlain body.\n" !== file_get_contents( $plain_path ) ) {
433+
$failures[] = 'plain docs CLI export did not reproduce the source bytes';
434+
}
399435
mdi_mysql_import_export_rm_rf( $tmp_root );
400436

401437
if ( ! empty( $failures ) ) {

0 commit comments

Comments
 (0)