Skip to content

Instantly share code, notes, and snippets.

@shivshank
Created July 19, 2016 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shivshank/e61eb7c5f3dba2160e3783ea07e576ff to your computer and use it in GitHub Desktop.
Save shivshank/e61eb7c5f3dba2160e3783ea07e576ff to your computer and use it in GitHub Desktop.
Count the lines of various files, ignoring lines that start with //

I've written this like a billion times because it's fun. The above code is pretty gross but it works...

It will kind of ignore commented lines, assuming those lines are commented out with //.

import os
from os.path import join
comments = 0
loc = 0
locByExt = {}
totalLines = 0
ignore = ["node_modules", ".git"]
fileExts = [".js", ".json", ".scss", ".pug"]
# this is the stuff relevant for me to throw in here... you can change to your liking
skipFiles = ["showdown.js", "showdown.min.js", "html5shiv.min.js"]
for root, dirs, fileNames in os.walk("."):
newDirs = []
for i in dirs:
if i in ignore:
print("\tskipping directory", i)
else:
newDirs.append(i)
dirs[:] = newDirs
for fileName in fileNames:
currentExt = os.path.splitext(fileName)[1]
if os.path.splitext(fileName)[1] not in fileExts \
or fileName in skipFiles:
print("\tskipping file", fileName)
continue
prevLoc = loc
with open(join(root, fileName), mode='r') as file:
for line in file:
totalLines += 1
if line.strip().startswith("//"):
comments += 1
elif line.strip() != "":
loc += 1
print("+", loc - prevLoc, "added by", fileName)
locByExt[currentExt] = locByExt.get(currentExt, 0) + loc - prevLoc
print("LOC", loc)
print("Comments", comments)
print("Total lines", totalLines)
import pprint
print("LOC by Ext")
pprint.pprint(locByExt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment