Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(front-matter): call extract() functions in any.ts #6390

Merged
Merged
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
29 changes: 12 additions & 17 deletions front_matter/any.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,15 @@
// Copyright 2018-2025 the Deno authors. MIT license.

import { extractAndParse, type Parser, recognize } from "./_shared.ts";
import { parse as parseYaml } from "@std/yaml/parse";
import { parse as parseToml } from "@std/toml/parse";
import { recognize } from "./_shared.ts";
import { extract as extractToml } from "@std/front-matter/toml";
import { extract as extractYaml } from "@std/front-matter/yaml";
import { extract as extractJson } from "@std/front-matter/json";
import type { Extract } from "./types.ts";
import type { Format } from "./test.ts";
import { EXTRACT_REGEXP_MAP } from "./_formats.ts";

export type { Extract };

function getParserForFormat(format: Format): Parser {
switch (format) {
case "yaml":
return parseYaml as Parser;
case "toml":
return parseToml as Parser;
case "json":
return JSON.parse;
}
}

/**
* Extracts and parses {@link https://yaml.org | YAML}, {@link https://toml.io |
* TOML}, or {@link https://www.json.org/ | JSON} from the metadata of front
Expand Down Expand Up @@ -49,7 +39,12 @@ function getParserForFormat(format: Format): Parser {
export function extract<T>(text: string): Extract<T> {
const formats = [...EXTRACT_REGEXP_MAP.keys()] as Format[];
const format = recognize(text, formats);
const regexp = EXTRACT_REGEXP_MAP.get(format) as RegExp;
const parser = getParserForFormat(format);
return extractAndParse(text, regexp, parser);
switch (format) {
case "yaml":
return extractYaml<T>(text);
case "toml":
return extractToml<T>(text);
case "json":
return extractJson<T>(text);
}
}
2 changes: 1 addition & 1 deletion front_matter/toml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ export type { Extract };
* @returns The extracted TOML front matter and body content.
*/
export function extract<T>(text: string): Extract<T> {
return extractAndParse(text, EXTRACT_TOML_REGEXP, parse as Parser);
return extractAndParse<T>(text, EXTRACT_TOML_REGEXP, parse as Parser);
}
Loading