Skip to content

Instantly share code, notes, and snippets.

@rosskevin
Last active October 28, 2015 10:41
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save rosskevin/ddfe895091de2ca5f931 to your computer and use it in GitHub Desktop.
Save rosskevin/ddfe895091de2ca5f931 to your computer and use it in GitHub Desktop.
Rakefile - less to sass a.k.a. less2sass or less2scss
# less to scss based on http://stackoverflow.com/a/19167099/2363935
namespace :convert do
task :less_to_scss do
source_glob = "assets/less/*.less"
dest_dir = "converted"
rm_r dest_dir rescue nil
mkdir_p(dest_dir)
file_map = {}
# copy the files
Dir.glob(source_glob).each do |source_file|
# puts "\tWorking on #{source_file}"
basename = File.basename(source_file, '.less')
dest_filename = "_#{basename}.scss"
dest_file = File.join(dest_dir, dest_filename)
# track the file mapping for a replace later
file_map["#{basename}.less"] = dest_filename
cp source_file, dest_file
# convert_file(source_file, dest_file)
end
# do the conversion
Dir.glob("#{dest_dir}/*.scss").each do |file_name|
puts "Converting #{file_name}"
text = File.read(file_name)
# http://stackoverflow.com/a/19167099/2363935
# 1. replace @ with $
text = text.gsub(/@(?!import|media|keyframes|-)/, '$')
# 2. replace mixins
text = text.gsub(/\.([\w\-]*)\s*\((.*)\)\s*\{/, '@mixin \1(\2){')
# 3. replace includes
text = text.gsub(/\.([\w\-]*\s*;)/, '@include \1')
# text = text.gsub(/\.([\w\-]*\(.*\)\s*;)/, '@include \1')
# text = text.gsub(/\.\([a-z0-9-]\+/, '@include \1(/')
# 3. a) replace no param mixin includes with empty parens
text = text.gsub(/@include\ ([\w\-]*\s*;)/, '@include \1()')
# 3. b) I'm terrible with regex, 3a makes a ';()', so fix it
text = text.gsub(/;\(\)/, '();')
# 4. replace string literals
text = text.gsub(/~"(.*)"/, '#{"\1"}')
# 5. replace spin to adjust-hue (function name diff)
text = text.gsub(/spin/, 'adjust-hue')
# 6. replace all the file maps
file_map.each do |less, scss|
text = text.gsub(less, scss)
end
File.open(file_name, 'w') { |file| file.puts text }
end
end
end
@rosskevin
Copy link
Author

3/a/b needs to be rewritten by a more savvy regexer.

@sukima
Copy link

sukima commented Sep 23, 2014

Since the ; is a constant(-ish) why not use it in the output (unless you meant to the be optional):

 text = text.gsub(/@include\ ([\w\-]*\s*);/, '@include \1();')

@mikemaccana
Copy link

For those of us who aren't Ruby developers, can you please give us a hand running this gist? So far I've ran sudo gem install rake, saved this file as Rakefile and ran rake less_to_css:convert, but I get Don't know how to build task 'less_to_css:convert'

@nickmccurdy
Copy link

I believe the command would be rake convert:less_to_css. convert is first because that's the namespace that the less_to_css command is in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment