|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: Apache-2.0 |
| 3 | + * |
| 4 | + * Copyright 2024 The Enola <https://enola.dev> Authors |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | +package dev.enola.common.io.resource; |
| 19 | + |
| 20 | +import static com.google.common.net.MediaType.HTML_UTF_8; |
| 21 | + |
| 22 | +import static dev.enola.common.io.mediatype.YamlMediaType.YAML_UTF_8; |
| 23 | + |
| 24 | +import com.google.common.collect.ImmutableMap; |
| 25 | + |
| 26 | +import java.io.IOException; |
| 27 | + |
| 28 | +/** |
| 29 | + * MarkdownResource is a {@link MultipartResource} which separates "Front Matter" (as {@link #FRONT} |
| 30 | + * part, typically YAML structured data) and Markdown content (as {@link #BODY}) from the base |
| 31 | + * resource. |
| 32 | + * |
| 33 | + * <p>The "frontmatter" is anything between 2 "---" lines at the very start of the file (if present, |
| 34 | + * it's optional) and the "body" is everything that follows. Any HTML comment before the frontmatter |
| 35 | + * is stripped (this is useful e.g. to ignore license headers). |
| 36 | + * |
| 37 | + * <p>This is very common de-facto standard format used by many Markdown tools. It may (TBC) |
| 38 | + * originally have been <a href="https://jekyllrb.com/docs/front-matter/">introduced by Jekyll</a>. |
| 39 | + */ |
| 40 | +public class MarkdownResource extends RegexMultipartResource { |
| 41 | + |
| 42 | + public static final String FIRST_COMMENT = "comment"; |
| 43 | + public static final String FRONT = "frontmatter"; |
| 44 | + public static final String BODY = "body"; |
| 45 | + |
| 46 | + private static final PartsDef PARTS = |
| 47 | + new PartsDef( |
| 48 | + "(?s)^(?<" |
| 49 | + + FIRST_COMMENT |
| 50 | + + "><!--.*-->)?(\r?\n)*(===\r?\n(?<" |
| 51 | + + FRONT |
| 52 | + + ">.*)===\r?\n)?(\r?\n)*(?<" |
| 53 | + + BODY |
| 54 | + + ">.*)$", |
| 55 | + ImmutableMap.of( |
| 56 | + FIRST_COMMENT, |
| 57 | + HTML_UTF_8.withoutParameters(), |
| 58 | + FRONT, |
| 59 | + YAML_UTF_8.withoutParameters())); |
| 60 | + |
| 61 | + public MarkdownResource(ReadableResource baseResource) throws IOException { |
| 62 | + super(baseResource, PARTS); |
| 63 | + } |
| 64 | +} |
0 commit comments