Skip to content

Instantly share code, notes, and snippets.

@sbeyer
Created October 10, 2015 23:44
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 sbeyer/192324f8a8470ce36b27 to your computer and use it in GitHub Desktop.
Save sbeyer/192324f8a8470ce36b27 to your computer and use it in GitHub Desktop.
Find commented out code in C/C++ files
#!/usr/bin/env ruby
# Tool that attempts to find commented out C++ code
#
# Basic strategy:
# - look for keywords (see CheckRE) in commented out code
# - ignore doxygen comment blocks
#
# Usage: find-code-in-comments.rb <files...>
#
# Author: Stephan Beyer
CheckRE = [
/\balignas\b/,
/\balignof\b/,
/\basm\b/,
/\bbool\b/,
/\bbreak\b\s*;/,
/\bcase\b/,
/\bcatch\b/,
/\bchar\b/,
/\bcompl\b/,
/\bconst\b/,
/\bconst_cast\b/,
/\bconstexpr\b/,
/\bcontinue\b\s*;/,
/\bdecltype\b/,
/\belse\b/,
/\benum\b/,
/\bfloat\b/,
/\bfor\b\s*\(/,
/\bgoto\b/,
/\bif\b\s*\(/,
/\bmutable\b/,
/\bnullptr\b/,
/\breturn\b.*;/,
/\bstatic\b/,
/\bstatic_assert\b/,
/\bstruct\b/,
/\bswitch\b\(/,
/\btemplate\b\s*</,
/\bthrow\b/,
/\btry\b\s*{/,
/\btypedef\b/,
/\btypeid\b/,
/\btypename\b/,
/\busing\b.*;/,
/\bvoid\b/,
/\bwhile\b\s*\(/,
/_cast\b/,
]
def check_for_code(filename, lineno, comment)
# ignore doxygen
return if (comment[0] == '*' and comment[1] != '*') or comment[0] == '!'
notcode = true
CheckRE.each do |regex|
notcode &= (comment =~ regex).nil?
end
puts "#{filename}:#{lineno}" unless notcode
end
def find_code_in_comments(filename)
content = File.open(filename, 'rb') do |file|
file.read
end
line = 1
while not (pos = content =~ %r(/)).nil?
line += content[0..pos].scan(/\n/).length
content.slice!(0..pos)
case content[0]
when '/'
endpos = content =~ /\n/
endpos = -1 if endpos.nil?
check_for_code(filename, line, content[1...endpos])
content.slice!(0...endpos)
when '*'
endpos = content[1..-1] =~ /\*\//
endpos = -1 if endpos.nil?
check_for_code(filename, line, content[1...endpos])
line += content[1..endpos+1].scan(/\n/).length
content.slice!(0..endpos+2)
end
end
end
ARGV.each do |filename|
find_code_in_comments(filename)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment