git » homepage.git » master » tree

[master] / tools / index_list.awk

#!/usr/bin/env awk -f
# Generate a nested unordered list of site pages from a list of Markdown files.

function escape_regex(s,    i, c, out, specials) {
  specials = ".^$[]()|*+?{}\\"
  out = ""
  for (i = 1; i <= length(s); i++) {
    c = substr(s, i, 1)
    if (index(specials, c)) {
      out = out "\\" c
    } else {
      out = out c
    }
  }
  return out
}

function indent(depth,    i, s) {
  s = ""
  for (i = 1; i < depth; i++) {
    s = s "  "
  }
  return s
}

function render(node, depth,    i, child, display, link, pad, link_tmp) {
  for (i = 1; i <= child_count[node]; i++) {
    child = children[node, i]
    display = name[child]
    link = href[child]
    pad = indent(depth)

    if (link != "") {
      link_tmp = link
      sub(/\.md$/, ".html", link_tmp)
      link_tmp = "./" link_tmp
      printf("%s<li><a href=\"%s\">%s</a>", pad, link_tmp, display)
    } else {
      printf("%s<li>%s", pad, display)
    }

    if (child_count[child] > 0) {
      printf("\n%s  <ul>\n", pad)
      render(child, depth + 1)
      printf("%s  </ul>\n", pad)
      printf("%s</li>\n", pad)
    } else {
      printf("</li>\n")
    }
  }
}

BEGIN {
  FS = "/"
  pref = prefix
  if (pref != "" && substr(pref, length(pref), 1) != "/") {
    pref = pref "/"
  }
  pref_pattern = escape_regex(pref)
}
{
  rel = $0
  if (pref != "") {
    sub("^" pref_pattern, "", rel)
  }
  base = rel
  gsub(/\.md$/, "", base)

  n = split(base, parts, "/")
  full = ""
  for (i = 1; i <= n; i++) {
    parent = full
    full = (full == "" ? parts[i] : full "/" parts[i])

    if (!(full in seen)) {
      seen[full] = 1
      child_count[parent]++
      children[parent, child_count[parent]] = full
      name[full] = parts[i]
    }

    if (i == n) {
      href[full] = rel
    }
  }
}
END {
  print "<ul class=\"site-index\">"
  render("", 1)
  print "</ul>"
}