Skip to content

Instantly share code, notes, and snippets.

@rriemann
Created January 26, 2012 16:11
Show Gist options
  • Save rriemann/1683533 to your computer and use it in GitHub Desktop.
Save rriemann/1683533 to your computer and use it in GitHub Desktop.
Help correcting header includes in c++ projects
#!/usr/bin/env ruby
require 'optparse'
require 'pathname'
options = {:root => './'}
optparse = OptionParser.new do |opts|
opts.on('-r', '--root PATH', 'Source Code Root') do |path|
options[:root] = path
end
opts.on('-h', '--help', 'Display this screen') do
puts opts
exit
end
end
begin
optparse.parse!
mandatory = [:root]
missing = mandatory.select{ |param| options[param].nil? }
if not missing.empty?
puts "Missing options: #{missing.join(', ')}"
puts optparse
exit
end
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
puts $!.to_s
puts optparse
exit
end
root = Pathname.new(options[:root]).expand_path
header_files = Dir["#{root.to_s}/**/*.h"].map do |file|
Pathname.new file
end
header_index = {}
gui = Pathname.new "gui"
data = Pathname.new "data"
header_files.each do |header|
filename = header.expand_path.relative_path_from root
if (filename.parent.to_s =~ /#{gui.to_s}/) == 0
filename = filename.relative_path_from gui
elsif (filename.parent.to_s =~ /#{data.to_s}/) == 0
filename = filename.relative_path_from data
end
header_index[header.basename.to_s] = filename
end
Dir["#{root}/**/*.{h,cpp}"].each do |filename|
File.open(filename, "r+") do |file|
buffer = file.readlines
file.rewind
file.truncate 0
buffer.map do |line|
begin
match = line.match(/#include "(.+\.h)"/)
if match and not header_index[match[1]].nil?
line.sub!(/[^"]+.h/, header_index[match[1]].to_s)
end
rescue ArgumentError
puts line
end
line
end
file.puts buffer
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment