blob: 6d675052e8baef57b1a3d92aca16db1f0c5fbec1 [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
19import org.pegdown.ast.Node;
20import org.pegdown.ast.TextNode;
21
22public class MarkdownHelper {
23 /** Check if anchor URL is like {@code /top.md}. */
24 public static boolean isAbsolutePathToMarkdown(String url) {
25 return url.length() >= 5
26 && url.charAt(0) == '/' && url.charAt(1) != '/'
27 && url.endsWith(".md");
28 }
29
30 /** Combine child nodes as string; this must be escaped for HTML. */
31 public static String getInnerText(Node node) {
32 if (node == null || node.getChildren().isEmpty()) {
33 return null;
34 }
35
36 StringBuilder b = new StringBuilder();
37 appendTextFromChildren(b, node);
38 return Strings.emptyToNull(b.toString().trim());
39 }
40
41 private static void appendTextFromChildren(StringBuilder b, Node node) {
42 for (Node child : node.getChildren()) {
43 if (child instanceof TextNode) {
44 b.append(((TextNode) child).getText());
45 } else {
46 appendTextFromChildren(b, child);
47 }
48 }
49 }
50
51 private MarkdownHelper() {
52 }
53}