xiangpengzhao
9/9/2017 - 6:02 AM

This script updates the TOC of a markdown file. Derived from https://github.com/kubernetes/release/blob/master/lib/common.sh

This script updates the TOC of a markdown file. Derived from https://github.com/kubernetes/release/blob/master/lib/common.sh

#!/bin/bash
#
# Copyright 2017 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

file=$1
begin_block="<!-- BEGIN MUNGE: GENERATED_TOC -->"
end_block="<!-- END MUNGE: GENERATED_TOC -->"
tmpfile=/tmp/tmp.md

declare -A count

while read level heading; do
  indent="$(echo $level |sed -e "s,^#,,g" -e 's,#,  ,g')"
  # make a valid anchor
  anchor=${heading,,}
  anchor=${anchor// /-}
  anchor=${anchor//[\.\?\*\,\/\[\]()]/}
  # Keep track of dups and identify
  if [[ -n ${count[$anchor]} ]]; then
    ((count[$anchor]++)) ||true
    anchor+="-${count[$anchor]}"
  else
    # initialize value
    count[$anchor]=0
  fi
  echo "${indent}- [$heading](#$anchor)"
done < <(egrep "^#+ " $file) > $tmpfile

# Insert new TOC
sed -ir "/^$begin_block/,/^$end_block/{
   /^$begin_block/{
	 n
	 r $tmpfile
   }
   /^$end_block/!d
   }" $file

rm -f $tmpfile