[HOW-TO] Count Lines of Code within a Project with Cloc š§®
March 29, 2021ā¢352 words
TLDR; Install cloc and run
cloc ./directory
orcloc [options] <file(s)/dir(s)> | <set 1> <set 2> | <report files>
The easiest method to get a breakdown of lines of code is using a script called cloc (Count Lines of Code). It counts blank lines, comments and physical lines of code, and produces a clear output categorized by file type. It's written in Perl, and has no dependencies.
Install Cloc via you're system's package manager, Docker, NPM or manually from source. Cloc is a Perl binary, so you must also have Perl installed on you're system.
E.g. pacman -S cloc
on Arch or apt install cloc
on Debian
Quick start, just run cloc ./path/to/project
Cloc has many additional options, allowing you to get detailed stats Run --help
to see a list of the full options. The command is formatted as so:
cloc [options] <file(s)/dir(s)> | <set 1> <set 2> | <report files>
An example output would look something like this:
āÆ cloc ./sn-web/
201 text files.
201 unique files.
23 files ignored.
github.com/AlDanial/cloc v 1.81 T=2.99 s (61.6 files/s, 17851.7 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
JavaScript 12 7020 2790 27619
TypeScript 74 953 425 9290
Pug 20 5 0 1455
Sass 14 264 45 1351
Ruby 37 197 391 343
YAML 10 91 50 271
HTML 5 25 6 243
Markdown 3 77 0 173
JSON 3 0 0 127
ERB 2 13 0 52
Bourne Shell 1 5 0 29
Dockerfile 1 12 0 20
XML 1 0 0 9
SVG 1 0 0 3
-------------------------------------------------------------------------------
SUM: 184 8662 3707 40985
-------------------------------------------------------------------------------
You can incorporate this into a script to count lines of a remote git repo, with something like:
#!/usr/bin/env bash
git clone --depth 1 "$1" ./temp-repo-cloc &&
printf "('temp-repo-cloc' will be deleted automatically)\n\n\n" &&
cloc temp-repo-cloc &&
rm -rf temp-repo-cloc
Then run ./cloc-count.sh git@github.com:Lissy93/hasami-shogi.git
If you're running this over any JavaScript project, you're going to want to ignore node_modules
and/ or any other large directories of irrelevant files. This can be done with:
cloc --fullpath --not-match-d="(node_modules|App/ios|App/android)" --not-match-f="(yarn\.lock|package\.json|package\-lock\.json)" .