blob: e7566f5f83fd8b338aa42cc5778ce9081bda1fca [file] [log] [blame]
Shawn Pearcec9549982015-02-11 13:09:01 -08001// Copyright 2015 Google Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package com.google.gitiles.doc;
16
17import com.google.common.base.Strings;
18
Shawn Pearce374f1842015-02-10 15:36:54 -080019import org.pegdown.ast.HeaderNode;
Shawn Pearcec9549982015-02-11 13:09:01 -080020import org.pegdown.ast.Node;
21import org.pegdown.ast.TextNode;
22
23public class MarkdownHelper {
24 /** Check if anchor URL is like {@code /top.md}. */
25 public static boolean isAbsolutePathToMarkdown(String url) {
26 return url.length() >= 5
27 && url.charAt(0) == '/' && url.charAt(1) != '/'
28 && url.endsWith(".md");
29 }
30
31 /** Combine child nodes as string; this must be escaped for HTML. */
32 public static String getInnerText(Node node) {
33 if (node == null || node.getChildren().isEmpty()) {
34 return null;
35 }
36
37 StringBuilder b = new StringBuilder();
38 appendTextFromChildren(b, node);
39 return Strings.emptyToNull(b.toString().trim());
40 }
41
42 private static void appendTextFromChildren(StringBuilder b, Node node) {
43 for (Node child : node.getChildren()) {
44 if (child instanceof TextNode) {
45 b.append(((TextNode) child).getText());
46 } else {
47 appendTextFromChildren(b, child);
48 }
49 }
50 }
51
Shawn Pearce374f1842015-02-10 15:36:54 -080052 static String getTitle(Node node) {
53 if (node instanceof HeaderNode) {
54 if (((HeaderNode) node).getLevel() == 1) {
55 return getInnerText(node);
56 }
57 return null;
58 }
59
60 for (Node child : node.getChildren()) {
61 String title = getTitle(child);
62 if (title != null) {
63 return title;
64 }
65 }
66 return null;
67 }
68
Shawn Pearcec9549982015-02-11 13:09:01 -080069 private MarkdownHelper() {
70 }
71}