Skip to content

Instantly share code, notes, and snippets.

@TellowKrinkle
Last active May 14, 2021 04:57
Show Gist options
  • Save TellowKrinkle/77c43848727007ac51aea170bf692111 to your computer and use it in GitHub Desktop.
Save TellowKrinkle/77c43848727007ac51aea170bf692111 to your computer and use it in GitHub Desktop.
Converts relative C/C++ imports that reference parent folders to absolute imports
#!/usr/bin/env ruby
require "pathname"
$cwd = Pathname::new(".").expand_path
ARGV.each do |fname|
begin
path = Pathname::new(fname).expand_path
parent = path.parent
content = File.read(path, :encoding => "iso-8859-1")
newcontent = content.gsub(/#include "([^"]+)"/) do |full_include|
inc = Pathname::new($1).expand_path(parent)
if !inc.exist? then
next full_include
end
relative = inc.relative_path_from(parent)
absolute = inc.relative_path_from($cwd)
if absolute.to_s.start_with? ".." then
STDERR.puts "Warning: #{fname} import of #{$1} reaches outside of absolute base directory!"
next full_include
elsif relative.to_s.start_with? ".." then
choice = absolute
else
choice = relative
end
next "\#include \"#{choice}\""
end
if content != newcontent then
File.write(path, newcontent, :encoding => "iso-8859-1")
end
rescue => err
STDERR.puts "Failed to update #{fname}: #{err}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment