Skip to content

Instantly share code, notes, and snippets.

@kevbuchanan
Created September 14, 2016 00:19
Show Gist options
  • Save kevbuchanan/8b7b276261edca665f2597da52a6f6ca to your computer and use it in GitHub Desktop.
Save kevbuchanan/8b7b276261edca665f2597da52a6f6ca to your computer and use it in GitHub Desktop.
TS normalize
def normalize(import_statement, file_path)
import_from = import_statement.scan(/(?<=from ').*(?=')/)[0]
from_path = file_path.split('/').reverse
to_path = import_from.split('/')
new_path = []
while !to_path.empty?
case to_path.last
when '.'
new_path << to_path.pop
when '..'
if new_path.last == from_path.last
new_path.pop
to_path.pop
from_path.pop
new_path << '.' if from_path.length == 1
else
new_path << to_path.pop
end
else
new_path << to_path.pop.gsub(".ts", "")
end
end
import_statement.gsub(import_from, new_path.reverse.join('/'))
end
Dir["spec/**/*.ts"].each do |path|
replace = File.readlines(path).reduce([]) do |lines, line|
if line =~ /import.*from/
lines << normalize(line, path)
else
lines << line
end
end
File.open(path, 'w') { |f| f.puts(replace.join) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment