Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
countlines 2.54 KiB
#!/bin/sh

# This script counts the nr of lines in a C++ header or source file.
# It counts:    total nr of lines
#               nr of pure code lines (code lines containing alphanumeric char)
#               nr of pure comment lines
# It also calculates the percentages of pure lines.
#
# The values are printed on stdout for each file given.
# It -t is given as the first argument, only a total line is printed.
#
# Temporary files are created in a subdirectory of /tmp.
# Normally the subdirectory is deleted at the end, but is kept if -t is given.
# Then the calling script countalllines can copy them to another directory
# for use in a program like sloccount.

# Run as:    countlines [-t] file-names


# Get directory of the script (where the other scripts are as well).
edir=`dirname $0`
if [ "$edir" = "" -o "$edir" = "." ]; then
  edir=`pwd`
else
  edir=`cd $edir > /dev/null; pwd`
fi

# Test if only totals have to be given.
totonly=0
if [ "$1" = "-t" ]; then
  totonly=1
  shift
fi

# Create a temporary directory for this user in the /tmp directory.
dirnm=/tmp/`whoami`_tmp_count_dir
\rm -rf $dirnm
mkdir $dirnm
# Initialize the totals
tot_a=0
tot_b=0
tot_c=0
tot_f=0
# Print header line
if [ $totonly = 0 ]; then
  echo "Lines: total        code          comment"
fi
# Loop through all the source files.
for NM in $*
do
  NMB=`basename $NM`
  # Count total nr of lines
  cnt_a=`wc $NM | awk '{ print $1 }'`
  # Count nr of pure code and comment lines
  $edir/countpurecodecomm $NM > $dirnm/$NMB
  cnt_c=`wc $dirnm/$NMB | awk '{ print $1 }'`
  # Count nr of pure code lines
  # Do this count as the last one, so the result can be used by countalllines.
  $edir/countpurecode $NM > $dirnm/$NMB
  cnt_b=`wc $dirnm/$NMB | awk '{ print $1 }'`
  # Print nr of lines, code lines and comment lines and percentages
  if [ $totonly = 0 ]; then
    echo "$cnt_a $cnt_b $cnt_c $NM" | awk '{ printf "%12d%8d%6.1f%%%8d%6.1f%%   %s\n", $1, $2, 100*$2/$1, $3-$2, 100*($3-$2)/$1, $4 }'
  fi
  # Add to the total
  tot_a=`echo "$tot_a $cnt_a" | awk '{ print $1+$2 }'`
  tot_b=`echo "$tot_b $cnt_b" | awk '{ print $1+$2 }'`
  tot_c=`echo "$tot_c $cnt_c" | awk '{ print $1+$2 }'`
  tot_f=`echo "$tot_f" | awk '{ print $1+1 }'`
done

# Print the totals and an ending line.
# Avoid division by 0.
tot_a1=$tot_a
if [ $tot_a1 = 0 ]; then
  tot_a1 = 1
fi
echo "$tot_a $tot_b $tot_c $tot_f $tot_a1" | awk '{ printf "%12d%8d%6.1f%%%8d%6.1f%%    total %d files\n", $1, $2, 100*$2/$5, $3-$2, 100*($3-$2)/$5, $4 }'
if [ $totonly = 0 ]; then
  echo "Lines: total        code          comment"
  \rm -rf $dirnm
fi