clean-header-guards 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/ruby
  2. require 'find'
  3. require 'optparse'
  4. options = {}
  5. OptionParser.new do |opts|
  6. opts.banner = "Usage: clean-header-guards [options]"
  7. opts.on("--prefix [PREFIX]", "Append a header prefix to all guards") do |prefix|
  8. options[:prefix] = prefix
  9. end
  10. end.parse!
  11. IgnoredFilenamePatterns = [
  12. # ignore headers which are known not to have guard
  13. /WebCorePrefix/,
  14. /ForwardingHeaders/,
  15. %r|bindings/objc|,
  16. /vcproj/, # anything inside a vcproj is in the windows wasteland
  17. # we don't own any of these headers
  18. %r|icu/unicode|,
  19. %r|platform/graphics/cairo|,
  20. %r|platform/image-decoders|,
  21. /config.h/ # changing this one sounds scary
  22. ].freeze
  23. IgnoreFileNamesPattern = Regexp.union(*IgnoredFilenamePatterns).freeze
  24. Find::find(".") do |filename|
  25. next unless filename =~ /\.h$/
  26. next if filename.match(IgnoreFileNamesPattern)
  27. File.open(filename, "r+") do |file|
  28. contents = file.read
  29. match_results = contents.match(/#ifndef (\S+)\n#define \1/s)
  30. if match_results
  31. current_guard = match_results[1]
  32. new_guard = File.basename(filename).sub('.', '_')
  33. new_guard = options[:prefix] + '_' + new_guard if options[:prefix]
  34. contents.gsub!(/#{current_guard}\b/, new_guard)
  35. else
  36. puts "Ignoring #{filename}, failed to find existing header guards."
  37. end
  38. tmp_filename = filename + ".tmp"
  39. File.open(tmp_filename, "w+") do |new_file|
  40. new_file.write(contents)
  41. end
  42. File.rename tmp_filename, filename
  43. end
  44. end