1
#!/bin/bash
2
#  or
3
#!/usr/bin/env bash
4
#
5
# compact_comments.sh
6
# Copyright 2008 Ryan Barrett
7
#
8
# Compacts PyBlosxom comment files generated by comments.py into a single file,
9
# per entry. This makes rendering more efficient, particularly for entries with
10
# many comments, since fewer distinct files need to be statted and read from disk.
11
#
12
# For entry XXX, the all comment file will be named XXX-all.cmt.
13
#
14
# Operates on comment files in the current directory. Renames compacted
15
# comment files from *.cmt to *.cmt.compacted, but does not delete them.
16
#
17
# Currently, the .txt entry file suffix and .cmt comment file suffix are hard
18
# coded. If there's demand, they could easily be parameterized.
19
#
20
#
21
# Requires:
22
#
23
# - rename(1) that takes a perl expression, as opposed to fixed before and after
24
#   patterns.
25
#
26
# - xargs(1) that supports the -0 option.
27
#
28
# - find(1) that supports the -print0 option.
29
#
30
# - sed(1), head(1), tail(1), wc(1), expr(1)
31
32
echo 'Compacting all comments...'
33
34
for file in *.txt; do
35
  # filenames and patterns for the comment files for this entry
36
  all_cmt_file=`sed 's/.txt$/-all.cmt/' <<<"$file"`
37
  new_all_cmt_file="${all_cmt_file}.new"
38
  cmt_glob=`sed 's/.txt$/-????*.cmt/' <<<"$file"`
39
40
  # enumerate the comment files ahead of time, so that there's no race condition
41
  # in the globbing for copying their contents and for deleting them.
42
  cmt_files=`find . -maxdepth 1 -name "$cmt_glob"`
43
44
  if [ ! "$cmt_files" ]; then
45
    # no comment files for this entry to compact. skip it.
46
    continue
47
  fi
48
49
  # we know we're going to compact this entry's comments now.
50
  echo "$cmt_files"
51
52
  # write all of the comment files, including any existing -all.cmt file, to an
53
  # -all.cmt.new file.
54
  cat > "$new_all_cmt_file" <<-EOF
55
	<?xml version="1.0" encoding="utf-8"?>
56
	<items>
57
	EOF
58
59
  if [ -f "$all_cmt_file" ]; then
60
    # strip the leading <xml ...> and <items> and trailing </items> lines
61
    lines=`cat "$all_cmt_file" | wc -l`
62
    head -n `expr $lines - 1` "$all_cmt_file" \
63
      | tail -n `expr $lines - 3` \
64
      >> "$new_all_cmt_file"
65
  fi
66
67
  
68
  echo "$cmt_files" | while read cmt_file; do
69
    # strip the leading <xml ...> line
70
    lines=`cat "$cmt_file" | wc -l`
71
    tail -n `expr $lines - 1` "$cmt_file" >> "$new_all_cmt_file" 
72
  done
73
74
  cat >> "$new_all_cmt_file" <<-EOF
75
	</items>
76
	EOF
77
78
  # rename the existing *.cmt files to *.cmt.compacted.
79
  echo "$cmt_files" | while read cmt_file; do
80
    mv "$cmt_file" "${cmt_file}.compacted"
81
  done
82
83
  if [ -f "$all_cmt_file" ]; then
84
    mv "$all_cmt_file" "${all_cmt_file}.compacted"
85
  fi
86
87
  # finally, rename the -all.cmt.new file to -all.cmt.
88
  mv "${new_all_cmt_file}" "${all_cmt_file}"
89
done
90
91
echo '...done! Consider archiving or deleting *.compacted.'