Last active
May 14, 2021 04:57
-
-
Save TellowKrinkle/77c43848727007ac51aea170bf692111 to your computer and use it in GitHub Desktop.
Converts relative C/C++ imports that reference parent folders to absolute imports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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