Skip to content

Instantly share code, notes, and snippets.

@ibanez270dx
Created October 10, 2015 09:10
Show Gist options
  • Save ibanez270dx/f8da4bda53fa0cd079cd to your computer and use it in GitHub Desktop.
Save ibanez270dx/f8da4bda53fa0cd079cd to your computer and use it in GitHub Desktop.
Compile CoffeeScript & SCSS on save by hooking into Atom's init.coffee
# Your init script
#
# Atom will evaluate this file each time a new window is opened. It is run
# after packages are loaded/activated and after the previous editor state
# has been restored.
fs = require 'fs'
path = require 'path'
nodeCLI = require '/usr/local/lib/node_modules/shelljs-nodecli'
################################################################################
# Compile CoffeeScript & SCSS
################################################################################
# Add your project folder name to enable
# compilation of CoffeeScript and SASS
projects = ["bettr.link"]
atom.workspace.observeTextEditors (editor) ->
editor.onDidSave ->
projectPath = atom.project.getPaths()[0]
projectName = projectPath.split('/').pop()
if projects.indexOf(projectName) >= 0
absPath = editor.getPath()
relPath = absPath.replace projectPath, ''
hasMatch = absPath.match /\.(coffee|scss)$/
if hasMatch?
cmd = switch hasMatch[1]
when "coffee"
cli: 'coffee'
options: '-c --map'
type: 'CoffeeScript'
error: errorParser.coffee
when "scss"
cli: 'scss'
options: '--update'
type: 'SCSS'
error: errorParser.scss
# Conveniently, the extensions are named the same as their CLI
nodeCLI.exec cmd.cli, cmd.options, absPath, (code, response) ->
if code is 1
atom.notifications.addError "#{cmd.type} compilation failed!",
detail: cmd.error(response, { abs: absPath, rel: relPath })
else
atom.notifications.addSuccess "#{cmd.type} compiled successfully!",
detail: "Compiled #{relPath}"
# Parsing functions to diplay compilation
# errors with atom's notification module
errorParser =
coffee: (response, paths) ->
message = response.replace "#{paths.abs}:", ''
matches = message.match /^(\d+):\d+:\s+error:/
"""
Error in #{paths.rel} on line #{matches[1]}:
\n\t\n
#{message.replace(matches[0],'').trim()}
"""
scss: (response, paths) ->
message = response
.replace(/^.+\.scss\s{1}/,'')
.replace(/(^\(|\)+$)/g,'')
.replace(/\s{2,}/,'')
matches = message.match /^Line\s{1}(\d+):\s+/
message = message.replace(new RegExp(matches[0],"ig"),'').split('":')
"""
Error in #{paths.rel} on line #{matches[1]}:
\n\t\n
#{message[0].trim()}:
#{message[1].trim()}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment