Skip to content

Instantly share code, notes, and snippets.

@darcyclarke
Created May 29, 2015 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darcyclarke/355aa8045c2cf9816a3b to your computer and use it in GitHub Desktop.
Save darcyclarke/355aa8045c2cf9816a3b to your computer and use it in GitHub Desktop.
Example Build file
# --------------------------------------
# Setup
# --------------------------------------
server = false
fs = require( 'fs' )
path = require( 'path' )
_ = require( 'underscore' )
wrench = require( 'wrench' )
spawn = require( 'child-process-promise' ).spawn
gulp = require( 'gulp' )
plugins = require( 'gulp-load-plugins' )()
gm = require( 'gm' )
nib = require( 'nib' )
jeet = require( 'jeet' )
exec = require( 'exec' )
jade = require( 'jade' )
yaml = require( 'js-yaml' )
es = require( 'event-stream' )
bower = require( 'main-bower-files' )
request = require( 'request' )
cheerio = require( 'cheerio' )
sprite = require( 'css-sprite' ).stream
wintersmith = require( 'run-wintersmith' )
wintersmith.settings.configFile = 'wintersmith.json';
# --------------------------------------
# Handlers
# --------------------------------------
errorHandler = (error) ->
console.log('Task Error: ', error)
serverHandler = () ->
console.log('Started Server...')
templateHandler = (error) ->
console.log('Template Error: ', error) if error
fileHandler = (error) ->
console.log('File Error: ', error) if error
# --------------------------------------
# Paths
# --------------------------------------
paths =
api : 'http://0.0.0.0:4000/api/'
models : './api/common/models/'
data : './data.yaml'
server : './server.coffee'
bower : './bower_components/'
build :
default : './www/'
templates : './www/'
articles : './www/articles/'
images : './www/assets/images/'
styles : './www/assets/styles/'
scripts : './www/assets/scripts/'
src :
default : './src/'
base : './src/base.jade'
templates : ['./src/**/*.jade','!./src/articles/**/*.jade']
articles : './src/articles/'
images : './src/assets/images/**/*.{gif,png,jpeg,jpg,svg}'
styles : './src/assets/styles/index.styl'
scripts : [
'./src/assets/scripts/libs.coffee'
'./src/assets/scripts/main.coffee'
'./src/assets/scripts/controllers/app.coffee'
'./src/assets/scripts/views/base.coffee'
'./src/assets/scripts/views/home.coffee'
'./src/assets/scripts/views/work.coffee'
'./src/assets/scripts/views/about.coffee'
'./src/assets/scripts/views/contact.coffee'
'./src/assets/scripts/views/articles.coffee'
'./src/assets/scripts/views/speaking.coffee'
'./src/assets/scripts/views/error.coffee'
]
# --------------------------------------
# Defaults
# --------------------------------------
gulp.task('default', ['templates', 'styles', 'scripts'])
# --------------------------------------
# Serve Task
# --------------------------------------
gulp.task 'serve', () ->
# Start Server
plugins.nodemon( script: paths.server, ext: 'html js' )
.on('restart', serverHandler)
# --------------------------------------
# Styles Task
# --------------------------------------
gulp.task 'styles', () ->
gulp.src(paths.src.styles)
.pipe(plugins.stylus(use: [nib()]))
.pipe(plugins.rename('main.min.css'))
.on('error', errorHandler)
.pipe(gulp.dest(paths.build.styles))
.pipe(plugins.livereload( auto: false ))
# --------------------------------------
# Scripts Task
# --------------------------------------
gulp.task 'scripts', () ->
# Bower
gulp.src(bower())
.pipe(plugins.concat('libs.min.js'))
# .pipe(plugins.uglify())
.on('error', errorHandler)
.pipe(gulp.dest(paths.build.scripts))
.pipe(plugins.livereload( auto: false ))
# Application
gulp.src(paths.src.scripts)
.pipe(plugins.coffee( bare: true ))
.pipe(plugins.concat('main.min.js'))
# .pipe(plugins.uglify())
.on('error', errorHandler)
.pipe(gulp.dest(paths.build.scripts))
.pipe(plugins.livereload( auto: false ))
# --------------------------------------
# Articles Task
# --------------------------------------
gulp.task 'articles', () ->
# Cleanup articles directory
gulp.src( paths.build.articles, read: false )
.pipe( plugins.clean() )
# Do wintersmith compilation
wintersmith.build () ->
# Cleanup wintersmith garbage
gulp.src( [ paths.build.articles + '**/*.jade', paths.build.articles + 'plugins' ], read: false )
.pipe( plugins.clean() )
# Create article JavaScript templates
files = wrench.readdirSyncRecursive( paths.build.articles)
files = files.filter ( file ) ->
path.extname( file ) is '.html'
files.forEach ( file ) ->
cheerio( file )
console.log( files )
# --------------------------------------
# Templates Task
# --------------------------------------
gulp.task 'templates', () ->
# Setup
count = 0
data = pretty : true
requests = ['Agencies', 'Enterprises', 'Brands', 'Companies', 'Events', 'Opinions', 'Projects', 'Sites', 'Technologies', 'Awards', 'Charities', 'Publications', 'Startups']
# File Helper Function
find = (path) ->
temp = []
files = fs.readdirSync(path)
for file in files
if file.indexOf('.jade') >= 0
temp.push(path + (file.replace('.jade', '')))
temp
# Useful
useful = (file) ->
file isnt '.DS_Store' and file isnt '.' and file isnt '..'
# Handle Data
handler = () ->
# Find All Project Images and Add Count to Data
projects = fs.readdirSync('./src/assets/images/work/')
# Create Project Lookup
lookup = {}
for project, i in data.projects
do (project, i) ->
lookup[project.key] = i
# Define Image Counts
for project in projects
do (project) ->
return if not useful(project)
images = fs.readdirSync('./src/assets/images/work/' + project)
images.filter (image) ->
useful(image)
if lookup[project]
data.projects[lookup[project]].imageCount = images.length
# Fix Site Reference Data
data.site = data.sites[0]
# Find All Jade Templates
templates = find(paths.src.default)
names = templates.join('.jade ') + '.jade'
# ... goodbye jade templates :(
entityMap =
'&': '&'
'<': '&lt;'
'>': '&gt;'
'"': '&quot;'
"'": '&#39;'
'/': '&#x2F;'
escapeHtml = ( str ) ->
String( str ).replace /[&<>"'\/]/g, ( s ) ->
entityMap[ s ]
# Execute Shell Command
command = "clientjade #{names} > #{paths.build.scripts}templates.min.js"
exec(command, templateHandler)
# Store temporary SVGs
temp = []
# Complex Render Jade Files
data._ = _
data.inlineJadeSVG = ( svg ) ->
inner = fs.readFileSync( './src' + svg, 'utf8' )
temp.push( '"' + svg + '" : "' + encodeURIComponent( inner ) + '"' )
inner
data.title = title
# Setup for rendering
options = pretty: true, locals: data
base = jade.compile(fs.readFileSync(paths.src.base), options)
# Iterate over templates
for file in templates
do (file) ->
return if file.indexOf('base') >= 0
# Store HTML File
path = paths.build.default + file.replace(paths.src.default, '') + '.html'
# Set options for render
content = jade.render(fs.readFileSync(file + '.jade'), data)
# Store content
options.content = content
# Write to HTML file with the content
fs.writeFileSync(path, base(options), {}, fileHandler)
# Write to svg.min.js
fs.writeFileSync( paths.build.scripts + 'svgs.min.js', "var svgs = { #{temp.join(',')} };" )
# Get Live Data
for req in requests
do (req) ->
request paths.api + req, (error, response, body) ->
count++
if not error and response.statusCode is 200
data[req.toLowerCase()] = JSON.parse(body)
handler() if count is requests.length
# --------------------------------------
# Images
# --------------------------------------
gulp.task 'images', () ->
# Default Image Processing
# Generate Images
gulp.src([
'./src/assets/images/{about,home,contact}/**/*.{png,gif,jpeg,jpg}',
'./src/assets/images/*.{png,gif,jpeg,jpg,ico}'
])
.pipe(plugins.if('!**/*.svg', plugins.imagemin()))
.pipe(gulp.dest('./www/assets/images/'))
# gulp images -f=torontostar
# Get Process Arguments
for arg in process.argv
arg = arg + ''
if arg.match(/f/i)
folder = arg.replace('-f=','')
console.log('folder:', folder)
# Streams...
# Find all project folders
files = wrench.readdirSyncRecursive('./src/assets/images/work/')
folders = files.filter (path) ->
!!fs.statSync('./src/assets/images/work/' + path).isDirectory()
# Define the folders to process
folders = [folder] if folder
# Check for Folder Specification
for folder, i in folders
do (folder, i) ->
gulp.src('./src/assets/images/work/' + folder + '/**/*.{png,gif,jpeg,jpg}')
.pipe(plugins.plumber())
.pipe(sprite
name: folder + '-sprite'
style: folder + '.styl'
cssPath: '../images/'
processor: 'stylus'
prefix: folder + '-sprite'
template: './src/assets/styles/sprites.mustache'
)
.pipe(plugins.if('*.{png,gif,jpeg,jpg}', gulp.dest('./www/assets/images/work/')))
.pipe(plugins.if('*.styl', gulp.dest('./src/assets/styles/sprites/')))
# Generate Co-Ordinates
coordinates = {}
wait = 0
folders.forEach (folder) ->
files = wrench.readdirSyncRecursive('./src/assets/images/work/' + folder + '/')
coordinates[folder] = []
files.forEach (file) ->
wait++
gm('./src/assets/images/work/' + folder + '/' + file).size (err, size) ->
wait--
if (!err)
coordinates[folder].push([size.width, size.height])
# Check for Image Sizing to Return
check = () ->
console.log('Waiting for image processing...')
if wait
setTimeout(check, 100)
else
json = JSON.stringify(coordinates)
fs.writeFileSync('./www/coordinates.json', json, {}, fileHandler)
check()
# --------------------------------------
# Watch Task
# --------------------------------------
gulp.task 'watch', () ->
# LiveReload Server
plugins.livereload.listen()
# Watch Files & Kick-off Tasks
gulp.watch(paths.src.templates, ['templates'])
gulp.watch(paths.src.articles + '**/*.{jade,md}', ['articles'])
gulp.watch(paths.src.default + '**/*.styl', ['styles'])
gulp.watch(paths.src.default + '**/*.{coffee,js}', ['scripts'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment