dewwwald
11/19/2015 - 5:45 AM

FTP for gulp

FTP for gulp

fs           = require "fs"
ftp          = require 'gulp-ftp'

cleanFtpList = () ->
  ftpJsonFile = process.cwd() + '/.ftp.json'
  # clean ftp list
  fs.writeFile ftpJsonFile, JSON.stringify(new Array()), (err) ->
    if(err)
      return gutil.log gutil.colors.red err
    gutil.log(gutil.colors.yellow("Cleaned ftp list..."))


createRemotePath = (item) ->
  item = item.replace('src/', '')
  dir = item.replace /^(.*\/)?([^/]*)$/, (_, dir, file) ->
    return dir
  return dir

gulp.task 'ftp:up', () ->
  ftpJsonFile = process.cwd() + '/.ftp.json'

  cwd = process.cwd()
  fs.readFile ftpJsonFile, 'utf8', (err, data) ->
    if(err)
      gutil.log gutil.colors.red err + ": doing our own thing"
      filearr = new Array()
    else
      filearr = JSON.parse data
    for item in filearr
      uploadPath = createRemotePath(item)
      gulp.src(item)
        .pipe ftp
          host: scrt.ftp.host
          user: scrt.ftp.name
          pass: scrt.ftp.password
          remotePath: uploadPath
        .pipe(gutil.noop());
    item.replace('src/', '')
    return cleanFtpList()
    
addFtp = (e) ->
  filepath = e.path.replace(process.cwd() + '/', "")
  ftpJsonFile = process.cwd() + '/.ftp.json'
  fs.readFile ftpJsonFile, 'utf8', (err, data) ->
    if(err)
      gutil.log gutil.colors.red err + ": doing our own thing"
      filearr = new Array()
    else
      filearr = JSON.parse data

    if filearr.indexOf(filepath) < 0
      filearr.push(filepath)

    filearr = JSON.stringify(filearr)

    fs.writeFile ftpJsonFile, filearr, (err) ->
      if(err)
        return gutil.log gutil.colors.red err
      gutil.log(gutil.colors.yellow(filepath + " saved to ftp list..."))


gulp.task "ftp-watch",  () ->
  gulp.watch ".ftp.json", ["ftp:up"]

gulp.task "watch", ["concat-css", "browser-sync"], () ->
  gulp.watch "#{conf.path.scss}/**/*.scss", ["concat-css"]
  gulp.watch "#{conf.path.coffee}/**/*.coffee", ["concat-js"]
  gulp.watch("src/wp-content/**/*.php", ["bs-reload"]).on 'change', addFtp
  gulp.watch(["src/**/*.css", "src/**/*.js"]).on 'change', addFtp

gulp.task 'live-edit', ['concat-css', 'concat-js', 'watch', 'ftp-watch']