Skip to content

Instantly share code, notes, and snippets.

@brandon-fryslie
Last active April 7, 2016 15:32
Show Gist options
  • Save brandon-fryslie/980bdb1ee22f7b28c20c93b7e5e31f12 to your computer and use it in GitHub Desktop.
Save brandon-fryslie/980bdb1ee22f7b28c20c93b7e5e31f12 to your computer and use it in GitHub Desktop.
Fix Sombrero Imports
#!/usr/bin/env ruby
# Build a map of component names to paths - conveniently, there's a file
# already containing that information
def build_component_map()
text = File.read("#{ENV['HOME']}/projects/sombrero/components/index.js")
text.lines.reduce({}) do |res, line|
if /^\s+(\w+):\s*require\(\'\.([^']*)/ =~ line
key = $1
path = "sombrero/components#{$2}"
res[key] = path
end
res
end
end
def process_file(file_name, component_map)
file_changed = false
text = File.read(file_name)
sombrero_imports = []
new_contents = text.gsub(/^import {([^\}]+)} from 'sombrero'.*$/) do |match|
# Split by comma and trim whitespace
sombrero_imports = $1.split(',').map { |s| s.gsub(/\s/, '') }
# Generate new import statements
lines = sombrero_imports.map do |cmp|
"import #{cmp} from '#{component_map[cmp]}';"
end
file_changed = true
lines.join("\n")
end
# puts new_contents only if there was at least one change
if file_changed
File.write(file_name, new_contents)
fi
end
component_map = build_component_map()
file_paths = Dir["{components,pages}/**/*.js"].map { |file| File.join("#{Dir.pwd}", file) }
file_paths.map do |path|
process_file path, component_map
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment